dsh-inbox-bridge 2.19.3 → 2.20.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.
package/index.js CHANGED
@@ -117,15 +117,34 @@ export function preferenceNext(current = {}, action = "", value = "", options =
117
117
  }
118
118
  if (action === "primary") {
119
119
  // Who may be woken for this repository. An empty value releases the claim.
120
- if (!sessionId) return null;
121
- const repo = value ? repoFromInput(value) : sessionRepo;
120
+ // The page may name the session it means (`target`), because the person is
121
+ // choosing among the sessions watching a repository, not necessarily
122
+ // speaking from the one that should own it.
123
+ const owner = options.targetSession ?? sessionId;
124
+ if (!owner) return null;
125
+ const repo = value ? repoFromInput(value) : (options.sessionRepo ?? null);
122
126
  if (!repo) return null;
123
127
  const primary = { ...(next.primary ?? {}) };
124
- if (value) primary[repo] = sessionId;
128
+ if (value) primary[repo] = owner;
125
129
  else delete primary[repo];
126
130
  next.primary = primary;
127
131
  return next;
128
132
  }
133
+ if (action === "idle") {
134
+ // How long a session must be quiet before a wakeup may open a turn. Minutes
135
+ // in the page, milliseconds here; zero means "as soon as nobody is busy".
136
+ const minutes = Number(value);
137
+ if (!Number.isFinite(minutes) || minutes < 0 || minutes > 24 * 60) return null;
138
+ next.wakeAfterIdleMs = Math.round(minutes * 60_000);
139
+ return next;
140
+ }
141
+ if (action === "budget") {
142
+ // How many wakeups an hour this instance may spend in total.
143
+ const perHour = Number(value);
144
+ if (!Number.isInteger(perHour) || perHour < 1 || perHour > 24) return null;
145
+ next.wakesPerHour = perHour;
146
+ return next;
147
+ }
129
148
  return null;
130
149
  }
131
150
 
@@ -381,6 +400,24 @@ export function apply(ctx, config) {
381
400
  roles: options.roles ?? [],
382
401
  }
383
402
  : null;
403
+ // A repository can be watched by several sessions in the same directory, and
404
+ // a wakeup has to reach the one the person means. Two sessions in one
405
+ // workspace have the same title and the same folder, so each name carries the
406
+ // last four characters of its id — the only thing that really tells them
407
+ // apart — and the page marks which one is asking and which one would take a
408
+ // wakeup right now.
409
+ const viewers = repo
410
+ ? [...agents.entries()]
411
+ .map(([id, each]) => ({
412
+ id,
413
+ label: sessionLabel(each),
414
+ tag: sessionTag(each),
415
+ repo: repoOf(each),
416
+ recent: lastActive.get(each) ?? 0,
417
+ current: id === sessionId,
418
+ }))
419
+ .filter((entry) => entry.repo && entry.repo.toLowerCase() === repo.toLowerCase())
420
+ : [];
384
421
  return {
385
422
  ...buildUiPayload({
386
423
  options,
@@ -388,6 +425,7 @@ export function apply(ctx, config) {
388
425
  source: readJson(join(options.cwd, SOURCE_STATE_REL)),
389
426
  recent,
390
427
  session,
428
+ viewers,
391
429
  }),
392
430
  // The page proves it is this process's page before it may change anything,
393
431
  // and shows which choices came from it rather than from the profile.
@@ -550,7 +588,18 @@ export function apply(ctx, config) {
550
588
  signIn.signedIn = true;
551
589
  log(`swept the notification inbox: ${line || "done"} (${Date.now() - began}ms)`);
552
590
  } catch (error) {
553
- if (error?.exitCode === 2) {
591
+ // The command's own answer outranks its exit code. `--json` prints
592
+ // `{ ok: true, … }` even when the process ends non-zero (a browser it could
593
+ // not fully close, say), and reporting that as a failure would teach people
594
+ // to ignore the line that is supposed to mean "this is broken".
595
+ const answer = parseJsonAnswer(error?.stdout);
596
+ if (answer?.ok === true) {
597
+ signIn.signedIn = true;
598
+ const archived = Number.isFinite(answer.archived) ? `${answer.archived} thread(s)` : "done";
599
+ log(`swept the notification inbox: ${archived} (${Date.now() - began}ms)`);
600
+ return;
601
+ }
602
+ if (error?.exitCode === 2 || answer?.reason === "sign-in-required") {
554
603
  // The command says "sign-in required"; raise the window rather than
555
604
  // asking the operator to copy a command out of the log.
556
605
  signIn.signedIn = false;
@@ -884,6 +933,10 @@ export function apply(ctx, config) {
884
933
  const action = url.searchParams.get("set") ?? "";
885
934
  const value = url.searchParams.get("value") ?? "";
886
935
  const sessionId = url.searchParams.get("session") || null;
936
+ // A claim names the session that should own a repository, which is
937
+ // not always the session the page is drawn for.
938
+ const named = url.searchParams.get("target") || null;
939
+ const targetSession = named && agents.has(named) ? named : null;
887
940
  // Which repository the session lives in, so "subscribe my repo" and
888
941
  // "unsubscribe the last one" know what the default is.
889
942
  const sessionRepo = sessionId ? repoOf(agents.get(sessionId)) : null;
@@ -901,6 +954,7 @@ export function apply(ctx, config) {
901
954
  ...options,
902
955
  sessionId,
903
956
  sessionRepo,
957
+ targetSession,
904
958
  });
905
959
  if (action === "signin") {
906
960
  // Not a setting: open the window that archiving needs.
@@ -1022,8 +1076,9 @@ export function wakePlan(batches, options, state = {}) {
1022
1076
  // Opening a turn is expensive and public: whoever gets it suddenly starts
1023
1077
  // working. Several sessions can share one workspace, and then they all watch
1024
1078
  // the same repository, so "the session on this repository" is not an answer.
1025
- // A repository therefore wakes its responsible session — claimed in the page —
1026
- // and stays silent while more than one session watches it without a claim.
1079
+ // Every repository therefore has exactly one owner: the one you claimed in the
1080
+ // page, or — when nothing is claimed — the session you spoke to most recently,
1081
+ // which is the one you were working in when you walked away.
1027
1082
  const watchers = new Map();
1028
1083
  for (const [agent, events] of batches ?? []) {
1029
1084
  for (const event of events) {
@@ -1033,6 +1088,22 @@ export function wakePlan(batches, options, state = {}) {
1033
1088
  }
1034
1089
  }
1035
1090
 
1091
+ const ownerOf = (repo) => {
1092
+ const claimed = primary[repo] ?? null;
1093
+ if (claimed) return claimed;
1094
+ let best = null;
1095
+ let bestAt = -1;
1096
+ for (const watcher of watchers.get(repo) ?? []) {
1097
+ const at = lastActive.get(watcher) ?? 0;
1098
+ const name = keyOf(watcher) ?? "";
1099
+ if (at > bestAt || (at === bestAt && best && name < (keyOf(best) ?? ""))) {
1100
+ best = watcher;
1101
+ bestAt = at;
1102
+ }
1103
+ }
1104
+ return best ? (keyOf(best) ?? null) : null;
1105
+ };
1106
+
1036
1107
  const recentWakes = wakes.filter((at) => now - at < 60 * 60 * 1000).length;
1037
1108
  let considered = 0;
1038
1109
  let why = "no-match";
@@ -1042,14 +1113,13 @@ export function wakePlan(batches, options, state = {}) {
1042
1113
  if (!wakeOn.includes(role)) continue;
1043
1114
  considered += 1;
1044
1115
  const repo = event.repo ?? "";
1045
- const owner = primary[repo] ?? null;
1046
1116
  const key = keyOf(agent);
1117
+ const owner = ownerOf(repo);
1047
1118
  if (owner && key !== owner) {
1048
- why = "not-primary";
1049
- continue;
1050
- }
1051
- if (!owner && (watchers.get(repo)?.size ?? 0) > 1) {
1052
- why = "ambiguous";
1119
+ // An explicit claim is a decision the operator made; falling back to
1120
+ // "most recent" silently would break it. The default is not a decision,
1121
+ // so it is allowed to move as you move between sessions.
1122
+ why = primary[repo] ? "not-primary" : "not-recent";
1053
1123
  continue;
1054
1124
  }
1055
1125
  if (recentWakes >= perHour) {
@@ -1073,7 +1143,12 @@ export function wakePlan(batches, options, state = {}) {
1073
1143
  /** A stable, human-readable name for a session in the log. */
1074
1144
  export function sessionLabel(agent) {
1075
1145
  const header = agent?.session?.header ?? {};
1076
- const cwd = header.cwd ?? header.title ?? null;
1146
+ // The title is what the session list shows ("主维护", "本地修复"); a workspace
1147
+ // path is a fallback, and two sessions in one workspace then read the same —
1148
+ // which is why the page adds a short id to every name it offers.
1149
+ const title = typeof header.title === "string" ? header.title.trim() : "";
1150
+ if (title.length > 0) return title;
1151
+ const cwd = header.cwd ?? null;
1077
1152
  if (typeof cwd === "string" && cwd.length > 0) {
1078
1153
  const parts = cwd.replace(/[\\/]+$/u, "").split(/[\\/]/u);
1079
1154
  return parts[parts.length - 1] || cwd;
@@ -1081,6 +1156,12 @@ export function sessionLabel(agent) {
1081
1156
  return agent?.session?.id ?? "session";
1082
1157
  }
1083
1158
 
1159
+ /** The last four characters of a session id: enough to tell twins apart. */
1160
+ export function sessionTag(agent) {
1161
+ const id = keyOf(agent) ?? "";
1162
+ return id.length > 4 ? id.slice(-4) : id;
1163
+ }
1164
+
1084
1165
  /** `owner/name` a session workspace points at, cached for a short while. */
1085
1166
  export function repoOf(agent, options, cache = new Map(), now = Date.now()) {
1086
1167
  const hit = cache.get(agent);
@@ -1366,6 +1447,10 @@ function runCommand(spec, options, extraEnv = {}) {
1366
1447
  // needs a person once" (the sweep needs a browser sign-in), which is
1367
1448
  // not the same problem as a crashed command.
1368
1449
  if (typeof error.code === "number") failure.exitCode = error.code;
1450
+ // Keep the command's own words: a `--json` run may have answered while
1451
+ // still exiting non-zero, and the answer is the better evidence.
1452
+ failure.stdout = stdout ?? "";
1453
+ failure.stderr = stderr ?? "";
1369
1454
  reject(failure);
1370
1455
  return;
1371
1456
  }
@@ -1403,10 +1488,10 @@ export function filterUndelivered(events, seen, now, resurfaceMs) {
1403
1488
 
1404
1489
  export function pollLabel(ms) {
1405
1490
  const value = Number.isFinite(ms) ? ms : DEFAULTS.intervalMs;
1406
- const minutes = Math.round(value / 60_000);
1407
- if (minutes >= 1) return `${minutes} 分钟`;
1408
- // A sub-minute interval is legitimate in tests and while debugging; "0 分钟"
1409
- // would read as "never".
1491
+ // Round numbers of minutes read best ("15 分钟"); anything else is stated in
1492
+ // seconds, because 90 000 ms is not "2 分钟" — it is 90 秒, and rounding it up
1493
+ // makes the notice promise a wait longer than it will be.
1494
+ if (value >= 60_000 && value % 60_000 === 0) return `${Math.round(value / 60_000)} 分钟`;
1410
1495
  return `${Math.max(1, Math.round(value / 1_000))} 秒`;
1411
1496
  }
1412
1497
 
@@ -1474,6 +1559,7 @@ export function buildUiPayload({
1474
1559
  now = Date.now(),
1475
1560
  session = null,
1476
1561
  signIn = null,
1562
+ viewers = null,
1477
1563
  }) {
1478
1564
  const configured = options.repos?.length > 0 ? options.repos : options.repo ? [options.repo] : [];
1479
1565
  // A session sees exactly what a poll would deliver to it: the repositories it
@@ -1511,6 +1597,27 @@ export function buildUiPayload({
1511
1597
  .sort((left, right) => String(right.at ?? "").localeCompare(String(left.at ?? "")))
1512
1598
  .slice(0, 20);
1513
1599
  const identity = options.identity ?? DEFAULTS.identity;
1600
+ // How a wakeup may happen, in the terms the page can change: which roles, how
1601
+ // quiet a session must be, how many an hour, and which session owns the
1602
+ // repository this page is looking at.
1603
+ const claims = options.primary ?? {};
1604
+ const ownerOf = (name) => {
1605
+ if (!name) return null;
1606
+ const wanted = String(name).toLowerCase();
1607
+ const hit = Object.keys(claims).find((key) => key.toLowerCase() === wanted);
1608
+ return hit ? claims[hit] : null;
1609
+ };
1610
+ const sessionRepo = scoped ? (session.repo ?? repos[0] ?? null) : null;
1611
+ // The session that would receive a wakeup for this repository right now: the
1612
+ // claimed one, or — with nothing claimed — the one you spoke to most recently.
1613
+ // The page shows both facts so "nobody is woken" is never a mystery.
1614
+ const watchers = (viewers ?? []).filter((entry) => entry?.id);
1615
+ const claimed = ownerOf(sessionRepo);
1616
+ const recentViewer = watchers.reduce(
1617
+ (best, entry) => ((entry.recent ?? 0) > (best?.recent ?? -1) ? entry : best),
1618
+ null,
1619
+ );
1620
+ const effectiveOwner = claimed ?? recentViewer?.id ?? null;
1514
1621
  return {
1515
1622
  at: new Date(now).toISOString(),
1516
1623
  label: options.label ?? DEFAULTS.label,
@@ -1532,6 +1639,20 @@ export function buildUiPayload({
1532
1639
  sweep: options.sweep?.when ?? null,
1533
1640
  signIn: signIn ?? { signedIn: null, open: false, attemptedAt: null },
1534
1641
  intervalMs: options.intervalMs ?? DEFAULTS.intervalMs,
1642
+ wake: {
1643
+ on: options.wakeOn ?? [],
1644
+ idleMs: options.wakeAfterIdleMs ?? DEFAULTS.wakeAfterIdleMs,
1645
+ perHour: options.wakesPerHour ?? DEFAULTS.wakesPerHour,
1646
+ primary: claimed,
1647
+ owner: effectiveOwner,
1648
+ // Who is watching this repository, which of them would take a wakeup, and
1649
+ // which one is asking the question.
1650
+ viewers: watchers.map((entry) => ({
1651
+ ...entry,
1652
+ primary: claimed === entry.id,
1653
+ owner: effectiveOwner === entry.id,
1654
+ })),
1655
+ },
1535
1656
  queue: counts,
1536
1657
  events: events.slice(0, 20),
1537
1658
  polls: repos.map((repo) => ({ repo, ...(source?.repos?.[repo]?.lastPoll ?? {}) })),
@@ -1559,3 +1680,25 @@ function describeEvent(event) {
1559
1680
  function describe(error) {
1560
1681
  return error instanceof Error ? error.message : String(error);
1561
1682
  }
1683
+
1684
+ /**
1685
+ * The last JSON object a command printed, or null. Children print progress lines
1686
+ * before their answer, so scan from the end and take the first line that parses.
1687
+ */
1688
+ function parseJsonAnswer(stdout) {
1689
+ const lines = String(stdout ?? "")
1690
+ .trim()
1691
+ .split(/\r?\n/u)
1692
+ .reverse();
1693
+ for (const line of lines) {
1694
+ const text = line.trim();
1695
+ if (!text.startsWith("{")) continue;
1696
+ try {
1697
+ const parsed = JSON.parse(text);
1698
+ if (parsed && typeof parsed === "object") return parsed;
1699
+ } catch {
1700
+ // Not the answer; keep looking.
1701
+ }
1702
+ }
1703
+ return null;
1704
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-inbox-bridge",
3
- "version": "2.19.3",
3
+ "version": "2.20.1",
4
4
  "displayName": "GitHub inbox",
5
5
  "description": "DSH 插件:让 agent 像维护者一样盯着你的仓库——按会话订阅仓库,取回与你有关、需要你处理的事件(失败的 CI、待评审的 PR、指派给你的 issue、@你的评论、开着的安全告警),在自己的回合送进上下文;会话空闲又遇到要紧的事时也能主动开一轮,让 agent 自己去修、去审、去接。",
6
6
  "type": "module",