dsh-agy-link 0.6.55 → 0.6.56

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.56 (2026-11-22)
4
+
5
+ ### English
6
+
7
+ - **Fix(visibility): live background-task logs and ACP tracker activity are now surfaced, and a false "previous turn was interrupted" banner is gone (merges PR #155).** Two independent problems:
8
+ - Backgrounded `run_command` task logs (`.system_generated/tasks/*.log`) and completion/cancellation notices (`.system_generated/messages/{,undelivered/}*.json`) were not tailed in real time, and `runAcpAttempt()` created its attempt recorder with the tracker disabled. A new `TaskActivityTracker` (`src/features/subagent/task-activity.ts`) tails them incrementally (UTF-8 multi-byte safe, burst-bounded, EOF baselined on resumed runs, message ids de-duplicated) and is wired into `SubagentTracker` with a final synchronous flush in `stop()`; ACP runs now enable the tracker. `RUNNING` step fallback text and the mirror card carry task-id / log-path / timer hints.
9
+ - In `streamAttempt()`, a prior run that had **already produced a consumable result** but took slightly over 1.5s to tear down was still marked `binding.interrupted = true` and had `[the previous turn was interrupted before it finished …]` prepended to the next prompt — a lie about a turn that actually answered. Only runs **without** a consumable result are marked interrupted now.
10
+ - Note: `hasConsumableResult` (added in 0.6.51) is what distinguishes the two cases; the change is a net reduction in `adapter.ts`.
11
+
12
+ ### 中文
13
+
14
+ - **修复(可见性):实时后台任务日志与 ACP tracker 活动现在会展示,且错误插入的「上一轮被中断」横幅已消除(合并 PR #155)。** 两个独立问题:
15
+ - 转后台的 `run_command` 任务日志(`.system_generated/tasks/*.log`)与完成/取消通知(`.system_generated/messages/{,undelivered/}*.json`)此前不会被实时跟随,且 `runAcpAttempt()` 创建 recorder 时未启用 tracker。新增 `TaskActivityTracker`(`src/features/subagent/task-activity.ts`)增量跟随(UTF-8 多字节安全、突发有界、续跑时以 EOF 为基线、消息 id 去重),接入 `SubagentTracker` 并在 `stop()` 做最终同步 flush;ACP 运行现在会启用 tracker。`RUNNING` 步骤的兜底文案与镜像卡片会带上 task-id / 日志路径 / 定时提示。
16
+ - `streamAttempt()` 里,上一轮**已经产出可消费结果**、只是收尾超过 1.5 秒的情形,仍会被标记 `binding.interrupted = true` 并把「上一轮在完成前被中断…」插到下一条 prompt 前面——对一个实际已经作答的回合说谎。现在只有**没有**可消费结果的 run 才会被标记为中断。
17
+ - 说明:区分这两种情形依靠 0.6.51 引入的 `hasConsumableResult`;该改动使 `adapter.ts` 净减少代码。
18
+
3
19
  ## 0.6.55 (2026-11-21)
4
20
 
5
21
  ### English
@@ -4298,6 +4298,29 @@ function buildToolCallBlock(input) {
4298
4298
  }
4299
4299
  //#endregion
4300
4300
  //#region src/provider/mapper/event-mapper.ts
4301
+ function formatRunningToolFallback(toolName, rawArgs) {
4302
+ const unwrapped = unwrapMcpTool(toolName, rawArgs);
4303
+ const a = unwrapped.input;
4304
+ const str = (...keys) => {
4305
+ for (const k of keys) {
4306
+ const v = a[k];
4307
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
4308
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
4309
+ }
4310
+ return "";
4311
+ };
4312
+ if (unwrapped.tool === "schedule") {
4313
+ const cron = str("CronExpression", "cron_expression");
4314
+ const dur = str("DurationSeconds", "duration_seconds");
4315
+ const prompt = str("Prompt", "prompt");
4316
+ const timing = cron ? `cron ${cron}` : dur ? `${dur}s timer` : "schedule";
4317
+ return prompt ? `Schedule active (${timing}): ${prompt}` : `Schedule active (${timing})`;
4318
+ }
4319
+ const cmd = str("CommandLine", "command_line", "command", "cmd");
4320
+ const taskId = str("TaskId", "taskId", "task_id", "bgTaskId");
4321
+ if (cmd !== "") return `Tool is running as a background task${taskId ? ` (${taskId})` : ""}: ${cmd}`;
4322
+ return taskId ? `Tool is running as a background task (${taskId})` : "Tool is running as a background task";
4323
+ }
4301
4324
  var EventMapper = class {
4302
4325
  opts;
4303
4326
  blockIdx = 0;
@@ -4540,7 +4563,7 @@ var EventMapper = class {
4540
4563
  }
4541
4564
  return;
4542
4565
  }
4543
- if (ev.state === "RUNNING" && ev.tool.output === void 0) ev.tool.output = ev.text !== "" ? ev.text : "Tool is running as a background task";
4566
+ if (ev.state === "RUNNING" && (ev.tool.output === void 0 || ev.tool.output === "")) ev.tool.output = ev.text !== "" ? ev.text : formatRunningToolFallback(ev.tool.name, ev.tool.args);
4544
4567
  if (this.announcedTools.has(ev.stepKey)) return;
4545
4568
  this.announcedTools.add(ev.stepKey);
4546
4569
  if (!this.opts.cutOnTool) return;
@@ -34708,6 +34731,205 @@ function buildAgyEnv(input) {
34708
34731
  return env;
34709
34732
  }
34710
34733
  //#endregion
34734
+ //#region src/features/subagent/task-activity.ts
34735
+ const MAX_READ_BYTES_PER_POLL = 131072;
34736
+ const MAX_LINES_PER_POLL = 20;
34737
+ const MAX_LINE_CHARS = 220;
34738
+ const MAX_MESSAGE_CHARS = 240;
34739
+ function noteWarn(log, context, err) {
34740
+ const detail = err instanceof Error ? err.message : String(err);
34741
+ log?.(`[task-activity] ${context}: ${detail}`);
34742
+ }
34743
+ function clipSingleLine(text, maxChars) {
34744
+ const single = text.replace(/\r/g, "").replace(/\s+/g, " ").trim();
34745
+ if (single.length <= maxChars) return single;
34746
+ return single.slice(0, Math.max(0, maxChars - 1)) + "…";
34747
+ }
34748
+ function formatTaskLogLine(taskId, line) {
34749
+ return `[后台任务 · ${taskId}] ${clipSingleLine(line, MAX_LINE_CHARS)}`;
34750
+ }
34751
+ function summarizeMessageJson(rawObj, fallbackName = "message") {
34752
+ if (!rawObj || typeof rawObj !== "object") return null;
34753
+ const obj = rawObj;
34754
+ const id = typeof obj.id === "string" && obj.id.trim() !== "" ? obj.id.trim() : "";
34755
+ const rawSender = typeof obj.sender === "string" ? obj.sender.trim() : "";
34756
+ const senderLabel = rawSender.includes("/") ? rawSender.slice(rawSender.lastIndexOf("/") + 1) : rawSender || "system";
34757
+ const details = obj.renderDetails && typeof obj.renderDetails === "object" ? obj.renderDetails : void 0;
34758
+ const title = typeof details?.messageTitle === "string" ? clipSingleLine(details.messageTitle, 120) : "";
34759
+ const content = typeof obj.content === "string" ? clipSingleLine(obj.content, MAX_MESSAGE_CHARS) : "";
34760
+ if (title === "" && content === "") return null;
34761
+ const body = title !== "" && content !== "" && !content.toLowerCase().includes(title.toLowerCase()) ? `${title} — ${content}` : content !== "" ? content : title;
34762
+ return {
34763
+ dedupKey: id !== "" ? id : fallbackName,
34764
+ text: `[后台通知 · ${senderLabel}] ${body}`
34765
+ };
34766
+ }
34767
+ function listFilesSafe(dir, suffix) {
34768
+ if (!existsSync(dir)) return [];
34769
+ try {
34770
+ return readdirSync(dir).filter((f) => f.endsWith(suffix)).sort();
34771
+ } catch {
34772
+ return [];
34773
+ }
34774
+ }
34775
+ var TaskActivityTracker = class {
34776
+ log;
34777
+ logs = /* @__PURE__ */ new Map();
34778
+ seenMessageFiles = /* @__PURE__ */ new Set();
34779
+ seenMessageIds = /* @__PURE__ */ new Set();
34780
+ baselined = false;
34781
+ constructor(log) {
34782
+ this.log = log;
34783
+ }
34784
+ reset() {
34785
+ this.logs.clear();
34786
+ this.seenMessageFiles.clear();
34787
+ this.seenMessageIds.clear();
34788
+ this.baselined = false;
34789
+ }
34790
+ /** Record pre-existing logs and messages at EOF so resumed runs only emit new activity. */
34791
+ baseline(brainDir) {
34792
+ this.baselined = true;
34793
+ this.scanTaskLogs(brainDir, true, () => {});
34794
+ this.scanMessages(brainDir, true, () => {});
34795
+ }
34796
+ poll(brainDir, emit) {
34797
+ try {
34798
+ this.scanTaskLogs(brainDir, false, emit);
34799
+ this.scanMessages(brainDir, false, emit);
34800
+ } catch (err) {
34801
+ noteWarn(this.log, "poll", err);
34802
+ }
34803
+ }
34804
+ scanTaskLogs(brainDir, baselineOnly, emit) {
34805
+ const tasksDir = join(brainDir, ".system_generated", "tasks");
34806
+ for (const file of listFilesSafe(tasksDir, ".log")) {
34807
+ const taskId = file.slice(0, -4);
34808
+ const fullPath = join(tasksDir, file);
34809
+ let tracked = this.logs.get(file);
34810
+ if (!tracked) {
34811
+ let initialOffset = 0;
34812
+ if (baselineOnly || this.baselined) {
34813
+ if (baselineOnly) try {
34814
+ const st = statSync(fullPath);
34815
+ if (st.isFile()) initialOffset = st.size;
34816
+ } catch {
34817
+ initialOffset = 0;
34818
+ }
34819
+ }
34820
+ tracked = {
34821
+ taskId,
34822
+ filePath: fullPath,
34823
+ offset: initialOffset,
34824
+ decoder: new StringDecoder("utf8"),
34825
+ rest: "",
34826
+ seq: 0
34827
+ };
34828
+ this.logs.set(file, tracked);
34829
+ }
34830
+ if (baselineOnly) continue;
34831
+ this.pollSingleTaskLog(tracked, emit);
34832
+ }
34833
+ }
34834
+ pollSingleTaskLog(tracked, emit) {
34835
+ let size;
34836
+ try {
34837
+ const st = statSync(tracked.filePath);
34838
+ if (!st.isFile()) return;
34839
+ size = st.size;
34840
+ } catch {
34841
+ return;
34842
+ }
34843
+ if (size < tracked.offset) {
34844
+ tracked.offset = 0;
34845
+ tracked.decoder = new StringDecoder("utf8");
34846
+ tracked.rest = "";
34847
+ }
34848
+ if (size === tracked.offset) return;
34849
+ const toRead = Math.min(size - tracked.offset, MAX_READ_BYTES_PER_POLL);
34850
+ const buffer = Buffer.allocUnsafe(toRead);
34851
+ let bytesRead = 0;
34852
+ try {
34853
+ const fd = openSync(tracked.filePath, "r");
34854
+ try {
34855
+ bytesRead = readSync(fd, buffer, 0, toRead, tracked.offset);
34856
+ } finally {
34857
+ closeSync(fd);
34858
+ }
34859
+ } catch {
34860
+ return;
34861
+ }
34862
+ if (bytesRead <= 0) return;
34863
+ tracked.offset += bytesRead;
34864
+ const parts = (tracked.rest + tracked.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
34865
+ tracked.rest = size > tracked.offset ? "" : parts.pop() ?? "";
34866
+ if (size > tracked.offset) {
34867
+ tracked.offset = size;
34868
+ tracked.decoder = new StringDecoder("utf8");
34869
+ }
34870
+ const lines = parts.map((l) => l.trim()).filter((l) => l !== "");
34871
+ if (lines.length === 0) return;
34872
+ const skipped = Math.max(0, lines.length - MAX_LINES_PER_POLL);
34873
+ const visible = skipped > 0 ? lines.slice(-20) : lines;
34874
+ if (skipped > 0) {
34875
+ tracked.seq += 1;
34876
+ emit({
34877
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
34878
+ text: `[后台任务 · ${tracked.taskId}] … 跳过 ${skipped} 行中间输出,最新日志如下\n`,
34879
+ raw: {
34880
+ kind: "task-log",
34881
+ taskId: tracked.taskId,
34882
+ skipped
34883
+ }
34884
+ });
34885
+ }
34886
+ for (const line of visible) {
34887
+ tracked.seq += 1;
34888
+ emit({
34889
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
34890
+ text: `${formatTaskLogLine(tracked.taskId, line)}\n`,
34891
+ raw: {
34892
+ kind: "task-log",
34893
+ taskId: tracked.taskId,
34894
+ line
34895
+ }
34896
+ });
34897
+ }
34898
+ }
34899
+ scanMessages(brainDir, baselineOnly, emit) {
34900
+ const baseDir = join(brainDir, ".system_generated", "messages");
34901
+ const dirs = [{
34902
+ tag: "delivered",
34903
+ path: baseDir
34904
+ }, {
34905
+ tag: "undelivered",
34906
+ path: join(baseDir, "undelivered")
34907
+ }];
34908
+ for (const dir of dirs) for (const file of listFilesSafe(dir.path, ".json")) {
34909
+ const fileKey = `${dir.tag}:${file}`;
34910
+ if (this.seenMessageFiles.has(fileKey)) continue;
34911
+ this.seenMessageFiles.add(fileKey);
34912
+ const stem = file.slice(0, -5);
34913
+ let parsed;
34914
+ try {
34915
+ parsed = JSON.parse(readFileSync(join(dir.path, file), "utf8"));
34916
+ } catch {
34917
+ continue;
34918
+ }
34919
+ const summary = summarizeMessageJson(parsed, stem);
34920
+ if (!summary) continue;
34921
+ if (this.seenMessageIds.has(summary.dedupKey)) continue;
34922
+ this.seenMessageIds.add(summary.dedupKey);
34923
+ if (baselineOnly) continue;
34924
+ emit({
34925
+ stepKey: `task-msg-${summary.dedupKey}`,
34926
+ text: `${summary.text}\n`,
34927
+ raw: parsed
34928
+ });
34929
+ }
34930
+ }
34931
+ };
34932
+ //#endregion
34711
34933
  //#region src/features/subagent/tracker.ts
34712
34934
  /**
34713
34935
  * Swallow the failures a live transcript produces by design — a row still being
@@ -34790,6 +35012,7 @@ var SubagentTracker = class {
34790
35012
  brainDir = null;
34791
35013
  trackedSubagents = /* @__PURE__ */ new Map();
34792
35014
  seenStepKeys = /* @__PURE__ */ new Set();
35015
+ taskActivity;
34793
35016
  timer = null;
34794
35017
  active = false;
34795
35018
  polling = false;
@@ -34799,6 +35022,7 @@ var SubagentTracker = class {
34799
35022
  this.conversationId = opts.conversationId ?? "";
34800
35023
  this.accountHome = opts.accountHome;
34801
35024
  this.pollIntervalMs = opts.pollIntervalMs ?? 500;
35025
+ this.taskActivity = new TaskActivityTracker(opts.log);
34802
35026
  }
34803
35027
  /** Follow the conversation agy reported in its stream-json init/result envelope. */
34804
35028
  setConversationId(cid) {
@@ -34806,6 +35030,7 @@ var SubagentTracker = class {
34806
35030
  this.conversationId = cid;
34807
35031
  this.brainDir = null;
34808
35032
  this.baselined = false;
35033
+ this.taskActivity.reset();
34809
35034
  if (this.active) {
34810
35035
  if (this.opts.resumed === true) {
34811
35036
  this.baselined = true;
@@ -34830,6 +35055,7 @@ var SubagentTracker = class {
34830
35055
  try {
34831
35056
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
34832
35057
  if (!this.brainDir) return;
35058
+ this.taskActivity.baseline(this.brainDir);
34833
35059
  this.scanSubagentsForConv(this.conversationId, true);
34834
35060
  for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
34835
35061
  } catch (err) {
@@ -34837,10 +35063,14 @@ var SubagentTracker = class {
34837
35063
  }
34838
35064
  }
34839
35065
  stop() {
34840
- this.active = false;
34841
- if (this.timer) {
34842
- clearInterval(this.timer);
34843
- this.timer = null;
35066
+ try {
35067
+ if (this.active && !this.polling && this.conversationId !== "") this.poll();
35068
+ } finally {
35069
+ this.active = false;
35070
+ if (this.timer) {
35071
+ clearInterval(this.timer);
35072
+ this.timer = null;
35073
+ }
34844
35074
  }
34845
35075
  }
34846
35076
  /** Run one scan across known conversations and subagents. */
@@ -34851,6 +35081,9 @@ var SubagentTracker = class {
34851
35081
  try {
34852
35082
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
34853
35083
  if (!this.brainDir) return;
35084
+ this.taskActivity.poll(this.brainDir, (ev) => {
35085
+ this.emitSubagentEvent(ev.stepKey, ev.text, ev.raw);
35086
+ });
34854
35087
  const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
34855
35088
  for (const cid of convsToScan) this.scanSubagentsForConv(cid);
34856
35089
  for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
@@ -35128,6 +35361,9 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35128
35361
  tracker?.start();
35129
35362
  proc.outcome.finally(() => tracker?.stop());
35130
35363
  },
35364
+ startTracker: () => {
35365
+ tracker?.start();
35366
+ },
35131
35367
  feedLine: (line, onEvent, onFirstEvent) => {
35132
35368
  watchdog.markEvent();
35133
35369
  onFirstEvent?.();
@@ -36192,22 +36428,25 @@ var AgyAdapter = class extends LlmAdapter {
36192
36428
  }
36193
36429
  if (samePrompt && prevPrompt !== void 0 && prevPrompt.inFlight && liveRun === void 0 && now - prevPrompt.startedAt < 2e3) throw new LlmError("Duplicate request ignored: an identical request is already running for this session.", Err.BUSY);
36194
36430
  if (runLive && !samePrompt) {
36195
- const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
36196
- if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
36197
- conversationId: liveCid,
36198
- lastMessageCount: Math.max(0, lastAssistantIdx + 1),
36199
- updatedAt: Date.now(),
36200
- model: currentModel,
36201
- interrupted: true
36202
- };
36203
- else if (binding !== void 0) binding.interrupted = true;
36204
36431
  if (liveRun.hasResult) {
36205
36432
  if (!await waitForRunSettle(liveRun, 1500)) this.deps.log?.("previous agy run did not exit within 1.5s after producing its result — preempting it");
36206
36433
  }
36434
+ const wasConsumable = liveRun.hasConsumableResult;
36207
36435
  if (!liveRun.isSettled) {
36436
+ const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
36437
+ if (!wasConsumable) {
36438
+ if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
36439
+ conversationId: liveCid,
36440
+ lastMessageCount: Math.max(0, lastAssistantIdx + 1),
36441
+ updatedAt: Date.now(),
36442
+ model: currentModel,
36443
+ interrupted: true
36444
+ };
36445
+ else if (binding !== void 0) binding.interrupted = true;
36446
+ }
36208
36447
  liveRun.requestAbort?.();
36209
36448
  if (!await waitForRunSettle(liveRun, 3500)) this.warnOnce("settle-timeout:" + sessionKey, "the preempted agy run did not exit within 3.5s — starting the replacement anyway; its late write-back is ignored because the newer run owns the session");
36210
- if (!prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
36449
+ if (!wasConsumable && !prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
36211
36450
  }
36212
36451
  }
36213
36452
  this.activeSessionPrompts.set(sessionKey, {
package/dist/index.js CHANGED
@@ -32200,10 +32200,26 @@ function presentMirrorCall(args) {
32200
32200
  default: return presentDefaultCall(input, name, server);
32201
32201
  }
32202
32202
  }
32203
+ function formatBackgroundTerminalOutput(text) {
32204
+ const taskMatch = /\b(task-\d+)\b/i.exec(text);
32205
+ if (!(/^Tool is running as a background task(?:\s*\([^)]+\))?(?::\s*.*)?$/i.test(text) || /^Running in background\b/i.test(text)) || /tasks[\\/]+task-\d+\.log/i.test(text)) return text;
32206
+ const hint = taskMatch ? `[background] ${taskMatch[1]} running — live lines stream from .system_generated/tasks/${taskMatch[1]}.log; completion arrives via background message.` : "[background] running in background — awaiting completion notice.";
32207
+ return text === "" ? hint : `${text}\n${hint}`;
32208
+ }
32209
+ function formatScheduleResultOutput(input, text) {
32210
+ const cron = pick(input, "CronExpression", "cron_expression");
32211
+ const duration = pick(input, "DurationSeconds", "duration_seconds");
32212
+ const prompt = pick(input, "Prompt", "prompt");
32213
+ const timing = cron ? `cron ${cron}` : duration ? `${duration}s timer` : "schedule";
32214
+ const header = prompt ? `[scheduled] ${timing} — ${prompt}` : `[scheduled] ${timing}`;
32215
+ if (text === "" || /^Tool is running as a background task/i.test(text)) return header;
32216
+ return `${header}\n${text}`;
32217
+ }
32203
32218
  /** Native completed-card projection for one mirrored agy tool call. */
32204
32219
  function presentMirrorResult(args, result) {
32205
32220
  const a = args;
32206
- const name = unwrapMcpTool(typeof a?.tool === "string" ? a.tool : "", a?.input).tool;
32221
+ const unwrapped = unwrapMcpTool(typeof a?.tool === "string" ? a.tool : "", a?.input);
32222
+ const name = unwrapped.tool;
32207
32223
  const text = cleanResultText(resultText$1(result.content));
32208
32224
  switch (name) {
32209
32225
  case "run_command":
@@ -32218,10 +32234,17 @@ function presentMirrorResult(args, result) {
32218
32234
  else if (/\[command timed out/i.test(text) || result.isError) exitCode = 1;
32219
32235
  return {
32220
32236
  card: "terminal",
32221
- output: text,
32237
+ output: formatBackgroundTerminalOutput(text),
32222
32238
  ...exitCode !== void 0 ? { exitCode } : {}
32223
32239
  };
32224
32240
  }
32241
+ case "schedule": return {
32242
+ card: "generic",
32243
+ content: [{
32244
+ type: "text",
32245
+ text: clip$1(formatScheduleResultOutput(unwrapped.input, text), 4e3)
32246
+ }]
32247
+ };
32225
32248
  case "replace_file_content":
32226
32249
  case "write_to_file":
32227
32250
  case "write_file":
@@ -32536,6 +32559,29 @@ function buildToolCallBlock(input) {
32536
32559
  }
32537
32560
  //#endregion
32538
32561
  //#region src/provider/mapper/event-mapper.ts
32562
+ function formatRunningToolFallback(toolName, rawArgs) {
32563
+ const unwrapped = unwrapMcpTool(toolName, rawArgs);
32564
+ const a = unwrapped.input;
32565
+ const str = (...keys) => {
32566
+ for (const k of keys) {
32567
+ const v = a[k];
32568
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
32569
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
32570
+ }
32571
+ return "";
32572
+ };
32573
+ if (unwrapped.tool === "schedule") {
32574
+ const cron = str("CronExpression", "cron_expression");
32575
+ const dur = str("DurationSeconds", "duration_seconds");
32576
+ const prompt = str("Prompt", "prompt");
32577
+ const timing = cron ? `cron ${cron}` : dur ? `${dur}s timer` : "schedule";
32578
+ return prompt ? `Schedule active (${timing}): ${prompt}` : `Schedule active (${timing})`;
32579
+ }
32580
+ const cmd = str("CommandLine", "command_line", "command", "cmd");
32581
+ const taskId = str("TaskId", "taskId", "task_id", "bgTaskId");
32582
+ if (cmd !== "") return `Tool is running as a background task${taskId ? ` (${taskId})` : ""}: ${cmd}`;
32583
+ return taskId ? `Tool is running as a background task (${taskId})` : "Tool is running as a background task";
32584
+ }
32539
32585
  var EventMapper = class {
32540
32586
  opts;
32541
32587
  blockIdx = 0;
@@ -32778,7 +32824,7 @@ var EventMapper = class {
32778
32824
  }
32779
32825
  return;
32780
32826
  }
32781
- if (ev.state === "RUNNING" && ev.tool.output === void 0) ev.tool.output = ev.text !== "" ? ev.text : "Tool is running as a background task";
32827
+ if (ev.state === "RUNNING" && (ev.tool.output === void 0 || ev.tool.output === "")) ev.tool.output = ev.text !== "" ? ev.text : formatRunningToolFallback(ev.tool.name, ev.tool.args);
32782
32828
  if (this.announcedTools.has(ev.stepKey)) return;
32783
32829
  this.announcedTools.add(ev.stepKey);
32784
32830
  if (!this.opts.cutOnTool) return;
@@ -35448,6 +35494,205 @@ function readAgyRunLogText(homeDir, before) {
35448
35494
  return parts.join("\n");
35449
35495
  }
35450
35496
  //#endregion
35497
+ //#region src/features/subagent/task-activity.ts
35498
+ const MAX_READ_BYTES_PER_POLL = 131072;
35499
+ const MAX_LINES_PER_POLL = 20;
35500
+ const MAX_LINE_CHARS = 220;
35501
+ const MAX_MESSAGE_CHARS = 240;
35502
+ function noteWarn(log, context, err) {
35503
+ const detail = err instanceof Error ? err.message : String(err);
35504
+ log?.(`[task-activity] ${context}: ${detail}`);
35505
+ }
35506
+ function clipSingleLine(text, maxChars) {
35507
+ const single = text.replace(/\r/g, "").replace(/\s+/g, " ").trim();
35508
+ if (single.length <= maxChars) return single;
35509
+ return single.slice(0, Math.max(0, maxChars - 1)) + "…";
35510
+ }
35511
+ function formatTaskLogLine(taskId, line) {
35512
+ return `[后台任务 · ${taskId}] ${clipSingleLine(line, MAX_LINE_CHARS)}`;
35513
+ }
35514
+ function summarizeMessageJson(rawObj, fallbackName = "message") {
35515
+ if (!rawObj || typeof rawObj !== "object") return null;
35516
+ const obj = rawObj;
35517
+ const id = typeof obj.id === "string" && obj.id.trim() !== "" ? obj.id.trim() : "";
35518
+ const rawSender = typeof obj.sender === "string" ? obj.sender.trim() : "";
35519
+ const senderLabel = rawSender.includes("/") ? rawSender.slice(rawSender.lastIndexOf("/") + 1) : rawSender || "system";
35520
+ const details = obj.renderDetails && typeof obj.renderDetails === "object" ? obj.renderDetails : void 0;
35521
+ const title = typeof details?.messageTitle === "string" ? clipSingleLine(details.messageTitle, 120) : "";
35522
+ const content = typeof obj.content === "string" ? clipSingleLine(obj.content, MAX_MESSAGE_CHARS) : "";
35523
+ if (title === "" && content === "") return null;
35524
+ const body = title !== "" && content !== "" && !content.toLowerCase().includes(title.toLowerCase()) ? `${title} — ${content}` : content !== "" ? content : title;
35525
+ return {
35526
+ dedupKey: id !== "" ? id : fallbackName,
35527
+ text: `[后台通知 · ${senderLabel}] ${body}`
35528
+ };
35529
+ }
35530
+ function listFilesSafe(dir, suffix) {
35531
+ if (!existsSync(dir)) return [];
35532
+ try {
35533
+ return readdirSync(dir).filter((f) => f.endsWith(suffix)).sort();
35534
+ } catch {
35535
+ return [];
35536
+ }
35537
+ }
35538
+ var TaskActivityTracker = class {
35539
+ log;
35540
+ logs = /* @__PURE__ */ new Map();
35541
+ seenMessageFiles = /* @__PURE__ */ new Set();
35542
+ seenMessageIds = /* @__PURE__ */ new Set();
35543
+ baselined = false;
35544
+ constructor(log) {
35545
+ this.log = log;
35546
+ }
35547
+ reset() {
35548
+ this.logs.clear();
35549
+ this.seenMessageFiles.clear();
35550
+ this.seenMessageIds.clear();
35551
+ this.baselined = false;
35552
+ }
35553
+ /** Record pre-existing logs and messages at EOF so resumed runs only emit new activity. */
35554
+ baseline(brainDir) {
35555
+ this.baselined = true;
35556
+ this.scanTaskLogs(brainDir, true, () => {});
35557
+ this.scanMessages(brainDir, true, () => {});
35558
+ }
35559
+ poll(brainDir, emit) {
35560
+ try {
35561
+ this.scanTaskLogs(brainDir, false, emit);
35562
+ this.scanMessages(brainDir, false, emit);
35563
+ } catch (err) {
35564
+ noteWarn(this.log, "poll", err);
35565
+ }
35566
+ }
35567
+ scanTaskLogs(brainDir, baselineOnly, emit) {
35568
+ const tasksDir = join(brainDir, ".system_generated", "tasks");
35569
+ for (const file of listFilesSafe(tasksDir, ".log")) {
35570
+ const taskId = file.slice(0, -4);
35571
+ const fullPath = join(tasksDir, file);
35572
+ let tracked = this.logs.get(file);
35573
+ if (!tracked) {
35574
+ let initialOffset = 0;
35575
+ if (baselineOnly || this.baselined) {
35576
+ if (baselineOnly) try {
35577
+ const st = statSync(fullPath);
35578
+ if (st.isFile()) initialOffset = st.size;
35579
+ } catch {
35580
+ initialOffset = 0;
35581
+ }
35582
+ }
35583
+ tracked = {
35584
+ taskId,
35585
+ filePath: fullPath,
35586
+ offset: initialOffset,
35587
+ decoder: new StringDecoder("utf8"),
35588
+ rest: "",
35589
+ seq: 0
35590
+ };
35591
+ this.logs.set(file, tracked);
35592
+ }
35593
+ if (baselineOnly) continue;
35594
+ this.pollSingleTaskLog(tracked, emit);
35595
+ }
35596
+ }
35597
+ pollSingleTaskLog(tracked, emit) {
35598
+ let size;
35599
+ try {
35600
+ const st = statSync(tracked.filePath);
35601
+ if (!st.isFile()) return;
35602
+ size = st.size;
35603
+ } catch {
35604
+ return;
35605
+ }
35606
+ if (size < tracked.offset) {
35607
+ tracked.offset = 0;
35608
+ tracked.decoder = new StringDecoder("utf8");
35609
+ tracked.rest = "";
35610
+ }
35611
+ if (size === tracked.offset) return;
35612
+ const toRead = Math.min(size - tracked.offset, MAX_READ_BYTES_PER_POLL);
35613
+ const buffer = Buffer.allocUnsafe(toRead);
35614
+ let bytesRead = 0;
35615
+ try {
35616
+ const fd = openSync(tracked.filePath, "r");
35617
+ try {
35618
+ bytesRead = readSync(fd, buffer, 0, toRead, tracked.offset);
35619
+ } finally {
35620
+ closeSync(fd);
35621
+ }
35622
+ } catch {
35623
+ return;
35624
+ }
35625
+ if (bytesRead <= 0) return;
35626
+ tracked.offset += bytesRead;
35627
+ const parts = (tracked.rest + tracked.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
35628
+ tracked.rest = size > tracked.offset ? "" : parts.pop() ?? "";
35629
+ if (size > tracked.offset) {
35630
+ tracked.offset = size;
35631
+ tracked.decoder = new StringDecoder("utf8");
35632
+ }
35633
+ const lines = parts.map((l) => l.trim()).filter((l) => l !== "");
35634
+ if (lines.length === 0) return;
35635
+ const skipped = Math.max(0, lines.length - MAX_LINES_PER_POLL);
35636
+ const visible = skipped > 0 ? lines.slice(-20) : lines;
35637
+ if (skipped > 0) {
35638
+ tracked.seq += 1;
35639
+ emit({
35640
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
35641
+ text: `[后台任务 · ${tracked.taskId}] … 跳过 ${skipped} 行中间输出,最新日志如下\n`,
35642
+ raw: {
35643
+ kind: "task-log",
35644
+ taskId: tracked.taskId,
35645
+ skipped
35646
+ }
35647
+ });
35648
+ }
35649
+ for (const line of visible) {
35650
+ tracked.seq += 1;
35651
+ emit({
35652
+ stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
35653
+ text: `${formatTaskLogLine(tracked.taskId, line)}\n`,
35654
+ raw: {
35655
+ kind: "task-log",
35656
+ taskId: tracked.taskId,
35657
+ line
35658
+ }
35659
+ });
35660
+ }
35661
+ }
35662
+ scanMessages(brainDir, baselineOnly, emit) {
35663
+ const baseDir = join(brainDir, ".system_generated", "messages");
35664
+ const dirs = [{
35665
+ tag: "delivered",
35666
+ path: baseDir
35667
+ }, {
35668
+ tag: "undelivered",
35669
+ path: join(baseDir, "undelivered")
35670
+ }];
35671
+ for (const dir of dirs) for (const file of listFilesSafe(dir.path, ".json")) {
35672
+ const fileKey = `${dir.tag}:${file}`;
35673
+ if (this.seenMessageFiles.has(fileKey)) continue;
35674
+ this.seenMessageFiles.add(fileKey);
35675
+ const stem = file.slice(0, -5);
35676
+ let parsed;
35677
+ try {
35678
+ parsed = JSON.parse(readFileSync(join(dir.path, file), "utf8"));
35679
+ } catch {
35680
+ continue;
35681
+ }
35682
+ const summary = summarizeMessageJson(parsed, stem);
35683
+ if (!summary) continue;
35684
+ if (this.seenMessageIds.has(summary.dedupKey)) continue;
35685
+ this.seenMessageIds.add(summary.dedupKey);
35686
+ if (baselineOnly) continue;
35687
+ emit({
35688
+ stepKey: `task-msg-${summary.dedupKey}`,
35689
+ text: `${summary.text}\n`,
35690
+ raw: parsed
35691
+ });
35692
+ }
35693
+ }
35694
+ };
35695
+ //#endregion
35451
35696
  //#region src/features/subagent/tracker.ts
35452
35697
  /**
35453
35698
  * Swallow the failures a live transcript produces by design — a row still being
@@ -35530,6 +35775,7 @@ var SubagentTracker = class {
35530
35775
  brainDir = null;
35531
35776
  trackedSubagents = /* @__PURE__ */ new Map();
35532
35777
  seenStepKeys = /* @__PURE__ */ new Set();
35778
+ taskActivity;
35533
35779
  timer = null;
35534
35780
  active = false;
35535
35781
  polling = false;
@@ -35539,6 +35785,7 @@ var SubagentTracker = class {
35539
35785
  this.conversationId = opts.conversationId ?? "";
35540
35786
  this.accountHome = opts.accountHome;
35541
35787
  this.pollIntervalMs = opts.pollIntervalMs ?? 500;
35788
+ this.taskActivity = new TaskActivityTracker(opts.log);
35542
35789
  }
35543
35790
  /** Follow the conversation agy reported in its stream-json init/result envelope. */
35544
35791
  setConversationId(cid) {
@@ -35546,6 +35793,7 @@ var SubagentTracker = class {
35546
35793
  this.conversationId = cid;
35547
35794
  this.brainDir = null;
35548
35795
  this.baselined = false;
35796
+ this.taskActivity.reset();
35549
35797
  if (this.active) {
35550
35798
  if (this.opts.resumed === true) {
35551
35799
  this.baselined = true;
@@ -35570,6 +35818,7 @@ var SubagentTracker = class {
35570
35818
  try {
35571
35819
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35572
35820
  if (!this.brainDir) return;
35821
+ this.taskActivity.baseline(this.brainDir);
35573
35822
  this.scanSubagentsForConv(this.conversationId, true);
35574
35823
  for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
35575
35824
  } catch (err) {
@@ -35577,10 +35826,14 @@ var SubagentTracker = class {
35577
35826
  }
35578
35827
  }
35579
35828
  stop() {
35580
- this.active = false;
35581
- if (this.timer) {
35582
- clearInterval(this.timer);
35583
- this.timer = null;
35829
+ try {
35830
+ if (this.active && !this.polling && this.conversationId !== "") this.poll();
35831
+ } finally {
35832
+ this.active = false;
35833
+ if (this.timer) {
35834
+ clearInterval(this.timer);
35835
+ this.timer = null;
35836
+ }
35584
35837
  }
35585
35838
  }
35586
35839
  /** Run one scan across known conversations and subagents. */
@@ -35591,6 +35844,9 @@ var SubagentTracker = class {
35591
35844
  try {
35592
35845
  if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
35593
35846
  if (!this.brainDir) return;
35847
+ this.taskActivity.poll(this.brainDir, (ev) => {
35848
+ this.emitSubagentEvent(ev.stepKey, ev.text, ev.raw);
35849
+ });
35594
35850
  const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
35595
35851
  for (const cid of convsToScan) this.scanSubagentsForConv(cid);
35596
35852
  for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
@@ -35868,6 +36124,9 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
35868
36124
  tracker?.start();
35869
36125
  proc.outcome.finally(() => tracker?.stop());
35870
36126
  },
36127
+ startTracker: () => {
36128
+ tracker?.start();
36129
+ },
35871
36130
  feedLine: (line, onEvent, onFirstEvent) => {
35872
36131
  watchdog.markEvent();
35873
36132
  onFirstEvent?.();
@@ -36932,22 +37191,25 @@ var AgyAdapter = class extends LlmAdapter {
36932
37191
  }
36933
37192
  if (samePrompt && prevPrompt !== void 0 && prevPrompt.inFlight && liveRun === void 0 && now - prevPrompt.startedAt < 2e3) throw new LlmError("Duplicate request ignored: an identical request is already running for this session.", Err.BUSY);
36934
37193
  if (runLive && !samePrompt) {
36935
- const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
36936
- if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
36937
- conversationId: liveCid,
36938
- lastMessageCount: Math.max(0, lastAssistantIdx + 1),
36939
- updatedAt: Date.now(),
36940
- model: currentModel,
36941
- interrupted: true
36942
- };
36943
- else if (binding !== void 0) binding.interrupted = true;
36944
37194
  if (liveRun.hasResult) {
36945
37195
  if (!await waitForRunSettle(liveRun, 1500)) this.deps.log?.("previous agy run did not exit within 1.5s after producing its result — preempting it");
36946
37196
  }
37197
+ const wasConsumable = liveRun.hasConsumableResult;
36947
37198
  if (!liveRun.isSettled) {
37199
+ const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
37200
+ if (!wasConsumable) {
37201
+ if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
37202
+ conversationId: liveCid,
37203
+ lastMessageCount: Math.max(0, lastAssistantIdx + 1),
37204
+ updatedAt: Date.now(),
37205
+ model: currentModel,
37206
+ interrupted: true
37207
+ };
37208
+ else if (binding !== void 0) binding.interrupted = true;
37209
+ }
36948
37210
  liveRun.requestAbort?.();
36949
37211
  if (!await waitForRunSettle(liveRun, 3500)) this.warnOnce("settle-timeout:" + sessionKey, "the preempted agy run did not exit within 3.5s — starting the replacement anyway; its late write-back is ignored because the newer run owns the session");
36950
- if (!prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
37212
+ if (!wasConsumable && !prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
36951
37213
  }
36952
37214
  }
36953
37215
  this.activeSessionPrompts.set(sessionKey, {
@@ -45982,8 +46244,9 @@ async function runAcpAttempt(pool, deps, input, slot) {
45982
46244
  proc.cancelSession(sid);
45983
46245
  return settleEarlyAbort(deps, input, slot, sid, "request aborted after ACP session opened");
45984
46246
  }
45985
- const recorder = createAttemptRecorder(deps, cfg, account, sid, false);
46247
+ const recorder = createAttemptRecorder(deps, cfg, account, sid, !input.isAux);
45986
46248
  recorder.streamCid = sid;
46249
+ recorder.startTracker?.();
45987
46250
  recorder.rec.requestAbort = () => proc.cancelSession(sid);
45988
46251
  if (!input.isAux && sessionKey !== "") deps.registerActiveRun(sessionKey, recorder.rec);
45989
46252
  slot.armHandoff()?.onFirstEvent();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.6.55",
3
+ "version": "0.6.56",
4
4
  "description": "Google Antigravity (agy CLI) models for DeepSeek Harness — stream Gemini/Claude/GPT-OSS subscriptions into DSH with thinking, tool activity, token usage and in-GUI Google OAuth login.",
5
5
  "type": "module",
6
6
  "license": "MIT",