dsh-ws-recency 0.24.1 → 0.25.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 (4) hide show
  1. package/README.md +11 -4
  2. package/client.js +569 -133
  3. package/index.js +181 -9
  4. package/package.json +1 -1
package/index.js CHANGED
@@ -32,7 +32,7 @@ import { dirname, join } from "node:path";
32
32
  export const name = "ws-recency";
33
33
 
34
34
  /** Version marker reported by the health route. */
35
- export const HOST_VERSION = "0.24.1";
35
+ export const HOST_VERSION = "0.25.1";
36
36
 
37
37
  /**
38
38
  * Exact routes the client half calls. Registered on the bare web server, so they
@@ -306,6 +306,31 @@ function blockText(content) {
306
306
  return text;
307
307
  }
308
308
 
309
+ /**
310
+ * A one-line hint of what a tool call touched, for the amplified ranking.
311
+ *
312
+ * The argument text is the model's own JSON; the interesting field is the first
313
+ * path/command/query it names, and a malformed or non-string argument simply
314
+ * yields no hint.
315
+ */
316
+ function toolDetail(args) {
317
+ if (typeof args !== "string") return "";
318
+ try {
319
+ const parsed = JSON.parse(args);
320
+ const value = parsed?.file_path ?? parsed?.path ?? parsed?.command ?? parsed?.pattern ?? parsed?.query ?? parsed?.url ?? parsed?.name;
321
+ if (typeof value === "string" && value.trim() !== "") return value.trim().replace(/\s+/g, " ").slice(0, 80);
322
+ } catch {
323
+ /* not JSON: no hint */
324
+ }
325
+ return "";
326
+ }
327
+
328
+ /** First non-empty line, trimmed, for a user/system block's label. */
329
+ function snippetOf(text, limit = 80) {
330
+ const line = String(text ?? "").split("\n")[0].trim().replace(/\s+/g, " ");
331
+ return line.slice(0, limit);
332
+ }
333
+
309
334
  /**
310
335
  * Aggregate one session's events into costs.
311
336
  *
@@ -321,6 +346,15 @@ export function aggregateSession(events) {
321
346
  };
322
347
  const tools = new Map();
323
348
  const callNames = new Map();
349
+ /* Real per-step context, so the bill can be attributed back to the content
350
+ that produced it instead of to the step that happened to be running. */
351
+ const steps = [];
352
+ /** Content blocks with the step before which they enter the prompt. */
353
+ const blocks = [];
354
+ /** Tool-call blocks by call id, so a result can extend its own call. */
355
+ const callBlocks = new Map();
356
+ /** Steps at which a compaction dropped the prefix; blocks stop being re-read. */
357
+ const compactions = [];
324
358
  const toolOf = (name) => {
325
359
  const key = typeof name === "string" && name !== "" ? name : "unknown";
326
360
  let entry = tools.get(key);
@@ -334,6 +368,9 @@ export function aggregateSession(events) {
334
368
  for (const event of events) {
335
369
  if (event === null || typeof event !== "object") continue;
336
370
  const data = event.data ?? {};
371
+ if (typeof event.type === "string" && event.type.toLowerCase().indexOf("compact") !== -1) {
372
+ compactions.push(steps.length);
373
+ }
337
374
  if (typeof event.time === "number") {
338
375
  if (summary.session.createdAt === 0 || event.time < summary.session.createdAt) summary.session.createdAt = event.time;
339
376
  if (event.time > summary.session.lastAt) summary.session.lastAt = event.time;
@@ -359,13 +396,24 @@ export function aggregateSession(events) {
359
396
  summary.totals.cacheReadTokens += Number(usage.cacheReadTokens) || 0;
360
397
  summary.totals.outputTokens += Number(usage.outputTokens) || 0;
361
398
  summary.totals.totalTokens += Number(usage.totalTokens) || 0;
399
+ steps.push({
400
+ input: Number(usage.inputTokens) || 0,
401
+ cacheRead: Number(usage.cacheReadTokens) || 0,
402
+ output: Number(usage.outputTokens) || 0,
403
+ });
362
404
  }
405
+ /* Whatever this reply said or requested enters the prompt of the next
406
+ step. Reasoning is deliberately left out: providers usually do not
407
+ resend it, so it would be counted as amplified when it never is. */
363
408
  const content = data.message !== null && data.message !== undefined ? data.message.content : undefined;
364
409
  for (const block of Array.isArray(content) ? content : []) {
365
410
  if (block === null || typeof block !== "object") continue;
366
411
  if (block.type === "reasoning") summary.estimate.agent.reasoning += estimateTokens(block.text);
367
- else if (block.type === "text") summary.estimate.agent.text += estimateTokens(block.text);
368
- else if (block.type === "tool-call" && block.id !== undefined) callNames.set(String(block.id), block.name);
412
+ else if (block.type === "text") {
413
+ const tokens = estimateTokens(block.text);
414
+ summary.estimate.agent.text += tokens;
415
+ if (tokens > 0) blocks.push({ kind: "agent", name: "agent", detail: snippetOf(block.text), tokens, entry: steps.length });
416
+ } else if (block.type === "tool-call" && block.id !== undefined) callNames.set(String(block.id), block.name);
369
417
  }
370
418
  break;
371
419
  }
@@ -374,21 +422,48 @@ export function aggregateSession(events) {
374
422
  if (data.callId !== undefined) callNames.set(String(data.callId), name);
375
423
  const entry = toolOf(name);
376
424
  entry.calls += 1;
377
- entry.args += estimateTokens(data.arguments);
425
+ const args = estimateTokens(data.arguments);
426
+ entry.args += args;
427
+ const block = {
428
+ kind: "tool",
429
+ name: typeof name === "string" && name !== "" ? name : "unknown",
430
+ detail: toolDetail(data.arguments),
431
+ tokens: args,
432
+ args,
433
+ results: 0,
434
+ entry: steps.length,
435
+ };
436
+ blocks.push(block);
437
+ if (data.callId !== undefined) callBlocks.set(String(data.callId), block);
378
438
  break;
379
439
  }
380
440
  case "tool/result": {
381
- const name = callNames.get(String(data.toolCallId ?? data.message?.source?.callId ?? ""));
441
+ const callId = String(data.toolCallId ?? data.message?.source?.callId ?? "");
442
+ const name = callNames.get(callId);
382
443
  const entry = toolOf(name);
383
- entry.results += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
444
+ const results = estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
445
+ entry.results += results;
446
+ const block = callBlocks.get(callId);
447
+ if (block !== undefined) {
448
+ block.results += results;
449
+ block.tokens += results;
450
+ } else if (results > 0) {
451
+ blocks.push({ kind: "tool", name: typeof name === "string" && name !== "" ? name : "unknown", detail: "", tokens: results, args: 0, results, entry: steps.length });
452
+ }
384
453
  break;
385
454
  }
386
455
  case "user/message": {
387
- summary.estimate.agent.user += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
456
+ const text = blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content);
457
+ const tokens = estimateTokens(text);
458
+ summary.estimate.agent.user += tokens;
459
+ if (tokens > 0) blocks.push({ kind: "user", name: "user", detail: snippetOf(text), tokens, entry: steps.length });
388
460
  break;
389
461
  }
390
462
  case "system/message": {
391
- summary.estimate.agent.system += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
463
+ const text = blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content);
464
+ const tokens = estimateTokens(text);
465
+ summary.estimate.agent.system += tokens;
466
+ if (tokens > 0) blocks.push({ kind: "system", name: "system", detail: snippetOf(text), tokens, entry: steps.length });
392
467
  break;
393
468
  }
394
469
  default:
@@ -408,6 +483,85 @@ export function aggregateSession(events) {
408
483
  for (const entry of list) entry.share = entry.total / grand;
409
484
  summary.estimate.agent.share = agent.total / grand;
410
485
  }
486
+
487
+ /* -------------------------------------------------------------------------
488
+ * Amplified cost: the bill is `sum(context per step)`, so a block that enters
489
+ * early is paid for again on every later step. Its share of the bill is
490
+ * `tokens x remaining steps`, not the tokens it showed at the moment it
491
+ * appeared. That is what makes "top steps" useless and "top content" useful.
492
+ * ----------------------------------------------------------------------- */
493
+ const totalSteps = steps.length;
494
+ const bill = steps.reduce((sum, step) => sum + step.input + step.cacheRead, 0);
495
+ const limitFor = (entry) => {
496
+ let limit = totalSteps;
497
+ /* Conservative: a compaction recorded before step k replaces everything up
498
+ to k, so a block that entered at k is not re-read afterwards either. */
499
+ for (const at of compactions) if (at >= entry && at < limit) limit = at;
500
+ return limit;
501
+ };
502
+ const byKind = new Map();
503
+ const addKind = (kind, tokens, remaining) => {
504
+ let entry = byKind.get(kind);
505
+ if (entry === undefined) {
506
+ entry = { kind, tokens: 0, amplified: 0 };
507
+ byKind.set(kind, entry);
508
+ }
509
+ entry.tokens += tokens;
510
+ entry.amplified += tokens * remaining;
511
+ };
512
+ for (const block of blocks) {
513
+ const limit = limitFor(block.entry);
514
+ block.remaining = Math.max(0, limit - block.entry);
515
+ block.amplified = block.tokens * block.remaining;
516
+ if (block.kind === "tool") {
517
+ addKind("results", block.results, block.remaining);
518
+ addKind("args", block.args, block.remaining);
519
+ } else {
520
+ addKind(block.kind, block.tokens, block.remaining);
521
+ }
522
+ }
523
+ const attributed = [...byKind.values()].reduce((sum, entry) => sum + entry.amplified, 0);
524
+ const ranked = blocks
525
+ .filter((block) => block.amplified > 0)
526
+ .sort((a, b) => b.amplified - a.amplified)
527
+ .slice(0, 15)
528
+ .map((block) => ({
529
+ kind: block.kind,
530
+ name: block.name,
531
+ detail: block.detail,
532
+ entry: block.entry + 1,
533
+ remaining: block.remaining,
534
+ tokens: block.tokens,
535
+ args: block.args || 0,
536
+ results: block.results || 0,
537
+ amplified: block.amplified,
538
+ share: bill > 0 ? block.amplified / bill : 0,
539
+ saving: Math.round(block.amplified * 0.8),
540
+ }));
541
+
542
+ /* Downsample the context curve: at most 96 points keeps the panel cheap. */
543
+ const series = [];
544
+ if (totalSteps > 0) {
545
+ const buckets = Math.min(96, totalSteps);
546
+ const size = Math.ceil(totalSteps / buckets);
547
+ for (let start = 0; start < totalSteps; start += size) {
548
+ const end = Math.min(totalSteps, start + size);
549
+ let sum = 0;
550
+ for (let index = start; index < end; index += 1) sum += steps[index].input + steps[index].cacheRead;
551
+ series.push({ step: start + 1, context: Math.round(sum / (end - start)) });
552
+ }
553
+ }
554
+ summary.amplified = {
555
+ bill,
556
+ attributed,
557
+ share: bill > 0 ? attributed / bill : 0,
558
+ steps: totalSteps,
559
+ series,
560
+ blocks: ranked,
561
+ byKind: [...byKind.values()]
562
+ .map((entry) => ({ ...entry, share: bill > 0 ? entry.amplified / bill : 0 }))
563
+ .sort((a, b) => b.amplified - a.amplified),
564
+ };
411
565
  return summary;
412
566
  }
413
567
 
@@ -1368,8 +1522,24 @@ export async function handleHandoffRequest(ctx, req, res) {
1368
1522
  let text = "";
1369
1523
  let at = 0;
1370
1524
  let replies = 0;
1525
+ /** `seq` of the newest assistant text; the Client compares it with its start. */
1526
+ let textSeq = 0;
1527
+ /** `seq` of the newest event of any kind (a turn can add tool steps). */
1528
+ let lastSeq = 0;
1529
+ /** Turn of the newest assistant text, so the card renders on that turn only. */
1530
+ let turn;
1531
+ let turnOpen = false;
1371
1532
  for (const event of events) {
1372
1533
  if (event === null || typeof event !== "object") continue;
1534
+ if (typeof event.seq === "number" && event.seq > lastSeq) lastSeq = event.seq;
1535
+ if (event.type === "turn/start") {
1536
+ turnOpen = true;
1537
+ continue;
1538
+ }
1539
+ if (event.type === "turn/end") {
1540
+ turnOpen = false;
1541
+ continue;
1542
+ }
1373
1543
  if (event.type !== "assistant/message") continue;
1374
1544
  replies += 1;
1375
1545
  const content = event.data?.message?.content ?? event.data?.content;
@@ -1381,9 +1551,11 @@ export async function handleHandoffRequest(ctx, req, res) {
1381
1551
  if (joined !== "") {
1382
1552
  text = joined;
1383
1553
  at = typeof event.time === "number" ? event.time : 0;
1554
+ if (typeof event.seq === "number") textSeq = event.seq;
1555
+ if (typeof event.data?.turn === "number") turn = event.data.turn;
1384
1556
  }
1385
1557
  }
1386
- sendJson(res, 200, { ok: true, text, at, replies });
1558
+ sendJson(res, 200, { ok: true, text, at, replies, textSeq, lastSeq, turn, turnOpen });
1387
1559
  }
1388
1560
 
1389
1561
  export async function handleTrashListRequest(ctx, req, res) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ws-recency",
3
- "version": "0.24.1",
3
+ "version": "0.25.1",
4
4
  "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, archived sessions managed from that same trash panel, per-session token statistics with an argument/result split and an option to count tool arguments as the agent's writing, and moving a session to another workspace.",
5
5
  "license": "MIT",
6
6
  "author": "chyxhtc",