@agent-dock/cli 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -474,6 +474,48 @@ function createRepositories(filename, options = {}) {
474
474
  async countBySession(sessionId) {
475
475
  return sqlite.prepare("SELECT count(*) AS total FROM events WHERE session_id = ?").get(sessionId).total;
476
476
  },
477
+ /**
478
+ * 和 mergeStreamingSegments 同一套合并规则,但只回数量、不物化正文:
479
+ * 连续 thinking、连续 assistant text 各算一段;user text 是轮次锚点,每行都算;
480
+ * status / raw_terminal 是诊断信息,不算对话体积。
481
+ */
482
+ async countConversationSegments(sessionId) {
483
+ const row = sqlite.prepare(`
484
+ WITH ordered AS (
485
+ SELECT type,
486
+ coalesce(json_extract(data, '$.role'), 'assistant') AS role,
487
+ lag(type) OVER (ORDER BY sequence) AS prev_type,
488
+ lag(coalesce(json_extract(data, '$.role'), 'assistant')) OVER (ORDER BY sequence) AS prev_role
489
+ FROM events
490
+ WHERE session_id = ?
491
+ )
492
+ SELECT count(*) AS total
493
+ FROM ordered
494
+ WHERE type NOT IN ('status', 'raw_terminal')
495
+ AND (
496
+ type NOT IN ('thinking', 'text')
497
+ OR (type = 'text' AND role = 'user')
498
+ OR prev_type IS NULL
499
+ OR prev_type <> type
500
+ OR prev_role IS NULL
501
+ OR prev_role <> role
502
+ )
503
+ `).get(sessionId);
504
+ return row.total;
505
+ },
506
+ async countCompletedCompactions(sessionId) {
507
+ return sqlite.prepare(`
508
+ SELECT
509
+ count(DISTINCT CASE WHEN json_extract(data, '$.compactionId') IS NOT NULL
510
+ THEN json_extract(data, '$.compactionId') END)
511
+ + coalesce(sum(CASE WHEN json_extract(data, '$.compactionId') IS NULL THEN 1 ELSE 0 END), 0) AS total
512
+ FROM events
513
+ WHERE session_id = ?
514
+ AND type = 'status'
515
+ AND json_extract(data, '$.state') = 'compaction'
516
+ AND json_extract(data, '$.phase') = 'completed'
517
+ `).get(sessionId).total;
518
+ },
477
519
  async maxSequence(sessionId) {
478
520
  return sqlite.prepare("SELECT coalesce(max(sequence), 0) AS max FROM events WHERE session_id = ?").get(sessionId).max;
479
521
  },
@@ -6115,7 +6157,7 @@ import { dirname as dirname6, join as join6 } from "node:path";
6115
6157
  import { existsSync as existsSync6 } from "node:fs";
6116
6158
  import { fileURLToPath as fileURLToPath4 } from "node:url";
6117
6159
 
6118
- // ../../node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/agent-registry-Gtwn7nMp.js
6160
+ // ../../../../../Users/codeax/workspace/agent-dock/node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/agent-registry-Gtwn7nMp.js
6119
6161
  import fs from "node:fs";
6120
6162
  import { fileURLToPath as fileURLToPath2 } from "node:url";
6121
6163
  import path from "node:path";
@@ -6917,7 +6959,7 @@ function normalizeRegistryOverride(value) {
6917
6959
  return value.length > 0 && value[0]?.length ? [...value] : void 0;
6918
6960
  }
6919
6961
 
6920
- // ../../node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/ipc-D2BC99hf.js
6962
+ // ../../../../../Users/codeax/workspace/agent-dock/node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/ipc-D2BC99hf.js
6921
6963
  import fs2, { statSync as statSync2 } from "node:fs";
6922
6964
  import path2 from "node:path";
6923
6965
  import fs$1 from "node:fs/promises";
@@ -8613,7 +8655,7 @@ var DEFAULT_LIMITS = Object.freeze({
8613
8655
  observers: 64
8614
8656
  });
8615
8657
 
8616
- // ../../node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/queue-owner-runtime-Be8sr9L5.js
8658
+ // ../../../../../Users/codeax/workspace/agent-dock/node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/queue-owner-runtime-Be8sr9L5.js
8617
8659
  import fs3, { readFileSync as readFileSync4, realpathSync } from "node:fs";
8618
8660
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
8619
8661
  import path3 from "node:path";
@@ -13520,7 +13562,7 @@ var LiveSessionCheckpoint = class {
13520
13562
  }
13521
13563
  };
13522
13564
 
13523
- // ../../node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/runtime.js
13565
+ // ../../../../../Users/codeax/workspace/agent-dock/node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/runtime.js
13524
13566
  import path4 from "node:path";
13525
13567
  import fs4 from "node:fs/promises";
13526
13568
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -16463,6 +16505,12 @@ function normalizeAcpxEvent(input) {
16463
16505
  }
16464
16506
  if (kind === "permission_request" || kind === "permission_escalation") return { type: "permission_request", data: { id: event.requestId ?? event.id ?? update.toolCallId, toolCallId: update.toolCallId, title: update.title ?? event.toolTitle ?? "Permission required", options: update.options ?? [], status: "pending" } };
16465
16507
  if (kind === "usage_update") return { type: "status", data: { state: "usage", used: event.used, size: event.size, breakdown: event.breakdown, cost: event.cost } };
16508
+ if (kind === "compaction_update") {
16509
+ const status = String(update.status ?? event.status ?? "");
16510
+ const phase = status === "completed" ? "completed" : status === "failed" ? "failed" : status === "cancelled" ? "cancelled" : "start";
16511
+ return { type: "status", data: { state: "compaction", phase, ...update.compactionId ? { compactionId: update.compactionId } : {}, ...status === "failed" && update.error ? { detail: String(update.error) } : {} } };
16512
+ }
16513
+ if (kind === "compaction_summary_chunk") return { type: "status", data: { state: "compaction", phase: "summary", ...update.compactionId ? { compactionId: update.compactionId } : {} } };
16466
16514
  if (kind === "available_commands_update") return { type: "status", data: { state: "commands", availableCommands: event.availableCommands ?? update.availableCommands ?? [] } };
16467
16515
  if (kind === "error") return { type: "error", data: { message: event.message ?? event.error?.message ?? "Agent error", detail: event } };
16468
16516
  if (kind === "done" || kind === "completed" || kind === "result" || event.result?.stopReason) return { type: "completed", data: { stopReason: event.stopReason ?? event.result?.stopReason ?? "end_turn" } };
@@ -26914,7 +26962,7 @@ init_src2();
26914
26962
 
26915
26963
  // src/assistant/lifecycle.ts
26916
26964
  var lifeStages = ["kitten", "adult", "senior", "elder"];
26917
- var lifecycleMetricKeys = ["rounds", "events", "contextPercent", "openNotes", "closedNotes", "archivedNotes", "uptimeDays"];
26965
+ var lifecycleMetricKeys = ["rounds", "compactions", "events", "contextPercent", "openNotes", "closedNotes", "archivedNotes", "uptimeDays"];
26918
26966
  var metricLevels = ["ok", "tidy", "handoff"];
26919
26967
  var DEFAULT_LIFECYCLE_CONFIG = {
26920
26968
  autoMaintenance: true,
@@ -26923,7 +26971,8 @@ var DEFAULT_LIFECYCLE_CONFIG = {
26923
26971
  maxAutoRunsPerDay: 2,
26924
26972
  thresholds: {
26925
26973
  rounds: { tidy: 200, handoff: 600 },
26926
- events: { tidy: 8e3, handoff: 3e4 },
26974
+ compactions: { tidy: 3, handoff: 6 },
26975
+ events: { tidy: 2e4, handoff: 6e4 },
26927
26976
  contextPercent: { tidy: 75, handoff: 90 },
26928
26977
  openNotes: { tidy: 15 },
26929
26978
  closedNotes: { tidy: 40 },
@@ -26933,7 +26982,8 @@ var DEFAULT_LIFECYCLE_CONFIG = {
26933
26982
  };
26934
26983
  var metricLabel = {
26935
26984
  rounds: "\u4E3B\u4F1A\u8BDD\u8F6E\u6B21",
26936
- events: "\u4E8B\u4EF6\u6761\u6570",
26985
+ compactions: "\u4E0A\u4E0B\u6587\u538B\u7F29",
26986
+ events: "\u4E8B\u4EF6\u6BB5\u6570",
26937
26987
  contextPercent: "\u4E0A\u4E0B\u6587\u7528\u91CF",
26938
26988
  openNotes: "\u672A\u5173\u95ED\u4FBF\u7B7E",
26939
26989
  closedNotes: "\u5DF2\u5B8C\u6210\u4FBF\u7B7E",
@@ -27052,6 +27102,7 @@ function reasonsFor(metrics, config, keys) {
27052
27102
  function formatMetricValue(metric, value) {
27053
27103
  if (metric === "contextPercent") return `${Math.round(value)}%`;
27054
27104
  if (metric === "uptimeDays") return `${Math.round(value * 10) / 10} \u5929`;
27105
+ if (metric === "compactions") return `${Math.round(value)} \u6B21`;
27055
27106
  return String(Math.round(value));
27056
27107
  }
27057
27108
  function formatReason(reason) {
@@ -27059,9 +27110,16 @@ function formatReason(reason) {
27059
27110
  }
27060
27111
  function computeAgeScore(metrics, config) {
27061
27112
  const ratio = (value, threshold) => value === void 0 || threshold === void 0 || threshold <= 0 ? void 0 : Math.max(0, value) / threshold;
27113
+ const compactionRatio = (value, threshold) => {
27114
+ const linear = ratio(value, threshold);
27115
+ return linear === void 0 ? void 0 : Math.pow(linear, 0.83);
27116
+ };
27117
+ const eventCap = config.thresholds.events.handoff;
27118
+ const eventCapLoad = eventCap !== void 0 && eventCap > 0 && metrics.events >= eventCap ? metrics.events / eventCap : void 0;
27062
27119
  const loads = [
27063
27120
  ratio(metrics.rounds, config.thresholds.rounds.handoff),
27064
- ratio(metrics.events, config.thresholds.events.handoff),
27121
+ compactionRatio(metrics.compactions, config.thresholds.compactions.handoff),
27122
+ eventCapLoad,
27065
27123
  ratio(metrics.contextPercent, config.thresholds.contextPercent.handoff)
27066
27124
  ].filter((value) => value !== void 0);
27067
27125
  const load = loads.length ? Math.max(...loads) : 0;
@@ -27456,6 +27514,11 @@ function buildMaintenancePrompt(input) {
27456
27514
  // src/assistant/lifecycle-service.ts
27457
27515
  var CONFIG_KEY = "assistant.lifecycle.config";
27458
27516
  var ALERTS_KEY = "assistant.lifecycle.alerts";
27517
+ var CONFIG_VERSION_KEY = "assistant.lifecycle.configVersion";
27518
+ var LIFECYCLE_CONFIG_VERSION = 1;
27519
+ var LEGACY_EVENTS_GUARD = { tidy: 2e5, handoff: 3e5 };
27520
+ var METRIC_VERSION_KEY = "assistant.lifecycle.metricVersion";
27521
+ var LIFECYCLE_METRIC_VERSION = 2;
27459
27522
  var METRICS_TTL_MS = 6e4;
27460
27523
  var DAY_MS = 864e5;
27461
27524
  var BUSY_STATES = /* @__PURE__ */ new Set(["starting", "thinking", "running_tool", "waiting_for_permission", "interrupting"]);
@@ -27483,6 +27546,7 @@ var AssistantLifecycle = class {
27483
27546
  }
27484
27547
  /** 启动时收拾上次没收完的摊子:交接提交点之前的回滚,整理轮次标成中断。 */
27485
27548
  async initialize() {
27549
+ this.migrateConfig();
27486
27550
  const open = this.store.openHandoff();
27487
27551
  if (open) {
27488
27552
  const predecessor = open.state === "retiring" ? await this.repos.sessions.get(open.fromSessionId) : void 0;
@@ -27512,6 +27576,31 @@ var AssistantLifecycle = class {
27512
27576
  await this.execution;
27513
27577
  }
27514
27578
  // ---------------------------------------------------------------- 配置
27579
+ /**
27580
+ * 配置口径迁移。旧正式库为了不让 0.3.4 按原始行重算 peak,把 events 阈值临时设成
27581
+ * 200000/300000,而且没有 compactions 阈值;新版本必须把它们落库修正,否则事件上限保护
27582
+ * 在装上新版后仍然形同虚设。版本标记保证只执行一次,之后用户再手动设置也不会被覆盖。
27583
+ */
27584
+ migrateConfig() {
27585
+ const stored = Number(this.store.getSetting(CONFIG_VERSION_KEY) ?? 0);
27586
+ if (Number.isFinite(stored) && stored >= LIFECYCLE_CONFIG_VERSION) return;
27587
+ const raw = this.store.getSetting(CONFIG_KEY);
27588
+ let parsed;
27589
+ try {
27590
+ parsed = raw ? JSON.parse(raw) : void 0;
27591
+ } catch {
27592
+ parsed = void 0;
27593
+ }
27594
+ const config = normalizeLifecycleConfig(parsed);
27595
+ const events2 = config.thresholds.events;
27596
+ const restoredEvents = events2.tidy === LEGACY_EVENTS_GUARD.tidy && events2.handoff === LEGACY_EVENTS_GUARD.handoff;
27597
+ if (restoredEvents) config.thresholds.events = { ...DEFAULT_LIFECYCLE_CONFIG.thresholds.events };
27598
+ this.store.setSetting(CONFIG_KEY, serializeLifecycleConfig(config));
27599
+ this.store.setSetting(CONFIG_VERSION_KEY, String(LIFECYCLE_CONFIG_VERSION));
27600
+ this.log.info(
27601
+ `\u751F\u547D\u5468\u671F\u914D\u7F6E\u8FC1\u79FB\u5230 v${LIFECYCLE_CONFIG_VERSION}\uFF1Acompactions=${config.thresholds.compactions.tidy ?? "-"}/${config.thresholds.compactions.handoff ?? "-"}\uFF0Cevents=${config.thresholds.events.tidy ?? "-"}/${config.thresholds.events.handoff ?? "-"}` + (restoredEvents ? `\uFF08\u5DF2\u4ECE\u4E34\u65F6\u5B88\u536B\u503C ${LEGACY_EVENTS_GUARD.tidy}/${LEGACY_EVENTS_GUARD.handoff} \u6062\u590D\uFF09` : "")
27602
+ );
27603
+ }
27515
27604
  getConfig() {
27516
27605
  const raw = this.store.getSetting(CONFIG_KEY);
27517
27606
  try {
@@ -27624,14 +27713,16 @@ var AssistantLifecycle = class {
27624
27713
  const cat = await this.ensureCat();
27625
27714
  if (!cat) return void 0;
27626
27715
  const config = this.getConfig();
27627
- const [tasks2, events2, recent] = await Promise.all([
27716
+ const [tasks2, compactions, events2, recent] = await Promise.all([
27628
27717
  this.runtime.getTasks(mainId),
27629
- this.repos.events.countBySession(mainId),
27718
+ this.repos.events.countCompletedCompactions(mainId),
27719
+ this.repos.events.countConversationSegments(mainId),
27630
27720
  this.repos.events.listRecent(mainId, 400)
27631
27721
  ]);
27632
27722
  const notes = this.store.listTasks();
27633
27723
  const metrics = {
27634
27724
  rounds: countRounds(tasks2),
27725
+ compactions,
27635
27726
  events: events2,
27636
27727
  ...withContext(latestContextPercent([...recent].sort((left, right) => left.sequence - right.sequence))),
27637
27728
  openNotes: notes.filter((task) => task.state !== "closed").length,
@@ -27642,7 +27733,8 @@ var AssistantLifecycle = class {
27642
27733
  computedAt: now()
27643
27734
  };
27644
27735
  const ageScore = computeAgeScore(metrics, config);
27645
- const { peak, stage } = advanceAge(cat.peakAgeScore, ageScore);
27736
+ const migrated = this.migrateMetricVersion(cat, metrics, config, ageScore);
27737
+ const { peak, stage } = advanceAge(migrated.peakAgeScore, ageScore);
27646
27738
  if (peak !== cat.peakAgeScore || stage !== cat.lifeStage || metrics.rounds !== cat.rounds) {
27647
27739
  cat.peakAgeScore = peak;
27648
27740
  cat.lifeStage = stage;
@@ -27653,6 +27745,38 @@ var AssistantLifecycle = class {
27653
27745
  this.metricsCache = { sessionId: mainId, at: Date.now(), value };
27654
27746
  return value;
27655
27747
  }
27748
+ /**
27749
+ * 一次性口径迁移。旧版 events 数的是 ACP 的原始流式行,会把刚接班的小猫直接推到老年;
27750
+ * 升级后第一次拿到新指标时,用新口径重算当前猫的 peak/stage,并清掉旧档位记录。
27751
+ * 只做一次:之后 peak 仍按单调规则增长。
27752
+ */
27753
+ migrateMetricVersion(cat, metrics, config, ageScore) {
27754
+ const stored = Number(this.store.getSetting(METRIC_VERSION_KEY) ?? 0);
27755
+ if (Number.isFinite(stored) && stored >= LIFECYCLE_METRIC_VERSION) return cat;
27756
+ cat.peakAgeScore = ageScore;
27757
+ cat.lifeStage = lifeStageFor(ageScore);
27758
+ cat.rounds = metrics.rounds;
27759
+ this.store.saveCat(cat);
27760
+ this.invalidateLegacyProposal(cat, metrics, config);
27761
+ this.writeAlerts(emptyAlertState(cat.id));
27762
+ this.store.setSetting(METRIC_VERSION_KEY, String(LIFECYCLE_METRIC_VERSION));
27763
+ this.log.info(`\u751F\u547D\u5468\u671F\u6307\u6807\u8FC1\u79FB\u5230 v${LIFECYCLE_METRIC_VERSION}\uFF1A${cat.name} peak=${ageScore} stage=${cat.lifeStage}`);
27764
+ return cat;
27765
+ }
27766
+ /** 旧提议的越线理由若只靠旧 events 口径,新口径下已经不再成立,就直接作废,等下一轮扫描重新判断。 */
27767
+ invalidateLegacyProposal(cat, metrics, config) {
27768
+ const open = this.store.openHandoff();
27769
+ if (!open || open.state !== "proposed" || open.fromCatId !== cat.id || open.trigger !== "threshold") return;
27770
+ const levels = computeLevels(metrics, config);
27771
+ if (!open.reasons.some((reason) => reason.metric === "events" && levels.events !== "handoff")) return;
27772
+ if (!this.store.compareAndSetHandoffState(open.id, "proposed", "cancelled")) return;
27773
+ const fresh = this.store.getHandoff(open.id);
27774
+ fresh.completedAt = now();
27775
+ fresh.error = "\u6307\u6807\u53E3\u5F84\u5347\u7EA7\uFF1A\u65E7\u7684 events \u884C\u6570\u53E3\u5F84\u5DF2\u5E9F\u5F03\uFF0C\u8FD9\u5F20\u4EA4\u63A5\u63D0\u8BAE\u4F5C\u5E9F";
27776
+ fresh.steps = [...fresh.steps, { step: "recovery", at: now(), ok: true, detail: "\u6307\u6807\u53E3\u5F84\u5347\u7EA7\uFF0C\u65E7\u63D0\u8BAE\u4F5C\u5E9F" }];
27777
+ this.store.saveHandoff(fresh);
27778
+ this.log.info(`\u5DF2\u4F5C\u5E9F\u65E7\u53E3\u5F84\u4EA4\u63A5\u63D0\u8BAE ${open.id}`);
27779
+ }
27656
27780
  // ---------------------------------------------------------------- 视图
27657
27781
  async overview() {
27658
27782
  const collected = await this.collectMetrics();