@nocville/npc 0.2.2 → 0.2.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.
Files changed (96) hide show
  1. package/README.md +23 -5
  2. package/dist/cjs/cli.js +55 -34
  3. package/dist/cjs/core/base-npc.js +8 -0
  4. package/dist/cjs/core/config.js +19 -2
  5. package/dist/cjs/core/errors.js +23 -0
  6. package/dist/cjs/core/http.js +121 -0
  7. package/dist/cjs/core/pixel-art.js +110 -0
  8. package/dist/cjs/core/polling-npc.js +99 -14
  9. package/dist/cjs/core/text.js +13 -0
  10. package/dist/cjs/core/thresholds.js +29 -0
  11. package/dist/cjs/index.js +10 -2
  12. package/dist/cjs/npcs/agent-common/session.js +1 -0
  13. package/dist/cjs/npcs/github-watcher/defaults.js +7 -1
  14. package/dist/cjs/npcs/github-watcher/github-api.js +82 -45
  15. package/dist/cjs/npcs/github-watcher/index.js +82 -36
  16. package/dist/cjs/npcs/internet-connectivity/checks.js +70 -67
  17. package/dist/cjs/npcs/internet-connectivity/defaults.js +5 -2
  18. package/dist/cjs/npcs/internet-connectivity/index.js +134 -131
  19. package/dist/cjs/npcs/log-watcher/buffer.js +61 -0
  20. package/dist/cjs/npcs/log-watcher/index.js +109 -103
  21. package/dist/cjs/npcs/log-watcher/tail.js +100 -53
  22. package/dist/cjs/npcs/process-watcher/index.js +61 -51
  23. package/dist/cjs/npcs/process-watcher/process-scanner.js +63 -69
  24. package/dist/cjs/npcs/receptionist/defaults.js +4 -0
  25. package/dist/cjs/npcs/receptionist/index.js +45 -19
  26. package/dist/cjs/npcs/receptionist/weather.js +42 -47
  27. package/dist/cjs/npcs/system-monitor/collectors.js +66 -17
  28. package/dist/cjs/npcs/system-monitor/index.js +52 -28
  29. package/dist/cjs/npcs/web-page-watcher/basic-mode.js +30 -14
  30. package/dist/cjs/npcs/web-page-watcher/capture.js +23 -1
  31. package/dist/cjs/npcs/web-page-watcher/defaults.js +44 -2
  32. package/dist/cjs/npcs/web-page-watcher/index.js +119 -68
  33. package/dist/cjs/npcs/web-page-watcher/pixelate.js +2 -1
  34. package/dist/cli.js +56 -35
  35. package/dist/core/base-npc.d.ts +5 -0
  36. package/dist/core/base-npc.js +8 -0
  37. package/dist/core/config.d.ts +5 -0
  38. package/dist/core/config.js +18 -2
  39. package/dist/core/errors.d.ts +11 -0
  40. package/dist/core/errors.js +18 -0
  41. package/dist/core/http.d.ts +52 -0
  42. package/dist/core/http.js +111 -0
  43. package/dist/core/pixel-art.d.ts +38 -0
  44. package/dist/core/pixel-art.js +105 -0
  45. package/dist/core/polling-npc.d.ts +22 -1
  46. package/dist/core/polling-npc.js +98 -13
  47. package/dist/core/text.d.ts +6 -0
  48. package/dist/core/text.js +12 -0
  49. package/dist/core/thresholds.d.ts +9 -1
  50. package/dist/core/thresholds.js +27 -0
  51. package/dist/index.d.ts +5 -2
  52. package/dist/index.js +4 -2
  53. package/dist/npcs/agent-common/session.js +1 -0
  54. package/dist/npcs/github-watcher/defaults.d.ts +6 -0
  55. package/dist/npcs/github-watcher/defaults.js +7 -1
  56. package/dist/npcs/github-watcher/github-api.d.ts +21 -7
  57. package/dist/npcs/github-watcher/github-api.js +80 -45
  58. package/dist/npcs/github-watcher/index.d.ts +6 -0
  59. package/dist/npcs/github-watcher/index.js +83 -37
  60. package/dist/npcs/internet-connectivity/checks.d.ts +15 -18
  61. package/dist/npcs/internet-connectivity/checks.js +70 -67
  62. package/dist/npcs/internet-connectivity/defaults.d.ts +3 -0
  63. package/dist/npcs/internet-connectivity/defaults.js +5 -2
  64. package/dist/npcs/internet-connectivity/index.d.ts +19 -6
  65. package/dist/npcs/internet-connectivity/index.js +135 -133
  66. package/dist/npcs/log-watcher/buffer.d.ts +22 -0
  67. package/dist/npcs/log-watcher/buffer.js +58 -0
  68. package/dist/npcs/log-watcher/index.d.ts +22 -21
  69. package/dist/npcs/log-watcher/index.js +112 -106
  70. package/dist/npcs/log-watcher/tail.d.ts +23 -3
  71. package/dist/npcs/log-watcher/tail.js +101 -54
  72. package/dist/npcs/process-watcher/index.d.ts +1 -1
  73. package/dist/npcs/process-watcher/index.js +62 -52
  74. package/dist/npcs/process-watcher/process-scanner.d.ts +29 -1
  75. package/dist/npcs/process-watcher/process-scanner.js +61 -71
  76. package/dist/npcs/receptionist/defaults.d.ts +4 -0
  77. package/dist/npcs/receptionist/defaults.js +4 -0
  78. package/dist/npcs/receptionist/index.d.ts +12 -2
  79. package/dist/npcs/receptionist/index.js +46 -20
  80. package/dist/npcs/receptionist/weather.d.ts +8 -6
  81. package/dist/npcs/receptionist/weather.js +39 -45
  82. package/dist/npcs/system-monitor/collectors.d.ts +15 -3
  83. package/dist/npcs/system-monitor/collectors.js +64 -17
  84. package/dist/npcs/system-monitor/defaults.d.ts +1 -1
  85. package/dist/npcs/system-monitor/index.d.ts +2 -1
  86. package/dist/npcs/system-monitor/index.js +54 -30
  87. package/dist/npcs/web-page-watcher/basic-mode.d.ts +2 -2
  88. package/dist/npcs/web-page-watcher/basic-mode.js +30 -14
  89. package/dist/npcs/web-page-watcher/capture.d.ts +18 -0
  90. package/dist/npcs/web-page-watcher/capture.js +21 -1
  91. package/dist/npcs/web-page-watcher/defaults.d.ts +23 -0
  92. package/dist/npcs/web-page-watcher/defaults.js +41 -1
  93. package/dist/npcs/web-page-watcher/index.d.ts +18 -1
  94. package/dist/npcs/web-page-watcher/index.js +121 -70
  95. package/dist/npcs/web-page-watcher/pixelate.js +2 -1
  96. package/package.json +2 -2
@@ -1,17 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PollingNPC = void 0;
3
+ exports.PollingNPC = exports.MIN_POLL_INTERVAL_MS = void 0;
4
4
  const base_npc_js_1 = require("./base-npc.js");
5
+ /**
6
+ * Lower bound for any poll interval, so a typo can't exhaust the API's
7
+ * per-service rate limit (60 pushes/min) or hammer the watched source.
8
+ */
9
+ exports.MIN_POLL_INTERVAL_MS = 5000;
10
+ /** How long `stop()` waits for an in-flight collection before pushing offline anyway. */
11
+ const STOP_DRAIN_TIMEOUT_MS = 10_000;
5
12
  function clamp(n, min, max) {
6
13
  return Math.min(max, Math.max(min, n));
7
14
  }
8
15
  class PollingNPC extends base_npc_js_1.BaseNPC {
9
16
  timer = null;
10
- collecting = false;
17
+ keepaliveTimer = null;
18
+ /** The running collection + push, if any (awaited by `onStop`). */
19
+ inflight = null;
20
+ /** A `collectNow()` arrived while a collection was in flight: run once more after it. */
21
+ rerunRequested = false;
22
+ /** The last successfully pushed cycle, replayed (without its screen) by the keepalive. */
23
+ lastPushed = null;
24
+ lastPushAt = 0;
11
25
  pollInterval;
12
26
  constructor(config) {
13
27
  super(config);
14
- this.pollInterval = config.pollInterval ?? 15000;
28
+ const requested = config.pollInterval ?? 15000;
29
+ this.pollInterval = Number.isFinite(requested)
30
+ ? Math.max(exports.MIN_POLL_INTERVAL_MS, requested)
31
+ : 15000;
15
32
  }
16
33
  /** Scale staleness to the poll cadence: the server marks unknown at ~2x the interval. */
17
34
  get heartbeatSeconds() {
@@ -20,14 +37,22 @@ class PollingNPC extends base_npc_js_1.BaseNPC {
20
37
  async onStart() {
21
38
  // Collect immediately on start
22
39
  await this.runCollection();
40
+ // Stopped while the first collection ran: don't arm timers nobody will clear.
41
+ if (this.state !== 'running')
42
+ return;
23
43
  // Then on interval
24
44
  this.timer = setInterval(() => {
25
45
  void this.runCollection();
26
46
  }, this.pollInterval);
27
- // For slow pollers, keep the NPC alive with a lightweight heartbeat between
28
- // collections so it never falsely goes stale mid-interval.
29
- if (this.pollInterval > 60_000) {
30
- this.client.startHeartbeat(30_000);
47
+ // Only very slow pollers (> heartbeatSeconds, i.e. > 30 min given the clamp)
48
+ // could go stale between collections. Keep them alive by replaying the
49
+ // last cycle. The SDK's own heartbeat is not used: it omits `map`, `name`
50
+ // and `alertConfig`, so it would spawn a twin on the team's default map.
51
+ const heartbeatMs = this.heartbeatSeconds * 1000;
52
+ if (this.pollInterval > heartbeatMs) {
53
+ this.keepaliveTimer = setInterval(() => {
54
+ void this.keepalive(heartbeatMs);
55
+ }, heartbeatMs);
31
56
  }
32
57
  }
33
58
  async onStop() {
@@ -35,29 +60,89 @@ class PollingNPC extends base_npc_js_1.BaseNPC {
35
60
  clearInterval(this.timer);
36
61
  this.timer = null;
37
62
  }
38
- this.client.stopHeartbeat();
63
+ if (this.keepaliveTimer) {
64
+ clearInterval(this.keepaliveTimer);
65
+ this.keepaliveTimer = null;
66
+ }
67
+ this.rerunRequested = false;
68
+ // Let an in-flight push land before the offline push, so it can't arrive
69
+ // afterwards and respawn the NPC. Bounded: a hung collector never blocks exit.
70
+ if (this.inflight) {
71
+ let timeout;
72
+ await Promise.race([
73
+ this.inflight,
74
+ new Promise((resolve) => {
75
+ timeout = setTimeout(resolve, STOP_DRAIN_TIMEOUT_MS);
76
+ }),
77
+ ]);
78
+ clearTimeout(timeout);
79
+ }
39
80
  }
40
- async runCollection() {
81
+ /**
82
+ * Collect and push now instead of waiting for the next tick — for NPCs that
83
+ * also react to events (e.g. a fresh error line). Coalesces: if a collection
84
+ * is already running, exactly one more runs after it.
85
+ */
86
+ collectNow() {
41
87
  if (this.state !== 'running')
42
88
  return;
89
+ if (this.inflight) {
90
+ this.rerunRequested = true;
91
+ return;
92
+ }
93
+ void this.runCollection();
94
+ }
95
+ runCollection() {
96
+ if (this.state !== 'running')
97
+ return Promise.resolve();
43
98
  // Overlap guard: if a slow collector is still running, skip this tick rather
44
99
  // than stacking collections (load-bearing for screenshot/render collectors).
45
- if (this.collecting) {
100
+ if (this.inflight) {
46
101
  this.logger.debug('Previous collection still in flight, skipping this tick');
47
- return;
102
+ return this.inflight;
48
103
  }
49
- this.collecting = true;
104
+ const run = this.collectAndPush().finally(() => {
105
+ this.inflight = null;
106
+ if (this.rerunRequested && this.state === 'running') {
107
+ this.rerunRequested = false;
108
+ void this.runCollection();
109
+ }
110
+ });
111
+ this.inflight = run;
112
+ return run;
113
+ }
114
+ async collectAndPush() {
50
115
  try {
51
116
  const metrics = await this.collect();
117
+ // Stopped mid-collection: never push after (or race) the offline push.
118
+ if (this.state !== 'running')
119
+ return;
52
120
  await this.pushMetrics(metrics);
121
+ this.lastPushed = metrics;
122
+ this.lastPushAt = Date.now();
53
123
  }
54
124
  catch (err) {
125
+ if (this.state !== 'running')
126
+ return; // teardown aborted the collector
55
127
  this.logger.error('Collection failed', {
56
128
  error: err instanceof Error ? err.message : String(err),
57
129
  });
58
130
  }
59
- finally {
60
- this.collecting = false;
131
+ }
132
+ /** Replay the last cycle (minus its screen, which the server keeps) if nothing was pushed recently. */
133
+ async keepalive(heartbeatMs) {
134
+ if (this.state !== 'running' || this.inflight || !this.lastPushed)
135
+ return;
136
+ if (Date.now() - this.lastPushAt < heartbeatMs / 2)
137
+ return;
138
+ try {
139
+ await this.pushMetrics({ ...this.lastPushed, screenData: undefined });
140
+ this.lastPushAt = Date.now();
141
+ }
142
+ catch (err) {
143
+ this.logger.debug('Keepalive push failed', {
144
+ error: err instanceof Error ? err.message : String(err),
145
+ });
61
146
  }
62
147
  }
63
148
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.truncate = truncate;
4
+ exports.sanitizeText = sanitizeText;
4
5
  /**
5
6
  * Truncate a string to at most `max` characters, appending an ellipsis when cut.
6
7
  * Used to keep messages and screen lines within API limits.
@@ -12,4 +13,16 @@ function truncate(s, max = 200) {
12
13
  return s.slice(0, Math.max(0, max));
13
14
  return s.slice(0, max - 1) + '…';
14
15
  }
16
+ // C0/C1 controls (incl. ESC, so no terminal escapes) plus the bidi overrides,
17
+ // isolates and marks that can visually reorder text on a banner.
18
+ // eslint-disable-next-line no-control-regex
19
+ const UNSAFE_CHARS = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F؜‎‏‪-‮⁦-⁩]/g;
20
+ /**
21
+ * Make untrusted remote text (commit messages, page titles, log lines) safe to
22
+ * display: drop control and bidi-override characters, collapse whitespace
23
+ * (including newlines and tabs) to single spaces, trim, and truncate.
24
+ */
25
+ function sanitizeText(s, max = 200) {
26
+ return truncate(s.replace(UNSAFE_CHARS, '').replace(/\s+/g, ' ').trim(), max);
27
+ }
15
28
  //# sourceMappingURL=text.js.map
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluateThreshold = evaluateThreshold;
4
4
  exports.worstStatus = worstStatus;
5
+ exports.moodForStatus = moodForStatus;
6
+ exports.thresholdProblem = thresholdProblem;
5
7
  /**
6
8
  * Evaluate a numeric value against thresholds to determine status.
7
9
  */
@@ -45,4 +47,31 @@ function worstStatus(statuses) {
45
47
  }
46
48
  return worst;
47
49
  }
50
+ /** The NPC mood that matches a status (drives the NPC's demeanour and emotes). */
51
+ function moodForStatus(status) {
52
+ switch (status) {
53
+ case 'healthy':
54
+ return 'happy';
55
+ case 'warning':
56
+ return 'concerned';
57
+ case 'critical':
58
+ return 'stressed';
59
+ default:
60
+ return 'idle';
61
+ }
62
+ }
63
+ /**
64
+ * Validate a warning/critical pair from user flags: both finite, and critical
65
+ * at least as severe as warning for the threshold's direction. Returns an error
66
+ * message, or null when the pair is usable.
67
+ */
68
+ function thresholdProblem(label, t) {
69
+ if (!Number.isFinite(t.warning) || !Number.isFinite(t.critical)) {
70
+ return `${label}: thresholds must be numbers`;
71
+ }
72
+ const inverted = (t.direction ?? 'above') === 'above' ? t.critical < t.warning : t.critical > t.warning;
73
+ return inverted
74
+ ? `${label}: critical (${t.critical}) must be at least as severe as warning (${t.warning})`
75
+ : null;
76
+ }
48
77
  //# sourceMappingURL=thresholds.js.map
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.geminiServiceId = exports.geminiTransition = exports.GEMINI_ADAPTER = exports.GEMINI_DEFAULTS = exports.WebPageWatcherNPC = exports.GitHubWatcherNPC = exports.ReceptionistNPC = exports.LogWatcherNPC = exports.ProcessWatcherNPC = exports.InternetConnectivityNPC = exports.ensureSessionFilterTemplate = exports.sessionPublishDecision = exports.sessionFilterPath = exports.loadSessionFilter = exports.userConfigPath = exports.saveUserConfig = exports.loadUserConfig = exports.redactSecrets = exports.shortPath = exports.shortCommand = exports.describeToolUse = exports.CodexWatcher = exports.parseRolloutLine = exports.uninstallCodexHooks = exports.setupCodexHooks = exports.codexTransition = exports.handleCodexHookEvent = exports.handleCodexCommand = exports.claudeTransition = exports.processHookEvent = exports.uninstallHooks = exports.setupHooks = exports.handleHookEvent = exports.handleClaudeCodeCommand = exports.ClaudeCodeNPC = exports.SystemMonitorNPC = exports.pushHistory = exports.statusColor = exports.truncate = exports.worstStatus = exports.evaluateThreshold = exports.numberFlag = exports.boolFlag = exports.stringFlag = exports.resolveConfig = exports.parseArgs = exports.Logger = exports.EventNPC = exports.PollingNPC = exports.BaseNPC = void 0;
4
- exports.normalizeCursorEvent = exports.isCursorInvocation = exports.CURSOR_HOOK_EVENTS = exports.installCursorHooksInto = exports.uninstallCursorHooks = exports.setupCursorHooks = exports.handleCursorHookEvent = exports.cursorServiceId = exports.CURSOR_ADAPTER = exports.CURSOR_DEFAULTS = exports.GEMINI_HOOK_EVENTS = exports.installGeminiHooksInto = exports.uninstallGeminiHooks = exports.setupGeminiHooks = exports.handleGeminiHookEvent = void 0;
3
+ exports.ReceptionistNPC = exports.LogWatcherNPC = exports.ProcessWatcherNPC = exports.InternetConnectivityNPC = exports.ensureSessionFilterTemplate = exports.sessionPublishDecision = exports.sessionFilterPath = exports.loadSessionFilter = exports.pixelDevice = exports.pixelArtFromPng = exports.encodePixelArt = exports.userConfigPath = exports.saveUserConfig = exports.loadUserConfig = exports.redactSecrets = exports.shortPath = exports.shortCommand = exports.describeToolUse = exports.CodexWatcher = exports.parseRolloutLine = exports.uninstallCodexHooks = exports.setupCodexHooks = exports.codexTransition = exports.handleCodexHookEvent = exports.handleCodexCommand = exports.claudeTransition = exports.processHookEvent = exports.uninstallHooks = exports.setupHooks = exports.handleHookEvent = exports.handleClaudeCodeCommand = exports.ClaudeCodeNPC = exports.SystemMonitorNPC = exports.pushHistory = exports.statusColor = exports.NpcConfigError = exports.sanitizeText = exports.truncate = exports.moodForStatus = exports.worstStatus = exports.evaluateThreshold = exports.numberFlag = exports.boolFlag = exports.stringFlag = exports.resolveConfig = exports.parseArgs = exports.Logger = exports.EventNPC = exports.PollingNPC = exports.BaseNPC = void 0;
4
+ exports.normalizeCursorEvent = exports.isCursorInvocation = exports.CURSOR_HOOK_EVENTS = exports.installCursorHooksInto = exports.uninstallCursorHooks = exports.setupCursorHooks = exports.handleCursorHookEvent = exports.cursorServiceId = exports.CURSOR_ADAPTER = exports.CURSOR_DEFAULTS = exports.GEMINI_HOOK_EVENTS = exports.installGeminiHooksInto = exports.uninstallGeminiHooks = exports.setupGeminiHooks = exports.handleGeminiHookEvent = exports.geminiServiceId = exports.geminiTransition = exports.GEMINI_ADAPTER = exports.GEMINI_DEFAULTS = exports.WebPageWatcherNPC = exports.GitHubWatcherNPC = void 0;
5
5
  // Core
6
6
  var base_npc_js_1 = require("./core/base-npc.js");
7
7
  Object.defineProperty(exports, "BaseNPC", { enumerable: true, get: function () { return base_npc_js_1.BaseNPC; } });
@@ -20,8 +20,12 @@ Object.defineProperty(exports, "numberFlag", { enumerable: true, get: function (
20
20
  var thresholds_js_1 = require("./core/thresholds.js");
21
21
  Object.defineProperty(exports, "evaluateThreshold", { enumerable: true, get: function () { return thresholds_js_1.evaluateThreshold; } });
22
22
  Object.defineProperty(exports, "worstStatus", { enumerable: true, get: function () { return thresholds_js_1.worstStatus; } });
23
+ Object.defineProperty(exports, "moodForStatus", { enumerable: true, get: function () { return thresholds_js_1.moodForStatus; } });
23
24
  var text_js_1 = require("./core/text.js");
24
25
  Object.defineProperty(exports, "truncate", { enumerable: true, get: function () { return text_js_1.truncate; } });
26
+ Object.defineProperty(exports, "sanitizeText", { enumerable: true, get: function () { return text_js_1.sanitizeText; } });
27
+ var errors_js_1 = require("./core/errors.js");
28
+ Object.defineProperty(exports, "NpcConfigError", { enumerable: true, get: function () { return errors_js_1.NpcConfigError; } });
25
29
  var screen_js_1 = require("./core/screen.js");
26
30
  Object.defineProperty(exports, "statusColor", { enumerable: true, get: function () { return screen_js_1.statusColor; } });
27
31
  Object.defineProperty(exports, "pushHistory", { enumerable: true, get: function () { return screen_js_1.pushHistory; } });
@@ -53,6 +57,10 @@ var user_config_js_1 = require("./core/user-config.js");
53
57
  Object.defineProperty(exports, "loadUserConfig", { enumerable: true, get: function () { return user_config_js_1.loadUserConfig; } });
54
58
  Object.defineProperty(exports, "saveUserConfig", { enumerable: true, get: function () { return user_config_js_1.saveUserConfig; } });
55
59
  Object.defineProperty(exports, "userConfigPath", { enumerable: true, get: function () { return user_config_js_1.userConfigPath; } });
60
+ var pixel_art_js_1 = require("./core/pixel-art.js");
61
+ Object.defineProperty(exports, "encodePixelArt", { enumerable: true, get: function () { return pixel_art_js_1.encodePixelArt; } });
62
+ Object.defineProperty(exports, "pixelArtFromPng", { enumerable: true, get: function () { return pixel_art_js_1.pixelArtFromPng; } });
63
+ Object.defineProperty(exports, "pixelDevice", { enumerable: true, get: function () { return pixel_art_js_1.pixelDevice; } });
56
64
  var session_filter_js_1 = require("./core/session-filter.js");
57
65
  Object.defineProperty(exports, "loadSessionFilter", { enumerable: true, get: function () { return session_filter_js_1.loadSessionFilter; } });
58
66
  Object.defineProperty(exports, "sessionFilterPath", { enumerable: true, get: function () { return session_filter_js_1.sessionFilterPath; } });
@@ -244,6 +244,7 @@ function buildAgentPayload(adapter, state, config) {
244
244
  name,
245
245
  message: current ? (0, text_js_1.truncate)(current, 120) : undefined,
246
246
  archetype: 'ai-agent',
247
+ kind: adapter.command,
247
248
  metrics: { sessionStartedAt: state.startedAt ?? state.lastUpdate },
248
249
  appearance: { family: adapter.family },
249
250
  agentStats: state.agentStats,
@@ -2,10 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULTS = void 0;
4
4
  exports.DEFAULTS = {
5
- pollInterval: 60000, // 60s
5
+ pollInterval: 60000, // 60s with a token
6
+ /** Without a token GitHub allows 60 requests/hour (304s included): poll every 90s. */
7
+ unauthenticatedPollInterval: 90000,
6
8
  fetchTimeoutMs: 5000,
7
9
  perPage: 10,
10
+ /** Commit rows on the board (plus a header row). */
11
+ boardRows: 8,
8
12
  /** Polls to keep the 'new-commit' sub-status active after a fresh commit. */
9
13
  newCommitPolls: 2,
14
+ /** Consecutive network/5xx failures tolerated (board kept, healthy) before warning. */
15
+ failuresBeforeWarning: 3,
10
16
  };
11
17
  //# sourceMappingURL=defaults.js.map
@@ -1,102 +1,139 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidRepo = isValidRepo;
3
4
  exports.fetchDefaultBranch = fetchDefaultBranch;
4
5
  exports.fetchCommits = fetchCommits;
6
+ exports.parseCommit = parseCommit;
5
7
  exports.commitsWithin = commitsWithin;
6
8
  exports.newCommitsSince = newCommitsSince;
9
+ const http_js_1 = require("../../core/http.js");
10
+ const text_js_1 = require("../../core/text.js");
11
+ /** Largest GitHub API response we read (10 commits are ~30-60 KB). */
12
+ const MAX_BODY_BYTES = 512 * 1024;
13
+ // GitHub owner and repository names: letters, digits, '-', '_' and '.'.
14
+ const REPO_RE = /^([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100})$/;
15
+ /**
16
+ * Validate an "owner/name" repository slug. It is interpolated into the API
17
+ * URL path, so anything else (`../`, extra segments, query characters) is
18
+ * rejected rather than letting it — and the token — reach another endpoint.
19
+ */
20
+ function isValidRepo(repo) {
21
+ const m = repo.match(REPO_RE);
22
+ return !!m && m[2] !== '.' && m[2] !== '..';
23
+ }
7
24
  function toNum(v) {
8
- if (v === null)
25
+ if (v === null || v.trim() === '')
9
26
  return null;
10
27
  const n = Number(v);
11
- return Number.isNaN(n) ? null : n;
28
+ return Number.isFinite(n) ? n : null;
12
29
  }
13
30
  function ghHeaders(opts) {
14
31
  const headers = {
15
32
  Accept: 'application/vnd.github+json',
16
- 'User-Agent': 'nocville-npc',
33
+ 'User-Agent': http_js_1.NPC_USER_AGENT,
17
34
  'X-GitHub-Api-Version': '2022-11-28',
18
35
  };
19
36
  if (opts.token)
20
37
  headers['Authorization'] = `Bearer ${opts.token}`;
21
38
  return headers;
22
39
  }
40
+ function doFetchFn(opts) {
41
+ return opts.fetchFn ?? globalThis.fetch;
42
+ }
43
+ async function readJson(res) {
44
+ const { text, truncated } = await (0, http_js_1.readTextCapped)(res, MAX_BODY_BYTES);
45
+ if (truncated)
46
+ throw new Error('response too large');
47
+ return JSON.parse(text);
48
+ }
23
49
  /** Look up a repo's default branch (one call at startup). Null on failure. */
24
50
  async function fetchDefaultBranch(repo, opts = {}) {
25
- const doFetch = opts.fetchFn ?? globalThis.fetch;
26
- const controller = new AbortController();
27
- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 5000);
28
51
  try {
29
- const res = await doFetch(`https://api.github.com/repos/${repo}`, {
52
+ const res = await doFetchFn(opts)(`https://api.github.com/repos/${repo}`, {
30
53
  headers: ghHeaders(opts),
31
- signal: controller.signal,
54
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 5000),
32
55
  });
33
56
  if (!res.ok)
34
57
  return null;
35
- const body = (await res.json());
36
- return body.default_branch ?? null;
58
+ const branch = (0, http_js_1.asRecord)(await readJson(res))?.['default_branch'];
59
+ return typeof branch === 'string' && branch.length > 0 && branch.length <= 255
60
+ ? (0, text_js_1.sanitizeText)(branch, 255)
61
+ : null;
37
62
  }
38
63
  catch {
39
64
  return null;
40
65
  }
41
- finally {
42
- clearTimeout(timer);
43
- }
44
66
  }
45
67
  /**
46
68
  * Fetch recent commits from the GitHub REST API using conditional requests.
47
- * Passing the previous ETag yields a 304 (which does not count against the
48
- * unauthenticated 60/hour limit) when nothing has changed. Never throws —
49
- * network errors surface as `status: 0`.
69
+ * Passing the previous ETag yields a cheap 304 when nothing has changed (free
70
+ * of the rate limit for authenticated requests). Never throws — network
71
+ * errors and unreadable bodies surface as `status: 0`.
50
72
  */
51
73
  async function fetchCommits(repo, opts = {}) {
52
74
  const perPage = opts.perPage ?? 10;
53
- const doFetch = opts.fetchFn ?? globalThis.fetch;
54
75
  let url = `https://api.github.com/repos/${repo}/commits?per_page=${perPage}`;
55
76
  if (opts.branch)
56
77
  url += `&sha=${encodeURIComponent(opts.branch)}`;
57
78
  const headers = ghHeaders(opts);
58
79
  if (opts.etag)
59
80
  headers['If-None-Match'] = opts.etag;
60
- const controller = new AbortController();
61
- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 5000);
81
+ const failed = {
82
+ notModified: false,
83
+ commits: [],
84
+ etag: null,
85
+ rateRemaining: null,
86
+ rateResetAt: null,
87
+ status: 0,
88
+ };
62
89
  try {
63
- const res = await doFetch(url, { headers, signal: controller.signal });
90
+ const res = await doFetchFn(opts)(url, {
91
+ headers,
92
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 5000),
93
+ });
64
94
  const rateRemaining = toNum(res.headers.get('x-ratelimit-remaining'));
95
+ const resetSecs = toNum(res.headers.get('x-ratelimit-reset'));
96
+ const rateResetAt = resetSecs === null ? null : resetSecs * 1000;
65
97
  const etag = res.headers.get('etag');
98
+ const meta = { rateRemaining, rateResetAt, status: res.status };
66
99
  if (res.status === 304) {
67
- return {
68
- notModified: true,
69
- commits: [],
70
- etag: opts.etag ?? null,
71
- rateRemaining,
72
- status: 304,
73
- };
100
+ return { ...meta, notModified: true, commits: [], etag: opts.etag ?? null };
74
101
  }
75
102
  if (!res.ok) {
76
- await res.text().catch(() => undefined);
77
- return { notModified: false, commits: [], etag, rateRemaining, status: res.status };
103
+ await res.body?.cancel().catch(() => undefined);
104
+ return { ...meta, notModified: false, commits: [], etag };
78
105
  }
79
- const body = (await res.json());
80
- const commits = body.map((c) => parseCommit(c));
81
- return { notModified: false, commits, etag, rateRemaining, status: res.status };
106
+ const body = await readJson(res);
107
+ if (!Array.isArray(body))
108
+ return failed;
109
+ const commits = body.map(parseCommit).filter((c) => c !== null);
110
+ return { ...meta, notModified: false, commits, etag };
82
111
  }
83
112
  catch {
84
- return { notModified: false, commits: [], etag: null, rateRemaining: null, status: 0 };
85
- }
86
- finally {
87
- clearTimeout(timer);
113
+ return failed;
88
114
  }
89
115
  }
90
- function parseCommit(c) {
91
- const commit = c['commit'] ?? {};
92
- const commitAuthor = commit['author'] ?? {};
93
- const ghAuthor = c['author'] ?? {};
94
- const message = String(commit['message'] ?? '').split('\n')[0] ?? '';
116
+ /**
117
+ * Extract the displayed fields from one (untrusted) commit object: a hex sha,
118
+ * the subject line and author name with control/bidi characters removed and
119
+ * lengths capped. Null for anything without a valid sha.
120
+ */
121
+ function parseCommit(raw) {
122
+ const c = (0, http_js_1.asRecord)(raw);
123
+ const sha = c?.['sha'];
124
+ if (typeof sha !== 'string' || !/^[0-9a-f]{7,64}$/i.test(sha))
125
+ return null;
126
+ const commit = (0, http_js_1.asRecord)(c['commit']) ?? {};
127
+ const commitAuthor = (0, http_js_1.asRecord)(commit['author']) ?? {};
128
+ const ghAuthor = (0, http_js_1.asRecord)(c['author']) ?? {};
129
+ const str = (v) => (typeof v === 'string' && v.trim() ? v : null);
130
+ const message = str(commit['message'])?.split('\n')[0] ?? '';
131
+ const date = str(commitAuthor['date']) ?? '';
95
132
  return {
96
- sha: String(c['sha'] ?? ''),
97
- author: String(commitAuthor['name'] ?? ghAuthor['login'] ?? 'unknown'),
98
- message,
99
- date: String(commitAuthor['date'] ?? ''),
133
+ sha: sha.toLowerCase(),
134
+ author: (0, text_js_1.sanitizeText)(str(commitAuthor['name']) ?? str(ghAuthor['login']) ?? 'unknown', 40),
135
+ message: (0, text_js_1.sanitizeText)(message, 200),
136
+ date: Number.isFinite(Date.parse(date)) ? date : '',
100
137
  };
101
138
  }
102
139
  /** Count how many commits landed within the last `hours`. */