dsh-claude-style 0.21.0-dev.61 → 0.21.1-dev.62

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.
@@ -3,6 +3,7 @@ var PACKAGE_NAME = "dsh-claude-style";
3
3
 
4
4
  // packages/host/src/search.ts
5
5
  import { createHash } from "node:crypto";
6
+ import { Buffer } from "node:buffer";
6
7
  import { cachePath, readJsonDocument, writeJsonDocument } from "./cache-file.js";
7
8
 
8
9
  // packages/engine/node/session-events.ts
@@ -44,7 +45,7 @@ async function readEvents(ctx, packageName, sessionId, label) {
44
45
  }
45
46
 
46
47
  // packages/host/src/search.ts
47
- var READ_CONCURRENCY = 4;
48
+ var CORPUS_CACHE_CHARS = 8e6;
48
49
  var SESSION_LIMIT = 40;
49
50
  var SNIPPET_LEAD = 36;
50
51
  var SNIPPET_CHARS = 140;
@@ -90,7 +91,8 @@ function snippetOf(text, index, length) {
90
91
  const match = flat(text.slice(index, index + length));
91
92
  const tail = `${flat(text.slice(index + length, end)).trimEnd()}${end < text.length ? "\u2026" : ""}`;
92
93
  const span = [head.length, head.length + match.length];
93
- return { snippet: head + match + tail, match: span };
94
+ const snippet = Buffer.from(head + match + tail, "utf16le").toString("utf16le");
95
+ return { snippet, match: span };
94
96
  }
95
97
  function isStoredMessage(value) {
96
98
  if (value === null || typeof value !== "object") return false;
@@ -99,11 +101,14 @@ function isStoredMessage(value) {
99
101
  }
100
102
  function createSessionSearch(ctx) {
101
103
  const cache = /* @__PURE__ */ new Map();
104
+ const sizes = /* @__PURE__ */ new Map();
105
+ let corpusChars = 0;
106
+ let catalog = /* @__PURE__ */ new Map();
102
107
  const lower = /* @__PURE__ */ new Map();
103
108
  let lowerChars = 0;
104
109
  const writtenAt = /* @__PURE__ */ new Map();
105
- let refreshing = null;
106
- let refreshingStore = false;
110
+ let serial = Promise.resolve();
111
+ let warming = null;
107
112
  let stored = null;
108
113
  let listedAt = 0;
109
114
  let disposed = false;
@@ -126,7 +131,7 @@ function createSessionSearch(ctx) {
126
131
  }
127
132
  function adopt(sessionId, entry, force) {
128
133
  if (disposed) return;
129
- cache.set(sessionId, entry);
134
+ hold(sessionId, entry);
130
135
  forgetLower(sessionId);
131
136
  const now = Date.now();
132
137
  if (!force && now - (writtenAt.get(sessionId) ?? 0) < CACHE_WRITE_INTERVAL_MS) return;
@@ -144,6 +149,24 @@ function createSessionSearch(ctx) {
144
149
  for (const text of held) lowerChars -= text.length;
145
150
  lower.delete(sessionId);
146
151
  }
152
+ function releaseCorpus(sessionId) {
153
+ corpusChars -= sizes.get(sessionId) ?? 0;
154
+ sizes.delete(sessionId);
155
+ cache.delete(sessionId);
156
+ forgetLower(sessionId);
157
+ }
158
+ function hold(sessionId, entry) {
159
+ let size = 0;
160
+ for (const message of entry.messages) size += message.text.length;
161
+ releaseCorpus(sessionId);
162
+ if (size > CORPUS_CACHE_CHARS) return;
163
+ while (corpusChars + size > CORPUS_CACHE_CHARS && cache.size > 0) {
164
+ releaseCorpus(cache.keys().next().value);
165
+ }
166
+ cache.set(sessionId, entry);
167
+ sizes.set(sessionId, size);
168
+ corpusChars += size;
169
+ }
147
170
  function loweredFor(sessionId, entry) {
148
171
  const held = lower.get(sessionId);
149
172
  if (held !== void 0) {
@@ -151,10 +174,11 @@ function createSessionSearch(ctx) {
151
174
  lower.set(sessionId, held);
152
175
  return held;
153
176
  }
177
+ if (!cache.has(sessionId) || (sizes.get(sessionId) ?? 0) > LOWER_CACHE_CHARS) return null;
154
178
  const texts = entry.messages.map((message) => message.text.toLowerCase());
155
179
  let size = 0;
156
180
  for (const text of texts) size += text.length;
157
- if (size > LOWER_CACHE_CHARS) return texts;
181
+ if (size > LOWER_CACHE_CHARS) return null;
158
182
  while (lowerChars + size > LOWER_CACHE_CHARS && lower.size > 0) {
159
183
  const oldest = lower.keys().next().value;
160
184
  if (oldest === void 0) break;
@@ -166,26 +190,47 @@ function createSessionSearch(ctx) {
166
190
  }
167
191
  function forget(sessionId) {
168
192
  if (disposed) return;
169
- cache.delete(sessionId);
170
- forgetLower(sessionId);
193
+ releaseCorpus(sessionId);
171
194
  writtenAt.delete(sessionId);
172
195
  writeJsonDocument(ctx, cacheFile(sessionId), "session search cache", null);
173
196
  }
174
197
  async function rebuild(sessionId, revision) {
175
198
  const events = await readEvents(ctx, PACKAGE_NAME, sessionId, "content search");
176
- if (disposed) return;
177
- if (events === null) return;
199
+ if (disposed) return null;
200
+ if (events === null) return null;
178
201
  const last = events[events.length - 1];
179
202
  const lastSeq = typeof last?.seq === "number" ? last.seq + 1 : 0;
180
- adopt(sessionId, { revision, lastSeq, messages: messagesOf(events) }, false);
203
+ const entry = { revision, lastSeq, messages: messagesOf(events) };
204
+ adopt(sessionId, entry, false);
205
+ return entry;
206
+ }
207
+ async function corpusFor(id, want) {
208
+ if (disposed) return null;
209
+ const entry = cache.get(id) ?? readCached(id);
210
+ if (entry === null || (want.live === null ? entry.revision !== want.revision : entry.lastSeq > want.live.seq)) {
211
+ return await rebuild(id, want.revision) ?? entry;
212
+ }
213
+ if (want.live !== null && entry.lastSeq < want.live.seq) {
214
+ entry.messages = entry.messages.concat(messagesOf(want.live.snapshotEvents(entry.lastSeq)));
215
+ entry.lastSeq = want.live.seq;
216
+ adopt(id, entry, false);
217
+ } else if (!cache.has(id)) hold(id, entry);
218
+ else {
219
+ cache.delete(id);
220
+ cache.set(id, entry);
221
+ }
222
+ return entry;
181
223
  }
182
224
  async function refresh(store) {
225
+ if (disposed) return;
183
226
  const persistence = ctx.get("sessionPersistence");
184
227
  const sessions = ctx.get("sessions");
185
228
  if (!persistence || !sessions) throw new Error("the host exposes no session persistence or session service");
186
229
  if (store && (stored === null || Date.now() - listedAt >= LIST_INTERVAL_MS)) {
187
230
  const listing = /* @__PURE__ */ new Map();
188
- for (const snapshot of await persistence.list()) {
231
+ const snapshots = await persistence.list();
232
+ if (disposed) return;
233
+ for (const snapshot of snapshots) {
189
234
  if (snapshot.header.origin === "subagent") continue;
190
235
  listing.set(snapshot.header.id, String(snapshot.revision));
191
236
  }
@@ -205,67 +250,36 @@ function createSessionSearch(ctx) {
205
250
  for (const [id, session] of live) {
206
251
  if (!wanted.has(id)) wanted.set(id, { revision: "", live: session });
207
252
  }
208
- for (const id of [...cache.keys()]) {
253
+ for (const id of catalog.keys()) {
209
254
  if (!wanted.has(id)) forget(id);
210
255
  }
211
- const stale = [];
212
- for (const [id, want] of wanted) {
213
- const entry = cache.get(id) ?? readCached(id);
214
- if (entry === null) {
215
- stale.push(id);
216
- continue;
217
- }
218
- cache.set(id, entry);
219
- if (want.live !== null) {
220
- if (entry.lastSeq > want.live.seq) stale.push(id);
221
- else if (entry.lastSeq < want.live.seq) {
222
- const tail = messagesOf(want.live.snapshotEvents(entry.lastSeq));
223
- entry.messages = entry.messages.concat(tail);
224
- entry.lastSeq = want.live.seq;
225
- adopt(id, entry, false);
226
- }
227
- continue;
228
- }
229
- if (entry.revision !== want.revision) stale.push(id);
230
- }
231
- let next = 0;
232
- const worker = async () => {
233
- while (next < stale.length) {
234
- const id = stale[next++];
235
- const want = wanted.get(id);
236
- if (want !== void 0) await rebuild(id, want.revision);
237
- }
238
- };
239
- const workers = [];
240
- for (let i = 0; i < READ_CONCURRENCY; i++) workers.push(worker());
241
- await Promise.all(workers);
256
+ catalog = wanted;
242
257
  }
243
- function catchUp(store) {
244
- if (refreshing !== null && (refreshingStore || !store)) return refreshing;
245
- refreshingStore = store;
246
- const pass = refresh(store);
247
- const done = pass.finally(() => {
248
- if (refreshing === done) {
249
- refreshing = null;
250
- refreshingStore = false;
251
- }
258
+ function enqueue(run) {
259
+ const result = serial.then(run);
260
+ serial = result.then(() => {
261
+ }, () => {
252
262
  });
253
- refreshing = done;
254
- return refreshing;
263
+ return result;
255
264
  }
256
265
  async function search(text) {
257
- await catchUp(stored === null);
266
+ await refresh(stored === null);
258
267
  const query = text.trim();
259
268
  const parts = query.split(/\s+/u);
260
269
  const single = parts.length === 1 ? parts[0].toLowerCase() : "";
261
270
  const pattern = single === "" ? compileQuery(query) : null;
262
271
  const hits = [];
263
- for (const [sessionId, entry] of cache) {
272
+ let scanned = 0;
273
+ for (const [sessionId, want] of catalog) {
274
+ if (disposed) break;
275
+ const entry = await corpusFor(sessionId, want);
276
+ if (entry === null || disposed) continue;
277
+ scanned += 1;
264
278
  const lowered = single === "" ? [] : loweredFor(sessionId, entry);
265
279
  for (let i = entry.messages.length - 1; i >= 0; i--) {
266
280
  const message = entry.messages[i];
267
281
  const found = single === "" ? pattern.exec(message.text) : null;
268
- const index = single === "" ? found?.index ?? -1 : (lowered[i] ?? message.text.toLowerCase()).indexOf(single);
282
+ const index = single === "" ? found?.index ?? -1 : (lowered?.[i] ?? message.text.toLowerCase()).indexOf(single);
269
283
  if (index < 0) continue;
270
284
  const length = single === "" ? found[0].length : single.length;
271
285
  hits.push({ sessionId, seq: message.seq, time: message.time, role: message.role, ...snippetOf(message.text, index, length) });
@@ -273,20 +287,45 @@ function createSessionSearch(ctx) {
273
287
  }
274
288
  }
275
289
  hits.sort((a, b) => b.time - a.time);
276
- return { sessions: hits.slice(0, SESSION_LIMIT), scanned: cache.size };
290
+ return { sessions: disposed ? [] : hits.slice(0, SESSION_LIMIT), scanned: disposed ? 0 : scanned };
277
291
  }
278
292
  function dispose() {
279
293
  disposed = true;
280
294
  cache.clear();
295
+ sizes.clear();
296
+ corpusChars = 0;
297
+ catalog.clear();
281
298
  lower.clear();
282
299
  lowerChars = 0;
283
300
  writtenAt.clear();
284
301
  stored = null;
285
- refreshing = null;
302
+ warming = null;
303
+ }
304
+ function warm() {
305
+ if (warming !== null) return warming;
306
+ const done = enqueue(async () => {
307
+ await refresh(true);
308
+ for (const [id, want] of catalog) {
309
+ if (disposed) break;
310
+ await corpusFor(id, want);
311
+ }
312
+ }).finally(() => {
313
+ if (warming === done) warming = null;
314
+ });
315
+ warming = done;
316
+ return done;
286
317
  }
287
- return { search, warm: () => catchUp(true), dispose };
318
+ return {
319
+ search: (text) => enqueue(() => search(text)),
320
+ warm,
321
+ dispose,
322
+ /** Resident UTF-16 units only; directory metadata and transient log reads are separate. */
323
+ memory: () => ({ corpusChars, lowerChars, sessions: cache.size, catalog: catalog.size })
324
+ };
288
325
  }
289
326
  export {
327
+ CORPUS_CACHE_CHARS,
328
+ LOWER_CACHE_CHARS,
290
329
  QUERY_MAX,
291
330
  createSessionSearch
292
331
  };
@@ -0,0 +1,55 @@
1
+ // packages/contracts/src/compaction.ts
2
+ var positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
3
+ var nonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
4
+ function compactionThreshold(inputs) {
5
+ const window = positive(inputs.contextWindow);
6
+ const ratio = positive(inputs.policy?.thresholdRatio);
7
+ if (window === null || ratio === null || ratio > 1) return null;
8
+ const headroom = nonNegative(inputs.policy?.headroomTokens) ?? 0;
9
+ const reserved = nonNegative(inputs.reservedOutput) ?? nonNegative(inputs.policy?.maxTokens) ?? 0;
10
+ const pressureBudget = window - reserved - headroom;
11
+ if (pressureBudget <= 0) return null;
12
+ return Math.floor(Math.min(window * ratio, pressureBudget));
13
+ }
14
+ var DEFAULT_COMPACTION_POLICY = { thresholdRatio: 0.8, headroomTokens: 65536 };
15
+
16
+ // packages/host/src/session-compact.ts
17
+ var COMPACT_COMMAND = "/compact";
18
+ var isRecord = (value) => value !== null && typeof value === "object";
19
+ function policyOf(config, provider, model) {
20
+ if (!isRecord(config)) return DEFAULT_COMPACTION_POLICY;
21
+ const overrides = Array.isArray(config.modelPolicies) ? config.modelPolicies : [];
22
+ const match = overrides.find((entry) => isRecord(entry) && entry.provider === provider && entry.model === model);
23
+ const stated = isRecord(match) ? match : {};
24
+ return {
25
+ thresholdRatio: stated.thresholdRatio ?? config.thresholdRatio ?? DEFAULT_COMPACTION_POLICY.thresholdRatio,
26
+ headroomTokens: stated.headroomTokens ?? config.headroomTokens ?? DEFAULT_COMPACTION_POLICY.headroomTokens,
27
+ maxTokens: stated.maxTokens ?? config.maxTokens ?? DEFAULT_COMPACTION_POLICY.maxTokens
28
+ };
29
+ }
30
+ function backendConfigOf(ctx, agent) {
31
+ const agentScope = agent?.ctx;
32
+ const fromAgent = agentScope?.get?.("compaction");
33
+ if (isRecord(fromAgent)) return fromAgent.config;
34
+ const fromRoot = ctx.get?.("compaction");
35
+ return isRecord(fromRoot) ? fromRoot.config : void 0;
36
+ }
37
+ function compactionThresholdOf(ctx, agents, sessionId, state, window) {
38
+ const policy = policyOf(backendConfigOf(ctx, agents?.get?.(sessionId)), state.provider, state.model);
39
+ return compactionThreshold({ contextWindow: window, reservedOutput: state.reservedOutput, policy });
40
+ }
41
+ async function compactSession(ctx, sessionId) {
42
+ const agent = ctx.get("agents")?.get?.(sessionId);
43
+ if (agent === void 0) return { ok: false, code: "no-agent" };
44
+ const commands = ctx.get("commands");
45
+ if (typeof commands?.execute !== "function") return { ok: false, code: "unavailable" };
46
+ const execution = await commands.execute(agent, COMPACT_COMMAND, [], new AbortController().signal);
47
+ if (execution === void 0) return { ok: false, code: "unavailable" };
48
+ const result = execution.result ?? {};
49
+ const text = typeof result.text === "string" && result.text !== "" ? result.text : void 0;
50
+ return result.kind === "success" ? { ok: true, ...text === void 0 ? {} : { text } } : { ok: false, ...text === void 0 ? {} : { text } };
51
+ }
52
+ export {
53
+ compactSession,
54
+ compactionThresholdOf
55
+ };
@@ -0,0 +1,27 @@
1
+ // packages/host/src/session-panel-call.ts
2
+ var COMMAND_TOOLS = /* @__PURE__ */ new Set(["bash", "pwsh", "terminal_send"]);
3
+ var PROCESS_KINDS = /* @__PURE__ */ new Set(["bash", "pwsh", "pty-send"]);
4
+ function panelArguments(value) {
5
+ if (typeof value !== "string" || value === "") return null;
6
+ let parsed;
7
+ try {
8
+ parsed = JSON.parse(value);
9
+ } catch {
10
+ return null;
11
+ }
12
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
13
+ }
14
+ function panelInvocation(name, value) {
15
+ const args = panelArguments(value);
16
+ const process = typeof name === "string" && COMMAND_TOOLS.has(name);
17
+ const label = [args?.description, args?.command, args?.text].find((part) => typeof part === "string" && part !== "");
18
+ return { process, background: args?.run_in_background === true, label: typeof label === "string" ? label : "" };
19
+ }
20
+ function isPanelProcess(id, kind, invocation) {
21
+ return invocation?.process === true || (typeof kind === "string" ? PROCESS_KINDS.has(kind) : /^(?:bash|pwsh|pty-send)-/.test(id));
22
+ }
23
+ export {
24
+ isPanelProcess,
25
+ panelArguments,
26
+ panelInvocation
27
+ };