dsh-ustc-campus 0.2.15 → 0.3.3

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/src/mcp-host.mjs CHANGED
@@ -36,8 +36,9 @@ import { libraryPlanLink } from './result-links.mjs';
36
36
 
37
37
  const SOURCE_URL = 'https://jw.ustc.edu.cn/for-std/course-table';
38
38
  const IPC_MAX_REQUEST_BYTES = 16 * 1024;
39
- const IPC_TIMEOUT_MS = 70_000;
40
- const SUMMARY_TIMEOUT_MS = 45_000;
39
+ const IPC_CONNECTION_TIMEOUT_MS = 5_000;
40
+ const READ_TIMEOUT_MS = 25_000;
41
+ const BATCH_TIMEOUT_MS = 45_000;
41
42
  const UPLOAD_TIMEOUT_MS = 60_000;
42
43
  const MAX_COUNT = 1_000_000;
43
44
  const RANGE_LIMIT_DAYS = 31;
@@ -582,7 +583,8 @@ const bbStatusMessages = {
582
583
  stopped_before_write: '已取消本次提交。',
583
584
  uncertain: '提交状态暂未核实,请查看 Blackboard 官方记录或用 bb_submission_status 复查。'
584
585
  };
585
- export function bbFeedback({ id, assignment, preparation: p, busy }) {
586
+ export function bbFeedback({ id, assignment, preparation: p, busy, state: status, message }) {
587
+ if (status === 'not_found') return { state: status, id, message };
586
588
  const state = busy ? 'processing' : p?.state ?? 'awaiting_materials';
587
589
  return { id, assignment, state, message: bbStatusMessages[state], preparation: p ? {
588
590
  state: p.state,
@@ -702,27 +704,12 @@ export function createHostHandlers(ctx) {
702
704
  if (ctx?.ustcTransit) handlers['campus-shuttle'] = ({fromCampus,toCampus,date,scheduleType}) => ctx.ustcTransit.read({fromCampus,toCampus,date,scheduleType});
703
705
  if (ctx?.ustcCampus && typeof ctx.ustcCampus.queryFeed === 'function') {
704
706
  handlers['feed-query'] = async (args = {}) => {
705
- const courseTitles = typeof ctx.ustcCampus.cachedCourseTitles === 'function' ? ctx.ustcCampus.cachedCourseTitles() : [];
706
- const extra = typeof ctx.ustcCampus.getExtraFeedData === 'function'
707
- ? await ctx.ustcCampus.getExtraFeedData(false)
708
- : { extraItems: [], extraSources: [] };
709
- const queryArgs = {
710
- source: args.source,
711
- category: args.category,
712
- intent: args.intent,
713
- keyword: args.keyword,
714
- sort: args.sort,
715
- interests: args.interests,
716
- courseTitles,
717
- ...extra
718
- };
707
+ const queryArgs = { source: args.source, category: args.category, intent: args.intent,
708
+ keyword: args.keyword, sort: args.sort, interests: args.interests };
719
709
  let feed = ctx.ustcCampus.queryFeed(queryArgs);
720
710
  if (feed.sources.length > 0 && feed.sources.every((entry) => entry.fetchedAt == null)) {
721
711
  await ctx.ustcCampus.refresh();
722
- const refreshedExtra = typeof ctx.ustcCampus.getExtraFeedData === 'function'
723
- ? await ctx.ustcCampus.getExtraFeedData(true)
724
- : extra;
725
- feed = ctx.ustcCampus.queryFeed({ ...queryArgs, ...refreshedExtra });
712
+ feed = ctx.ustcCampus.queryFeed(queryArgs);
726
713
  }
727
714
  const limit = Math.min(30, Math.max(1, Math.trunc(Number(args.limit) || 10)));
728
715
  const offset = Math.min(feed.items.length, Math.max(0, Math.trunc(Number(args.offset) || 0)));
@@ -800,7 +787,7 @@ export async function createCampusPipe({ handlers } = {}) {
800
787
  sockets.delete(socket);
801
788
  socket.destroy();
802
789
  };
803
- const timer = setTimeout(drop, IPC_TIMEOUT_MS);
790
+ let timer = setTimeout(drop, IPC_CONNECTION_TIMEOUT_MS);
804
791
  timer.unref?.();
805
792
 
806
793
  const reply = (payload) => {
@@ -855,15 +842,23 @@ export async function createCampusPipe({ handlers } = {}) {
855
842
  return;
856
843
  }
857
844
  processing = true;
845
+ clearTimeout(timer);
858
846
 
859
847
  let value;
860
848
  try {
861
- const opTimeout = request.op === 'bb-submit' ? UPLOAD_TIMEOUT_MS : SUMMARY_TIMEOUT_MS;
849
+ const opTimeout = request.op === 'bb-submit' ? UPLOAD_TIMEOUT_MS
850
+ : request.op === 'bb-assignments' && args.checkStatus === true ? BATCH_TIMEOUT_MS : READ_TIMEOUT_MS;
851
+ timer = setTimeout(drop, opTimeout + 1_000);
852
+ timer.unref?.();
862
853
  value = await withTimeout(
863
854
  Promise.resolve().then(() => table.get(request.op)({ ...args })),
864
855
  opTimeout
865
856
  );
866
857
  } catch (error) {
858
+ if (error?.code === 'IPC_TIMEOUT' && request.op !== 'school-status') {
859
+ reply({ v: 1, ok: false, error: 'timeout' });
860
+ return;
861
+ }
867
862
  if (request.op === 'school-status') {
868
863
  reply({ v: 1, ok: true, result: normalizeSchoolStatus({ status: error?.code === 'IPC_TIMEOUT' ? 'unavailable' : 'error' }) });
869
864
  return;
package/src/mcp.mjs CHANGED
@@ -32,7 +32,7 @@ import { bbMaterialsLink, bbResultLink, calendarReceiptLink, HS_LIBRARY_RESULT_L
32
32
  const SERVER_NAME = 'dsh-ustc-campus-mcp';
33
33
  const SERVER_VERSION = '0.3.0';
34
34
  const SOURCE_URL = 'https://jw.ustc.edu.cn/for-std/course-table';
35
- const IPC_TIMEOUT_MS = 50_000;
35
+ const IPC_TIMEOUT_MS = 26_000;
36
36
  const IPC_MAX_BYTES = 3 * 1024 * 1024;
37
37
  const MAX_COUNT = 1_000_000;
38
38
  const RANGE_LIMIT_DAYS = 31;
@@ -214,7 +214,7 @@ function requestHost(op, args = {}) {
214
214
  }
215
215
 
216
216
  socket.setEncoding('utf8');
217
- const timeoutMs = op === 'bb-submit' ? 65_000 : IPC_TIMEOUT_MS;
217
+ const timeoutMs = op === 'bb-submit' ? 61_000 : op === 'bb-assignments' && args?.checkStatus === true ? 46_000 : IPC_TIMEOUT_MS;
218
218
  timer = setTimeout(() => finish({ ok: false, code: 'unavailable', message: '请求超时,请稍后重试。' }), timeoutMs);
219
219
  timer.unref?.();
220
220
 
@@ -243,13 +243,13 @@ function requestHost(op, args = {}) {
243
243
  finish({ ok: true, value: reply.result });
244
244
  return;
245
245
  }
246
- const code = ['invalid', 'failed', 'forbidden', 'bad-request', 'too-large'].includes(reply.error)
246
+ const code = ['invalid', 'failed', 'forbidden', 'bad-request', 'too-large', 'timeout'].includes(reply.error)
247
247
  ? reply.error
248
248
  : 'failed';
249
249
  finish({
250
250
  ok: false,
251
251
  code,
252
- message: code === 'invalid' ? safePublicMessage(reply.message) : null
252
+ message: code === 'invalid' ? safePublicMessage(reply.message) : code === 'timeout' ? '请求超时,请稍后重试。' : null
253
253
  });
254
254
  });
255
255
  socket.on('error', () => finish({ ok: false, code: 'unavailable' }));
@@ -290,7 +290,8 @@ function charBigrams(str) {
290
290
  function jaccardSet(a, b) {
291
291
  if (!a || !b || a.size === 0 || b.size === 0) return 0;
292
292
  let intersection = 0;
293
- const [small, large] = a.size <= b.size ? [a, b] : [b, a];
293
+ const small = a.size <= b.size ? a : b;
294
+ const large = small === a ? b : a;
294
295
  for (const key of small) {
295
296
  if (large.has(key)) intersection += 1;
296
297
  }
@@ -1066,26 +1067,56 @@ export function createRecommender(options = {}) {
1066
1067
  let deduped = candidates;
1067
1068
  if (dedupe && candidates.length > 1) {
1068
1069
  deduped = [];
1070
+ const buckets = new Map();
1071
+ const undated = new Map();
1072
+ const allDates = new Map();
1073
+ const span = 7 * DAY_MS;
1074
+ // Rare grams first. A Jaccard match at 0.75 must share a token in
1075
+ // both prefixes of length |grams| - ceil(0.75 * |grams|) + 1.
1076
+ const counts = new Map();
1077
+ for (const { feat } of candidates) for (const gram of feat.dedupBigrams) counts.set(gram, (counts.get(gram) ?? 0) + 1);
1078
+ const index = (lookup, grams, id) => {
1079
+ for (const gram of grams) {
1080
+ let posting = lookup.get(gram);
1081
+ if (!posting) lookup.set(gram, posting = []);
1082
+ posting.push(id);
1083
+ }
1084
+ };
1069
1085
  for (const cand of candidates) {
1070
- let merged = false;
1071
- if (cand.feat.dedupKey.length >= 6) {
1072
- for (const kept of deduped) {
1073
- if (kept.feat.sourceId === cand.feat.sourceId) continue;
1074
- if (kept.feat.itemEpoch != null && cand.feat.itemEpoch != null) {
1075
- if (Math.abs(kept.feat.itemEpoch - cand.feat.itemEpoch) > 7 * DAY_MS) continue;
1076
- }
1077
- const sim = jaccardSet(kept.feat.dedupBigrams, cand.feat.dedupBigrams);
1078
- if (sim >= 0.75) {
1079
- const otherLabel = cand.sourceMeta?.label ?? cand.feat.sourceId;
1080
- if (otherLabel && !kept.alsoIn.includes(otherLabel)) {
1081
- kept.alsoIn.push(otherLabel);
1082
- }
1083
- merged = true;
1084
- break;
1086
+ const { dedupKey, dedupBigrams: grams, itemEpoch, sourceId } = cand.feat;
1087
+ const week = itemEpoch == null ? null : Math.floor(itemEpoch / span);
1088
+ const prefix = [...grams].sort((a, b) => counts.get(a) - counts.get(b) || (a < b ? -1 : a > b ? 1 : 0))
1089
+ .slice(0, grams.size - Math.ceil(0.75 * grams.size) + 1);
1090
+ let match = Infinity;
1091
+ if (dedupKey.length >= 6) {
1092
+ const checked = new Set();
1093
+ const tables = week === null ? [allDates] : [undated, buckets.get(week - 1), buckets.get(week), buckets.get(week + 1)];
1094
+ for (const table of tables) if (table) {
1095
+ for (const gram of prefix) for (const id of table.get(gram) ?? []) {
1096
+ if (id >= match || checked.has(id)) continue;
1097
+ checked.add(id);
1098
+ const feat = deduped[id].feat;
1099
+ if (feat.sourceId === sourceId) continue;
1100
+ if (itemEpoch != null && feat.itemEpoch != null && Math.abs(itemEpoch - feat.itemEpoch) > span) continue;
1101
+ if (jaccardSet(grams, feat.dedupBigrams) >= 0.75) match = id;
1085
1102
  }
1086
1103
  }
1087
1104
  }
1088
- if (!merged) deduped.push(cand);
1105
+ if (match !== Infinity) {
1106
+ const kept = deduped[match];
1107
+ const label = cand.sourceMeta?.label ?? sourceId;
1108
+ if (label && !kept.alsoIn.includes(label)) kept.alsoIn.push(label);
1109
+ } else {
1110
+ const id = deduped.length;
1111
+ deduped.push(cand);
1112
+ index(allDates, prefix, id);
1113
+ if (week === null) index(undated, prefix, id);
1114
+ else {
1115
+ let bucket = buckets.get(week);
1116
+ if (!bucket) buckets.set(week, bucket = new Map());
1117
+ index(bucket, prefix, id);
1118
+ }
1119
+ }
1089
1120
  }
1090
1121
  }
1091
1122
 
@@ -1094,28 +1125,37 @@ export function createRecommender(options = {}) {
1094
1125
  const remaining = [...deduped];
1095
1126
  const lambda = 0.78;
1096
1127
  const mmrWindow = Math.min(remaining.length, 60);
1128
+ const similarities = [];
1129
+ for (let i = 0; i < remaining.length; i++) remaining[i].rankIndex = i;
1097
1130
 
1098
1131
  while (remaining.length > 0 && selected.length < mmrWindow) {
1099
1132
  let bestIdx = 0;
1100
1133
  let bestMmr = -Infinity;
1101
- const recentWindow = selected.slice(-6);
1102
- const prev = selected[selected.length - 1] ?? null;
1134
+ const prev = selected[selected.length - 1];
1135
+ const sourceCounts = new Map();
1136
+ for (let i = Math.max(0, selected.length - 6); i < selected.length; i++) {
1137
+ const id = selected[i].feat.sourceId;
1138
+ sourceCounts.set(id, (sourceCounts.get(id) ?? 0) + 1);
1139
+ }
1140
+ let latest;
1141
+ if (prev) {
1142
+ const slot = (selected.length - 1) % 6;
1143
+ latest = similarities[slot] ??= new Float64Array(deduped.length);
1144
+ }
1103
1145
 
1104
1146
  for (let i = 0; i < remaining.length; i += 1) {
1105
1147
  const cand = remaining[i];
1106
1148
  const isPast = cand.feat.kind === 'event' && cand.item.past;
1107
1149
  let maxSim = 0;
1108
- for (const chosen of recentWindow) {
1109
- const tokSim = jaccardSet(cand.feat.tokenSet, chosen.feat.tokenSet);
1110
- if (tokSim > maxSim) maxSim = tokSim;
1111
- }
1150
+ if (latest) latest[cand.rankIndex] = jaccardSet(cand.feat.tokenSet, prev.feat.tokenSet);
1151
+ for (const scores of similarities) maxSim = Math.max(maxSim, scores[cand.rankIndex]);
1112
1152
 
1113
1153
  let streakPenalty = 0;
1114
1154
  if (!isPast) {
1115
1155
  if (prev && prev.feat.sourceId === cand.feat.sourceId) {
1116
1156
  streakPenalty += 0.18;
1117
1157
  }
1118
- const sameSourceCount = recentWindow.filter((c) => c.feat.sourceId === cand.feat.sourceId).length;
1158
+ const sameSourceCount = sourceCounts.get(cand.feat.sourceId) ?? 0;
1119
1159
  if (sameSourceCount >= 2) {
1120
1160
  streakPenalty += 0.22 * (sameSourceCount - 1);
1121
1161
  }