@beeos-ai/bma-dsh-adapter 0.3.0 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ BMA 的共享 DSH 适配层(Apache-2.0)。把 [DSH](https://www.npmjs.com/or
11
11
  | `recovery.ts` + `adapter.ts` | JSONL resume(无日志 → `SessionNotFoundError`)、按 input id 幂等(已记录的输入只发续跑提示) | 一致性套件 resume |
12
12
  | `stop.ts` + `spi.ts` | 停止原因映射:`output_limit_reached` / `context_too_large` / `model_stream_idle`(`TurnStopError`,消息以 `<code>: ` 开头),其余通用失败;`AGENT_ERROR_CODES` / `agentErrorCode` 对应执行端契约码表(`contracts/bma/schemas/agent.json` `AgentErrorCode`) | 一致性套件 stop reasons、`stop-contract.test.ts`、`model-limits.test.ts` |
13
13
  | `system-prompt.ts` | `BASE_SYSTEM_PROMPT` + `composeSystemPrompt(agentSystem?)`:所有外壳在这里拼系统提示,不自己写死 | 一致性套件 system prompt、`system-prompt.test.ts` |
14
- | `model.ts`、`model-catalog.ts` | OpenAI Chat 适配器:按模型取 max_tokens / 窗口(声明 > 目录文件 > 保守默认,记录)、图片 `image_url`、流空闲守卫(首个内容增量前空闲:退避 1–2 s 自动重试 1 次,已有内容后不重试) | `model-limits.test.ts` |
14
+ | `model.ts`、`model-catalog.ts` | OpenAI Chat 适配器:按模型取 max_tokens / 窗口(声明 > 目录文件 > 保守默认,记录)、图片 `image_url`、流空闲守卫(首个内容增量前空闲:退避 1–2 s 自动重试 1 次,已有内容后不重试)、暂时性失败重试(首个内容增量前遇到 HTTP 502/503/504、错误体 `retryable: true` 或响应前连接失败:最多重试 2 次,退避从 0.5 s 翻倍、上限 8 s、减最多 25% 抖动,同官方 OpenAI / Anthropic SDK;服务端给了 `retry-after-ms` / `Retry-After` 且比退避长时按它等,超过 8 s 则不等、直接失败;已有内容后不重试;宿主经 `ModelPort.transientRetry` 计数记日志,原因只含状态码和错误码,不含响应体和令牌) | `model-limits.test.ts` |
15
15
  | `spi.ts` | `HarnessAdapter` / `ModelPort` / `PlatformTool` 契约(harness 无关) | — |
16
16
 
17
17
  审批的等待逻辑(interaction.request/response、停机时保持打开)属于宿主的通道,留在宿主里。
package/lib/adapter.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type CompactReceipt, type CompactRequest } from "./context-store.ts";
1
2
  import type { Context } from "@deepseek-ai/cordis";
2
3
  import { type HarnessAdapter, type HarnessCapabilities, type HarnessEvent, type HarnessInput, type ModelPort, type PlatformTool, type SessionInit } from "./spi.ts";
3
4
  import { type InputSkillDocument, type InputSkillReceipt } from "./input-skills.ts";
@@ -9,16 +10,24 @@ export interface DshAdapterOptions {
9
10
  streamIdleMs?: number;
10
11
  /** Pause range (ms) before the one retry of a stream that idled before any content; default 1000..2000. */
11
12
  idleRetryBackoffMs?: readonly [number, number];
13
+ /** [first, cap] (ms) of the backoff before a transient retry (502/503/504, retryable, connection); default 500..8000. */
14
+ transientRetryBackoffMs?: readonly [number, number];
12
15
  }
13
16
  export declare class DshAdapter implements HarnessAdapter {
14
17
  readonly id = "dsh";
15
18
  /** The dsh kernel (exposed for the fail-closed gate tests). */
16
19
  readonly ctx: Context;
17
20
  private readonly sessions;
21
+ private readonly logicalSessions;
22
+ private readonly contexts;
23
+ private readonly retired;
24
+ private disposal?;
18
25
  private tools;
19
26
  private readonly streamIdleMs;
20
27
  private readonly idleRetryBackoffMs;
28
+ private readonly transientRetryBackoffMs;
21
29
  private port;
30
+ private model;
22
31
  private readonly toolImages;
23
32
  private constructor();
24
33
  static mount(options: DshAdapterOptions): Promise<DshAdapter>;
@@ -28,6 +37,7 @@ export declare class DshAdapter implements HarnessAdapter {
28
37
  createSession(init: SessionInit): Promise<void>;
29
38
  resumeSession(init: SessionInit): Promise<void>;
30
39
  private open;
40
+ private attach;
31
41
  private get;
32
42
  /**
33
43
  * The session's host tools from now on (AgentTurnConfig.host_tools of the
@@ -44,7 +54,13 @@ export declare class DshAdapter implements HarnessAdapter {
44
54
  /** Cancelled accepted work may never enter submitInput. Release only its idle preparation. */
45
55
  clearPreparedInputSkills(sessionId: string, inputId: string): void;
46
56
  submitInput(sessionId: string, input: HarnessInput, signal: AbortSignal): AsyncIterable<HarnessEvent>;
47
- /** Text-only input only: the host queues an input with images as the next turn instead. */
57
+ /**
58
+ * Steers the running input (agent.steering): DSH reads the input at its
59
+ * next step boundary, after the results of the current tool calls and
60
+ * before the next model request; a reply without tool calls does not end
61
+ * the turn while steering is pending. Text-only: the host runs an input
62
+ * with images after the running one instead.
63
+ */
48
64
  appendInput(sessionId: string, input: HarnessInput): void;
49
65
  /**
50
66
  * Whether this build can take image input: the attachment service decodes
@@ -65,8 +81,15 @@ export declare class DshAdapter implements HarnessAdapter {
65
81
  text: string;
66
82
  }[];
67
83
  checkpoint(sessionId: string): Promise<void>;
84
+ /** Internal primitive only. Public capability stays closed until platform
85
+ * reservation, maintenance-only model authority and RPC receipts are wired. */
86
+ compact(sessionId: string, request: CompactRequest, signal: AbortSignal): Promise<CompactReceipt>;
87
+ compactReceipt(sessionId: string, request: CompactRequest): CompactReceipt | undefined;
88
+ abortCompact(sessionId: string, request: CompactRequest): CompactReceipt | undefined;
89
+ private compactShadow;
68
90
  close(sessionId: string): Promise<void>;
69
91
  dispose(): Promise<void>;
92
+ private disposeOnce;
70
93
  private onSessionEvent;
71
94
  private onStreamFrame;
72
95
  }
package/lib/adapter.js CHANGED
@@ -1,5 +1,17 @@
1
+ // DSH adapter: one dsh agent per platform session, assembled from the dsh
2
+ // npm libraries (ADR 0004 option B). Its tool catalog is the platform tools
3
+ // and nothing else — restrict({ allow: [] }) masks every global tool before
4
+ // the platform tools are registered into the agent scope (superduck OMA
5
+ // oma-brain-dsh/src/sandbox-tools/index.ts:37-53, design only).
6
+ //
7
+ // The dsh session id is the platform session id; user message ids are
8
+ // platform input ids. The transcript is dsh's own session log (JSONL backend
9
+ // under home/sessions); externalizing it means mounting another dsh
10
+ // session-persistence backend in kernel.ts.
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { ContextNotPublishedError, ContextStore } from "./context-store.js";
1
13
  import { MessageId, freezeMessage } from "@deepseek-ai/dsh-llm";
2
- import { SessionId } from "@deepseek-ai/dsh-session";
14
+ import { SessionId, SessionLogOffset, buildForkSeed } from "@deepseek-ai/dsh-session";
3
15
  import {} from "./spi.js";
4
16
  import { prepareInputSkills } from "./input-skills.js";
5
17
  import { AsyncQueue } from "./async-queue.js";
@@ -11,47 +23,72 @@ import { mountKernel } from "./kernel.js";
11
23
  import { ChatCompletionsAdapter, DEFAULT_STREAM_IDLE_MS, PROVIDER, RecentToolImages } from "./model.js";
12
24
  import { stopForTurnEnd } from "./stop.js";
13
25
  /**
14
- * Target size of an image in a model request (no industry basis): long edge
15
- * 2048 px, 3.75 MiB encoded — under the 5 MB per-image limit of the common
16
- * vision APIs after base64 expansion is not guaranteed, but the platform
17
- * endpoint answers an oversized request with an error rather than dropping it.
26
+ * Target size of a user image in a model request: long edge 1568 px (Anthropic
27
+ * vision guide: larger images are scaled down by the model anyway), re-encoded
28
+ * (JPEG, WebP when it has alpha) to at most 1 MiB, so three of them stay well
29
+ * inside the request body budget (MAX_REQUEST_BODY_BYTES). Tool screenshots
30
+ * arrive already scaled by the executor SDK and are not re-encoded: the
31
+ * model's coordinates are pixels of the image the executor sent.
18
32
  */
19
- const REQUEST_IMAGE_TARGET = { width: 2048, height: 2048, maxBytes: 3_932_160 };
33
+ const REQUEST_IMAGE_TARGET = { width: 1568, height: 1568, maxBytes: 1 << 20 };
20
34
  const PROBE_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
21
35
  export class DshAdapter {
22
36
  id = "dsh";
23
37
  /** The dsh kernel (exposed for the fail-closed gate tests). */
24
38
  ctx;
25
39
  sessions = new Map();
40
+ logicalSessions = new Map();
41
+ contexts;
42
+ retired = new Set();
43
+ disposal;
26
44
  tools = [];
27
45
  streamIdleMs;
28
46
  idleRetryBackoffMs;
47
+ transientRetryBackoffMs;
29
48
  port;
49
+ model;
30
50
  toolImages = new RecentToolImages();
31
- constructor(ctx, streamIdleMs, idleRetryBackoffMs) {
51
+ constructor(ctx, streamIdleMs, contexts, idleRetryBackoffMs, transientRetryBackoffMs) {
52
+ this.contexts = contexts;
32
53
  this.ctx = ctx;
33
54
  this.streamIdleMs = streamIdleMs;
34
55
  this.idleRetryBackoffMs = idleRetryBackoffMs;
56
+ this.transientRetryBackoffMs = transientRetryBackoffMs;
35
57
  }
36
58
  static async mount(options) {
37
59
  const ctx = await mountKernel({ home: options.home, ...(options.maxParallelToolCalls !== undefined ? { maxParallelToolCalls: options.maxParallelToolCalls } : {}) });
38
- return new DshAdapter(ctx, options.streamIdleMs ?? DEFAULT_STREAM_IDLE_MS, options.idleRetryBackoffMs);
60
+ return new DshAdapter(ctx, options.streamIdleMs ?? DEFAULT_STREAM_IDLE_MS, new ContextStore(options.home), options.idleRetryBackoffMs, options.transientRetryBackoffMs);
39
61
  }
40
62
  capabilities() {
41
- return { resume: true, deltas: true, midTurnInput: true, imageInput: true };
63
+ return { resume: true, deltas: true, steering: true, imageInput: true };
42
64
  }
43
65
  configureModel(port) {
44
66
  this.port = port;
45
67
  const attachments = this.ctx.attachments;
46
- this.ctx.llm.registerAdapter([PROVIDER], new ChatCompletionsAdapter(port, {
68
+ const logical = (sid) => this.logicalSessions.get(sid) ?? sid;
69
+ const routed = {
70
+ limits: model => port.limits(model),
71
+ route: sid => port.route(logical(sid)),
72
+ firstChunk: (sid, ms) => port.firstChunk(logical(sid), ms),
73
+ usage: (sid, value) => port.usage(logical(sid), value),
74
+ ...(port.idleRetry ? { idleRetry: (sid, result) => port.idleRetry(logical(sid), result) } : {}),
75
+ ...(port.transientRetry ? { transientRetry: (sid, result, reason) => port.transientRetry(logical(sid), result, reason) } : {}),
76
+ ...(port.requestReduced ? { requestReduced: (sid, reduction) => port.requestReduced(logical(sid), reduction) } : {}),
77
+ };
78
+ const model = this.model = new ChatCompletionsAdapter(routed, {
47
79
  streamIdleMs: this.streamIdleMs,
48
80
  ...(this.idleRetryBackoffMs ? { idleRetryBackoffMs: this.idleRetryBackoffMs } : {}),
49
- toolImages: (sessionId, callId) => this.toolImages.get(sessionId, callId),
81
+ ...(this.transientRetryBackoffMs ? { transientRetryBackoffMs: this.transientRetryBackoffMs } : {}),
82
+ toolImages: (sessionId, callId) => this.toolImages.get(logical(sessionId), callId),
50
83
  readImage: async (block, signal) => {
51
84
  const image = await attachments.readImageRequest(block.attachment, REQUEST_IMAGE_TARGET, signal);
52
85
  return { mediaType: image.mediaType, data: Buffer.from(image.data).toString("base64") };
53
86
  },
54
- }));
87
+ });
88
+ this.ctx.llm.registerAdapter([PROVIDER], model);
89
+ // Registered after compaction-basic and image offload, so it sees a size failure only when
90
+ // neither recovered it: the model adapter then retries with its last-resort levels.
91
+ this.ctx.on("agent/request-error", ({ agent, failure, signal }, next) => !signal.aborted && model.lastResort(String(agent.session.id), failure.code) ? Promise.resolve({ kind: "retry" }) : next());
55
92
  }
56
93
  registerTools(tools) {
57
94
  this.tools = tools;
@@ -60,14 +97,27 @@ export class DshAdapter {
60
97
  return this.open(init, false);
61
98
  }
62
99
  async resumeSession(init) {
63
- await assertResumable(this.ctx, init.sessionId);
100
+ await assertResumable(this.ctx, this.contexts.current(init.sessionId).physicalId);
64
101
  return this.open(init, true);
65
102
  }
66
103
  async open(init, resume) {
67
104
  if (this.sessions.has(init.sessionId))
68
105
  throw new Error(`session ${init.sessionId} is already open`);
69
- const sessionId = SessionId(init.sessionId);
70
- const state = { init, hostTools: { tools: [], dispose: [] } };
106
+ const source = this.contexts.current(init.sessionId);
107
+ const state = { init, physicalId: source.physicalId, hostTools: { tools: [], dispose: [] } };
108
+ await this.attach(state, resume);
109
+ // Another host may have published while this resume waited for the old
110
+ // transcript writer. Never start a turn from a stale physical context.
111
+ if (this.contexts.current(init.sessionId).physicalId !== source.physicalId) {
112
+ await state.handle.dispose();
113
+ this.logicalSessions.delete(source.physicalId);
114
+ throw new Error("context version changed during resume");
115
+ }
116
+ this.sessions.set(init.sessionId, state);
117
+ }
118
+ async attach(state, resume, seed, parentSession) {
119
+ const { init, physicalId } = state;
120
+ const sessionId = SessionId(physicalId);
71
121
  const setup = (scope) => {
72
122
  state.scope = scope;
73
123
  scope.systemPrompt.section({ name: "bma", order: 0, complete: true, interpolate: false, text: () => state.init.systemPrompt + (state.inputSkills?.system ?? "") });
@@ -79,15 +129,23 @@ export class DshAdapter {
79
129
  scope.on("agent/assistant-stream", ({ frame }) => this.onStreamFrame(state, frame));
80
130
  };
81
131
  const options = { agentOptions: { provider: PROVIDER, model: init.model }, setup };
82
- state.handle = resume
83
- ? await this.ctx.agents.resume({ resumeSessionId: sessionId, ...options })
84
- : await this.ctx.agents.create({ sessionId, meta: { cwd: init.cwd }, ...options });
85
- this.sessions.set(init.sessionId, state);
132
+ this.logicalSessions.set(physicalId, init.sessionId);
133
+ try {
134
+ state.handle = resume
135
+ ? await this.ctx.agents.resume({ resumeSessionId: sessionId, ...options })
136
+ : await this.ctx.agents.create({ sessionId, meta: { cwd: init.cwd, ...(seed ? { isSeeded: true, parentSession: SessionId(parentSession) } : {}) }, ...(seed ? { seed: buildForkSeed(seed, seed.at(-1).seq), inheritedEventCount: SessionLogOffset(seed.length) } : {}), ...options });
137
+ }
138
+ catch (error) {
139
+ this.logicalSessions.delete(physicalId);
140
+ throw error;
141
+ }
86
142
  }
87
143
  get(sessionId) {
88
144
  const state = this.sessions.get(sessionId);
89
145
  if (!state)
90
146
  throw new Error(`session ${sessionId} is not open`);
147
+ if (this.contexts.current(sessionId).physicalId !== state.physicalId)
148
+ throw new Error("context version changed");
91
149
  return state;
92
150
  }
93
151
  /**
@@ -117,6 +175,8 @@ export class DshAdapter {
117
175
  const state = this.get(sessionId);
118
176
  if (state.sink)
119
177
  throw new Error("cannot change selected skills during an active input");
178
+ if (state.maintenance)
179
+ throw new Error("cannot change selected skills during maintenance");
120
180
  const candidate = prepareInputSkills(inputId, documents);
121
181
  if (state.inputSkills && JSON.stringify(state.inputSkills.receipt) !== JSON.stringify(candidate.receipt)) {
122
182
  throw new Error("another input skill context is already installed");
@@ -136,8 +196,8 @@ export class DshAdapter {
136
196
  }
137
197
  async *submitInput(sessionId, input, signal) {
138
198
  const state = this.get(sessionId);
139
- if (state.sink)
140
- throw new Error("session already has an active input");
199
+ if (state.sink || state.maintenance)
200
+ throw new Error("session already has active work");
141
201
  if (state.inputSkills && state.inputSkills.receipt.input_id !== (input.bindingInputId ?? input.id))
142
202
  throw new Error("selected skills belong to another input");
143
203
  const agent = state.handle.agent;
@@ -146,6 +206,7 @@ export class DshAdapter {
146
206
  const onAbort = () => agent.cancel({ kind: "user" });
147
207
  signal.addEventListener("abort", onAbort, { once: true });
148
208
  const from = agent.session.snapshotEvents().length;
209
+ this.model?.newTurn(state.physicalId);
149
210
  let idle;
150
211
  let settled = false;
151
212
  try {
@@ -180,14 +241,25 @@ export class DshAdapter {
180
241
  if (stop)
181
242
  throw stop;
182
243
  }
183
- /** Text-only input only: the host queues an input with images as the next turn instead. */
244
+ /**
245
+ * Steers the running input (agent.steering): DSH reads the input at its
246
+ * next step boundary, after the results of the current tool calls and
247
+ * before the next model request; a reply without tool calls does not end
248
+ * the turn while steering is pending. Text-only: the host runs an input
249
+ * with images after the running one instead.
250
+ */
184
251
  appendInput(sessionId, input) {
185
252
  if (input.images?.length)
186
253
  throw new Error("appendInput does not take images");
187
254
  const state = this.get(sessionId);
255
+ if (state.maintenance || !state.sink)
256
+ throw new Error("no active input accepts steering");
188
257
  if (state.inputSkills)
189
258
  throw new Error("cannot append another input to a selected-skill turn");
190
- state.handle.agent.followup(userMessage(input.id, [{ type: "text", text: input.text }]));
259
+ // A redelivered input (after a restart) the conversation already holds is not added twice.
260
+ if (hasRecordedInput(state.handle.agent.session.snapshotEvents(), input.id))
261
+ return;
262
+ state.handle.agent.steer(userMessage(input.id, [{ type: "text", text: input.text }]));
191
263
  }
192
264
  /**
193
265
  * Whether this build can take image input: the attachment service decodes
@@ -240,23 +312,155 @@ export class DshAdapter {
240
312
  async checkpoint(sessionId) {
241
313
  await this.ctx.sessions.flush(this.get(sessionId).handle.agent.session);
242
314
  }
315
+ /** Internal primitive only. Public capability stays closed until platform
316
+ * reservation, maintenance-only model authority and RPC receipts are wired. */
317
+ async compact(sessionId, request, signal) {
318
+ const { requestId, expectedVersion, expectedLastInputId, model } = request;
319
+ if (typeof expectedLastInputId !== 'string' || !expectedLastInputId || typeof model !== 'string' || !model)
320
+ throw new Error("invalid context binding");
321
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(requestId) || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0)
322
+ return Promise.reject(new Error("invalid context request"));
323
+ const recorded = this.compactReceipt(sessionId, request);
324
+ if (recorded)
325
+ return recorded;
326
+ const source = this.contexts.current(sessionId), state = this.get(sessionId);
327
+ if (state.sink || state.maintenance || state.inputSkills)
328
+ return Promise.reject(new Error("context maintenance requires an idle session"));
329
+ if (source.version !== expectedVersion)
330
+ return Promise.reject(new Error("context version changed"));
331
+ const abort = new AbortController();
332
+ const done = this.compactShadow(state, source, request, AbortSignal.any([signal, abort.signal]));
333
+ state.maintenance = { abort, done };
334
+ return done.finally(() => {
335
+ state.maintenance = undefined;
336
+ const selected = this.sessions.get(sessionId);
337
+ if (selected?.maintenance?.done === done)
338
+ selected.maintenance = undefined;
339
+ });
340
+ }
341
+ compactReceipt(sessionId, request) {
342
+ if (this.contexts.aborted(sessionId, request))
343
+ throw new ContextNotPublishedError(undefined);
344
+ const result = this.contexts.receipt(sessionId, request.requestId, request.expectedVersion);
345
+ if (result && (result.sourceInputId !== request.expectedLastInputId || result.model !== request.model))
346
+ throw new Error("context request idempotency conflict");
347
+ return result;
348
+ }
349
+ abortCompact(sessionId, request) {
350
+ return this.contexts.abort(sessionId, request);
351
+ }
352
+ async compactShadow(state, source, request, signal) {
353
+ const { requestId, expectedLastInputId, model } = request;
354
+ signal.throwIfAborted();
355
+ const logical = state.init.sessionId;
356
+ const seed = state.handle.agent.session.snapshotEvents();
357
+ const lastInput = seed.findLast(event => event.type === "user/message" && event.data.source?.kind === "user" && !String(event.data.id).includes(":continue:"));
358
+ if (lastInput?.type !== "user/message" || !(String(lastInput.data.id) === expectedLastInputId || String(lastInput.data.id).startsWith(expectedLastInputId + ":recovered:")) || this.port?.route(logical).model !== model)
359
+ throw new Error("context input or model changed");
360
+ const fingerprint = createHash("sha256").update(JSON.stringify(seed)).digest("hex");
361
+ const shadow = { init: state.init, physicalId: `${logical}-context-${randomUUID()}`, hostTools: { tools: [], dispose: [] } };
362
+ let published = false;
363
+ try {
364
+ await this.attach(shadow, false, seed, source.physicalId);
365
+ signal.throwIfAborted();
366
+ // compactNow may replace memory before its flush fails. It therefore runs
367
+ // exclusively on this durable shadow, never on the selected context.
368
+ const result = await this.ctx.compaction.compactNow(shadow.handle.agent, signal);
369
+ if (!result)
370
+ throw new Error("context does not need compaction");
371
+ await this.ctx.sessions.flush(shadow.handle.agent.session);
372
+ signal.throwIfAborted();
373
+ const now = createHash("sha256").update(JSON.stringify(state.handle.agent.session.snapshotEvents())).digest("hex");
374
+ if (now !== fingerprint)
375
+ throw new Error("context changed during maintenance");
376
+ const summary = result.summary.filter(block => block.type === "text").map(block => block.text).join("\n");
377
+ if (!summary.trim() || Buffer.byteLength(summary) > 524288)
378
+ throw new Error("invalid context summary");
379
+ const receipt = { sessionId: logical, requestId, previousVersion: source.version, version: source.version + 1, summary,
380
+ summarySha256: createHash("sha256").update(summary).digest("hex"), sourceEvents: seed.length, sourceInputId: expectedLastInputId, model };
381
+ try {
382
+ this.contexts.publish(logical, source, shadow.physicalId, receipt);
383
+ }
384
+ catch (error) {
385
+ // Never fall back to old context after a commit whose reply was lost.
386
+ if (this.contexts.current(logical).physicalId === shadow.physicalId) {
387
+ published = true;
388
+ shadow.maintenance = state.maintenance;
389
+ this.sessions.set(logical, shadow);
390
+ throw Object.assign(new Error("context commit result requires reconciliation"), { code: "context_commit_unknown", cause: error });
391
+ }
392
+ throw error;
393
+ }
394
+ published = true;
395
+ shadow.maintenance = state.maintenance;
396
+ this.sessions.set(logical, shadow);
397
+ return receipt;
398
+ }
399
+ catch (error) {
400
+ // The source handle still owns DSH's writer lock. No competing process
401
+ // can publish from this source while we prove it is still selected.
402
+ if (!published) {
403
+ const selected = this.contexts.current(logical);
404
+ if (selected.physicalId === source.physicalId && selected.version === source.version) {
405
+ // Freeze the terminal failure too: a late retry of this same request
406
+ // must return its failure rather than start another model call.
407
+ this.contexts.abort(logical, request);
408
+ throw new ContextNotPublishedError(error);
409
+ }
410
+ }
411
+ throw error;
412
+ }
413
+ finally {
414
+ const retired = published ? state : shadow;
415
+ if (retired.handle) {
416
+ try {
417
+ await retired.handle.dispose();
418
+ this.logicalSessions.delete(retired.physicalId);
419
+ }
420
+ catch {
421
+ this.retired.add(retired.handle);
422
+ }
423
+ }
424
+ }
425
+ }
243
426
  async close(sessionId) {
244
427
  const state = this.sessions.get(sessionId);
245
428
  if (!state)
246
429
  return;
430
+ if (state.maintenance)
431
+ throw new Error("cannot close active context");
247
432
  this.sessions.delete(sessionId);
248
433
  this.toolImages.forget(sessionId);
434
+ this.model?.forget(state.physicalId);
249
435
  try {
250
436
  await this.ctx.sessions.flush(state.handle.agent.session);
251
437
  }
252
438
  finally {
253
439
  await state.handle.dispose();
440
+ this.logicalSessions.delete(state.physicalId);
254
441
  }
255
442
  }
256
- async dispose() {
257
- for (const id of [...this.sessions.keys()])
258
- await this.close(id);
259
- await this.ctx.fiber.dispose();
443
+ dispose() {
444
+ return this.disposal ??= this.disposeOnce();
445
+ }
446
+ async disposeOnce() {
447
+ for (const state of this.sessions.values())
448
+ state.maintenance?.abort.abort();
449
+ await Promise.allSettled([...this.sessions.values()].flatMap(state => state.maintenance ? [state.maintenance.done] : []));
450
+ try {
451
+ for (const id of [...this.sessions.keys()])
452
+ await this.close(id);
453
+ for (const handle of this.retired)
454
+ await handle.dispose();
455
+ }
456
+ finally {
457
+ try {
458
+ await this.ctx.fiber.dispose();
459
+ }
460
+ finally {
461
+ this.contexts.close();
462
+ }
463
+ }
260
464
  }
261
465
  onSessionEvent(state, event) {
262
466
  if (state.sink)
@@ -125,7 +125,7 @@ export function registerConformance(name, factory, options = {}) {
125
125
  await run(adapter, "sesn_can", "in_1", "x", ctl.signal);
126
126
  assert.ok(Date.now() - started < 5_000);
127
127
  });
128
- test(`[conformance:${name}] stop reasons: output limit, context overflow and stream idle are typed; a model failure is generic`, async (t) => {
128
+ test(`[conformance:${name}] stop reasons: output limit, context overflow, stream idle and a refused model request are typed`, async (t) => {
129
129
  const typed = (code) => (err) => err instanceof TurnStopError && err.code === code && err.message.startsWith(`${code}: `);
130
130
  const cut = await mount(t, { script: () => ({ text: "cut off", finishReason: "length" }) });
131
131
  await cut.adapter.createSession(init("sesn_s1"));
@@ -150,6 +150,6 @@ export function registerConformance(name, factory, options = {}) {
150
150
  assert.equal(idle.model.requests.length, 1, "content had arrived: not retried");
151
151
  const failed = await mount(t, { script: () => ({ status: 401 }) });
152
152
  await failed.adapter.createSession(init("sesn_s4"));
153
- await assert.rejects(run(failed.adapter, "sesn_s4", "in_1", "x"), (err) => !(err instanceof TurnStopError));
153
+ await assert.rejects(run(failed.adapter, "sesn_s4", "in_1", "x"), typed("model_request_failed_error"));
154
154
  });
155
155
  }
@@ -0,0 +1,39 @@
1
+ export interface CompactReceipt {
2
+ sessionId: string;
3
+ requestId: string;
4
+ previousVersion: number;
5
+ version: number;
6
+ summary: string;
7
+ summarySha256: string;
8
+ sourceEvents: number;
9
+ sourceInputId: string;
10
+ model: string;
11
+ }
12
+ export interface CompactRequest {
13
+ requestId: string;
14
+ expectedVersion: number;
15
+ expectedLastInputId: string;
16
+ model: string;
17
+ }
18
+ /** The selected source was still held exclusively and no pointer was published. */
19
+ export declare class ContextNotPublishedError extends Error {
20
+ readonly code = "context_not_published";
21
+ constructor(cause: unknown);
22
+ }
23
+ export interface ContextPointer {
24
+ physicalId: string;
25
+ version: number;
26
+ }
27
+ export declare class ContextStore {
28
+ private readonly db;
29
+ constructor(home: string);
30
+ current(sessionId: string): ContextPointer;
31
+ receipt(sessionId: string, requestId: string, expectedVersion: number): CompactReceipt | undefined;
32
+ aborted(sessionId: string, request: CompactRequest): boolean;
33
+ /** A durable fence, not a signal acknowledgment. A late publication of this
34
+ * operation cannot cross it, including a request delayed on another replica. */
35
+ abort(sessionId: string, request: CompactRequest): CompactReceipt | undefined;
36
+ /** Called only after the shadow transcript has passed its durability barrier. */
37
+ publish(sessionId: string, source: ContextPointer, physicalId: string, receipt: CompactReceipt): void;
38
+ close(): void;
39
+ }
@@ -0,0 +1,95 @@
1
+ // The logical platform session stays fixed while its DSH context changes.
2
+ // Pointer and operation receipt commit together; transcript files are never
3
+ // overwritten or deleted. DSH still owns each physical transcript's writer lock.
4
+ import { mkdirSync, chmodSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { DatabaseSync } from "node:sqlite";
7
+ /** The selected source was still held exclusively and no pointer was published. */
8
+ export class ContextNotPublishedError extends Error {
9
+ code = "context_not_published";
10
+ constructor(cause) { super("context preparation did not publish", { cause }); }
11
+ }
12
+ export class ContextStore {
13
+ db;
14
+ constructor(home) {
15
+ mkdirSync(home, { recursive: true, mode: 0o700 });
16
+ const file = join(home, "context-index.sqlite");
17
+ this.db = new DatabaseSync(file);
18
+ try {
19
+ chmodSync(file, 0o600);
20
+ this.db.exec(`PRAGMA synchronous=FULL;
21
+ CREATE TABLE IF NOT EXISTS contexts(session_id TEXT PRIMARY KEY, physical_id TEXT NOT NULL, version INTEGER NOT NULL CHECK(version>0));
22
+ CREATE TABLE IF NOT EXISTS context_receipts(session_id TEXT NOT NULL,request_id TEXT NOT NULL,expected_version INTEGER NOT NULL,receipt TEXT NOT NULL,PRIMARY KEY(session_id,request_id));
23
+ CREATE TABLE IF NOT EXISTS context_aborts(session_id TEXT NOT NULL,request_id TEXT NOT NULL,expected_version INTEGER NOT NULL,source_input_id TEXT NOT NULL,model TEXT NOT NULL,PRIMARY KEY(session_id,request_id));`);
24
+ }
25
+ catch (error) {
26
+ this.db.close();
27
+ throw error;
28
+ }
29
+ }
30
+ current(sessionId) {
31
+ const row = this.db.prepare("SELECT physical_id,version FROM contexts WHERE session_id=?").get(sessionId);
32
+ return row ? { physicalId: String(row.physical_id), version: Number(row.version) } : { physicalId: sessionId, version: 0 };
33
+ }
34
+ receipt(sessionId, requestId, expectedVersion) {
35
+ const row = this.db.prepare("SELECT expected_version,receipt FROM context_receipts WHERE session_id=? AND request_id=?").get(sessionId, requestId);
36
+ if (!row)
37
+ return;
38
+ if (Number(row.expected_version) !== expectedVersion)
39
+ throw new Error("context request idempotency conflict");
40
+ return JSON.parse(String(row.receipt));
41
+ }
42
+ aborted(sessionId, request) {
43
+ const row = this.db.prepare("SELECT expected_version,source_input_id,model FROM context_aborts WHERE session_id=? AND request_id=?").get(sessionId, request.requestId);
44
+ if (!row)
45
+ return false;
46
+ if (Number(row.expected_version) !== request.expectedVersion || row.source_input_id !== request.expectedLastInputId || row.model !== request.model)
47
+ throw new Error("context request idempotency conflict");
48
+ return true;
49
+ }
50
+ /** A durable fence, not a signal acknowledgment. A late publication of this
51
+ * operation cannot cross it, including a request delayed on another replica. */
52
+ abort(sessionId, request) {
53
+ this.db.exec("BEGIN IMMEDIATE");
54
+ try {
55
+ const receipt = this.receipt(sessionId, request.requestId, request.expectedVersion);
56
+ if (receipt && (receipt.sourceInputId !== request.expectedLastInputId || receipt.model !== request.model))
57
+ throw new Error("context request idempotency conflict");
58
+ if (!receipt && !this.aborted(sessionId, request))
59
+ this.db.prepare("INSERT INTO context_aborts VALUES(?,?,?,?,?)").run(sessionId, request.requestId, request.expectedVersion, request.expectedLastInputId, request.model);
60
+ this.db.exec("COMMIT");
61
+ return receipt;
62
+ }
63
+ catch (error) {
64
+ try {
65
+ this.db.exec("ROLLBACK");
66
+ }
67
+ catch { }
68
+ throw error;
69
+ }
70
+ }
71
+ /** Called only after the shadow transcript has passed its durability barrier. */
72
+ publish(sessionId, source, physicalId, receipt) {
73
+ this.db.exec("BEGIN IMMEDIATE");
74
+ try {
75
+ if (this.aborted(sessionId, { requestId: receipt.requestId, expectedVersion: receipt.previousVersion, expectedLastInputId: receipt.sourceInputId, model: receipt.model }))
76
+ throw new ContextNotPublishedError(undefined);
77
+ const current = this.current(sessionId);
78
+ if (current.physicalId !== source.physicalId || current.version !== source.version ||
79
+ receipt.sessionId !== sessionId || receipt.previousVersion !== source.version || receipt.version !== source.version + 1 || physicalId === source.physicalId) {
80
+ throw new Error("context version changed");
81
+ }
82
+ this.db.prepare("INSERT INTO context_receipts VALUES(?,?,?,?)").run(sessionId, receipt.requestId, source.version, JSON.stringify(receipt));
83
+ this.db.prepare("INSERT INTO contexts VALUES(?,?,?) ON CONFLICT(session_id) DO UPDATE SET physical_id=excluded.physical_id,version=excluded.version").run(sessionId, physicalId, receipt.version);
84
+ this.db.exec("COMMIT");
85
+ }
86
+ catch (error) {
87
+ try {
88
+ this.db.exec("ROLLBACK");
89
+ }
90
+ catch { /* A commit may already be durable; caller fences an uncertain result. */ }
91
+ throw error;
92
+ }
93
+ }
94
+ close() { this.db.close(); }
95
+ }
package/lib/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export * from "./spi.ts";
2
2
  export { DshAdapter, type DshAdapterOptions } from "./adapter.ts";
3
- export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS, type KernelOptions } from "./kernel.ts";
4
- export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, MODEL_STREAM_IDLE, PROVIDER, RecentToolImages, TOOL_IMAGE_CALLS, type ModelAdapterOptions, type RequestImage } from "./model.ts";
3
+ export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS, COMPACTION_ATTEMPTS, type KernelOptions } from "./kernel.ts";
4
+ export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, DEFAULT_TRANSIENT_RETRY_BACKOFF_MS, MAX_SIZE_REJECTIONS, MODEL_CONNECTION, MODEL_STREAM_IDLE, REQUEST_TOO_LARGE, TRANSIENT_RETRIES, transientBackoffMs, retryAfterMs, PROVIDER, RecentToolImages, TOOL_IMAGE_INTERVAL, TOOL_IMAGE_KEEP, type ModelAdapterOptions, type RequestImage } from "./model.ts";
5
5
  export { ModelCatalog, DEFAULT_LIMITS, DEFAULT_REQUEST_MAX_TOKENS, requestMaxTokens, loadCatalogFile, parseLimits, type CatalogDefaults, type LimitsInput } from "./model-catalog.ts";
6
+ export { MAX_REQUEST_BODY_BYTES, RECENT_IMAGES, RECENT_TOOL_RESULTS, TOOL_TEXT_FLOOR } from "./request-budget.ts";
6
7
  export { restrictToPlatformTools, catalogViolation } from "./catalog-gate.ts";
7
8
  export { harnessEventsFromSessionEvent, harnessEventFromStreamFrame, cmaMessageEvent, cmaEventType, type CmaMessageEventType } from "./events.ts";
8
9
  export { approvalId, permissionRequest, refusalFor, type PermissionAnswer, type PermissionRequest } from "./approval.ts";
@@ -11,3 +12,5 @@ export { stopForTurnEnd, agentErrorCode, AGENT_ERROR_CODES, type AgentErrorCode,
11
12
  export { BASE_SYSTEM_PROMPT, composeSystemPrompt } from "./system-prompt.ts";
12
13
  export { DSH_VERSION } from "./version.ts";
13
14
  export type { InputSkillDocument, InputSkillReceipt } from "./input-skills.ts";
15
+ export type { CompactRequest, CompactReceipt } from "./context-store.ts";
16
+ export { ContextNotPublishedError } from "./context-store.ts";
package/lib/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // @beeos-ai/bma-dsh-adapter: the shared DSH adapter of BMA hosts.
2
2
  export * from "./spi.js";
3
3
  export { DshAdapter } from "./adapter.js";
4
- export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS } from "./kernel.js";
5
- export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, MODEL_STREAM_IDLE, PROVIDER, RecentToolImages, TOOL_IMAGE_CALLS } from "./model.js";
4
+ export { mountKernel, COMPACTION_HEADROOM_TOKENS, COMPACTION_SUMMARY_MAX_TOKENS, COMPACTION_ATTEMPTS } from "./kernel.js";
5
+ export { ChatCompletionsAdapter, DEFAULT_IDLE_RETRY_BACKOFF_MS, DEFAULT_STREAM_IDLE_MS, DEFAULT_TRANSIENT_RETRY_BACKOFF_MS, MAX_SIZE_REJECTIONS, MODEL_CONNECTION, MODEL_STREAM_IDLE, REQUEST_TOO_LARGE, TRANSIENT_RETRIES, transientBackoffMs, retryAfterMs, PROVIDER, RecentToolImages, TOOL_IMAGE_INTERVAL, TOOL_IMAGE_KEEP } from "./model.js";
6
6
  export { ModelCatalog, DEFAULT_LIMITS, DEFAULT_REQUEST_MAX_TOKENS, requestMaxTokens, loadCatalogFile, parseLimits } from "./model-catalog.js";
7
+ export { MAX_REQUEST_BODY_BYTES, RECENT_IMAGES, RECENT_TOOL_RESULTS, TOOL_TEXT_FLOOR } from "./request-budget.js";
7
8
  export { restrictToPlatformTools, catalogViolation } from "./catalog-gate.js";
8
9
  export { harnessEventsFromSessionEvent, harnessEventFromStreamFrame, cmaMessageEvent, cmaEventType } from "./events.js";
9
10
  export { approvalId, permissionRequest, refusalFor } from "./approval.js";
@@ -11,3 +12,4 @@ export { CONTINUE_NOTE, assertResumable, hasRecordedInput, continuationId } from
11
12
  export { stopForTurnEnd, agentErrorCode, AGENT_ERROR_CODES } from "./stop.js";
12
13
  export { BASE_SYSTEM_PROMPT, composeSystemPrompt } from "./system-prompt.js";
13
14
  export { DSH_VERSION } from "./version.js";
15
+ export { ContextNotPublishedError } from "./context-store.js";