@cyanheads/astronomy-mcp-server 0.4.1 → 0.4.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 (58) hide show
  1. package/AGENTS.md +16 -12
  2. package/CLAUDE.md +16 -12
  3. package/Dockerfile +3 -3
  4. package/README.md +39 -14
  5. package/changelog/0.4.x/0.4.2.md +37 -0
  6. package/changelog/0.4.x/0.4.3.md +28 -0
  7. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js +1 -1
  8. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js.map +1 -1
  9. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts +31 -4
  10. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts.map +1 -1
  11. package/dist/mcp-server/tools/definitions/find-events.tool.js +96 -24
  12. package/dist/mcp-server/tools/definitions/find-events.tool.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts +29 -7
  14. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts.map +1 -1
  15. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js +221 -46
  16. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js.map +1 -1
  17. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts.map +1 -1
  18. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js +1 -0
  19. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js.map +1 -1
  20. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts +49 -2
  21. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts.map +1 -1
  22. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js +85 -43
  23. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js.map +1 -1
  24. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts +27 -3
  25. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts.map +1 -1
  26. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js +98 -23
  27. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js.map +1 -1
  28. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts.map +1 -1
  29. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js +1 -0
  30. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js.map +1 -1
  31. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts.map +1 -1
  32. package/dist/mcp-server/tools/definitions/list-visible.tool.js +1 -0
  33. package/dist/mcp-server/tools/definitions/list-visible.tool.js.map +1 -1
  34. package/dist/services/ephemeris/ephemeris-service.d.ts +86 -14
  35. package/dist/services/ephemeris/ephemeris-service.d.ts.map +1 -1
  36. package/dist/services/ephemeris/ephemeris-service.js +455 -100
  37. package/dist/services/ephemeris/ephemeris-service.js.map +1 -1
  38. package/dist/services/ephemeris/iso-time.d.ts +2 -2
  39. package/dist/services/ephemeris/iso-time.js +5 -5
  40. package/dist/services/ephemeris/types.d.ts +42 -1
  41. package/dist/services/ephemeris/types.d.ts.map +1 -1
  42. package/dist/services/ephemeris/types.js +16 -0
  43. package/dist/services/ephemeris/types.js.map +1 -1
  44. package/dist/services/horizons/horizons-service.d.ts +25 -3
  45. package/dist/services/horizons/horizons-service.d.ts.map +1 -1
  46. package/dist/services/horizons/horizons-service.js +154 -15
  47. package/dist/services/horizons/horizons-service.js.map +1 -1
  48. package/dist/services/horizons/types.d.ts +8 -4
  49. package/dist/services/horizons/types.d.ts.map +1 -1
  50. package/dist/services/satellite/satellite-service.d.ts +48 -10
  51. package/dist/services/satellite/satellite-service.d.ts.map +1 -1
  52. package/dist/services/satellite/satellite-service.js +215 -102
  53. package/dist/services/satellite/satellite-service.js.map +1 -1
  54. package/dist/services/satellite/types.d.ts +36 -2
  55. package/dist/services/satellite/types.d.ts.map +1 -1
  56. package/dist/services/satellite/types.js.map +1 -1
  57. package/package.json +10 -9
  58. package/server.json +3 -3
@@ -9,7 +9,7 @@
9
9
  * @module services/ephemeris/ephemeris-service
10
10
  */
11
11
  import { invalidParams, notFound } from '@cyanheads/mcp-ts-core/errors';
12
- import { AngleFromSun, ApsisKind, Body, Constellation, DefineStar, Ecliptic, Equator, Horizon, Illumination, MakeTime, MoonPhase, NextGlobalSolarEclipse, NextLocalSolarEclipse, NextLunarApsis, NextLunarEclipse, NextMoonQuarter, NextPlanetApsis, Observer, SearchAltitude, SearchGlobalSolarEclipse, SearchHourAngle, SearchLocalSolarEclipse, SearchLunarApsis, SearchLunarEclipse, SearchMaxElongation, SearchMoonPhase, SearchMoonQuarter, SearchPlanetApsis, SearchRelativeLongitude, SearchRiseSet, Seasons, } from 'astronomy-engine';
12
+ import { AngleBetween, AngleFromSun, ApsisKind, Atmosphere, Body, Constellation, DefineStar, Ecliptic, Equator, GeoVector, Horizon, Illumination, MakeTime, MoonPhase, NextGlobalSolarEclipse, NextLocalSolarEclipse, NextLunarApsis, NextLunarEclipse, NextMoonQuarter, NextPlanetApsis, Observer, PairLongitude, Search, SearchAltitude, SearchGlobalSolarEclipse, SearchHourAngle, SearchLocalSolarEclipse, SearchLunarApsis, SearchLunarEclipse, SearchMaxElongation, SearchMoonPhase, SearchMoonQuarter, SearchPlanetApsis, SearchRelativeLongitude, SearchRiseSet, Seasons, } from 'astronomy-engine';
13
13
  import { BODY_META } from './body-data.js';
14
14
  import { parseIsoInstant } from './iso-time.js';
15
15
  import { CONSTELLATION_GENITIVES, GREEK_LETTER_NAMES, STAR_CATALOG } from './star-catalog.js';
@@ -42,6 +42,14 @@ const ASTRONOMICAL_DEG = -18;
42
42
  * next rise/set is months away) as null — the explanatory-note path.
43
43
  */
44
44
  const RISE_SET_WINDOW_DAYS = 2;
45
+ /** The step past a cycle's last event that the next cycle's search resumes from. */
46
+ const RESUME_STEP_MS = 1000;
47
+ /**
48
+ * Shorter than any body's culmination-to-lower-culmination interval: half a sidereal day is
49
+ * 11.97 h, the Sun's and Moon's are longer, and no planet's retrograde motion shortens one by
50
+ * an hour. A rise or set this soon after a culmination is inside that culmination's day.
51
+ */
52
+ const MIN_HALF_DAY_MS = 11 * 3_600_000;
45
53
  /** Longest synodic month, rounded up — the widest a new-moon look-back needs to be. */
46
54
  const MAX_SYNODIC_MONTH_DAYS = 29.9;
47
55
  /** Mean synodic month, for deriving an age from the phase longitude. */
@@ -61,6 +69,33 @@ const PLANETS = [
61
69
  const INNER_PLANETS = new Set(['mercury', 'venus']);
62
70
  /** Superior planets — the only ones that reach opposition. */
63
71
  const SUPERIOR_PLANETS = new Set(PLANETS.filter((p) => !INNER_PLANETS.has(p)));
72
+ /**
73
+ * Upper bound on how fast each pairable body's ecliptic longitude, seen from Earth's
74
+ * center, changes — in degrees per day, either direction. Each is its 1900–2100 maximum
75
+ * rounded up with a margin (Moon 15.40, Mercury 2.20, Venus 1.26, Mars 0.79, Jupiter
76
+ * 0.242, Saturn 0.130, Uranus 0.063, Neptune 0.038, Pluto 0.041). Two bodies' longitude
77
+ * offset can change no faster than the sum of their two bounds, which is what lets the
78
+ * conjunction scan step over a stretch where the offset cannot reach zero.
79
+ */
80
+ const MAX_LONGITUDE_RATE_DEG_PER_DAY = {
81
+ moon: 16.5,
82
+ mercury: 2.5,
83
+ venus: 1.5,
84
+ mars: 1,
85
+ jupiter: 0.3,
86
+ saturn: 0.15,
87
+ uranus: 0.08,
88
+ neptune: 0.05,
89
+ pluto: 0.05,
90
+ };
91
+ /**
92
+ * Shortest step of the conjunction scan, in days. Consecutive conjunctions of one pair
93
+ * are never closer than about 1.5 days in the supported span (Mercury–Venus), so a step
94
+ * this short holds at most one.
95
+ */
96
+ const PAIR_SCAN_MIN_STEP_DAYS = 1;
97
+ /** Whether a body can be one half of a two-body conjunction. */
98
+ const isPairBody = (body) => Object.hasOwn(MAX_LONGITUDE_RATE_DEG_PER_DAY, body);
64
99
  /** Map a wire body name to the engine's Body enum. */
65
100
  const BODY_ENUM = {
66
101
  sun: Body.Sun,
@@ -107,9 +142,12 @@ export class EphemerisService {
107
142
  * strict ISO 8601 instant or names a day that does not exist, and with reason
108
143
  * `time_out_of_range` outside the span.
109
144
  *
110
- * Both throws carry their recovery hint inline. A throw-site hint wins over the
111
- * one a calling tool declares for the same reason in `errors[]`, so every caller
112
- * hands the client this same `data.recovery.hint` and `Recovery:` line.
145
+ * `invalid_time` carries its recovery hint inline: a throw-site hint wins over the one
146
+ * a calling tool declares for the same reason in `errors[]`, so every caller hands the
147
+ * client that same hint. `time_out_of_range` carries none: the next move depends on the
148
+ * calling tool — which input field it exposes (`time` or `start`), and for satellite
149
+ * passes the element set's epoch window — so the framework fills that tool's declared
150
+ * recovery instead.
113
151
  */
114
152
  resolveTime(time) {
115
153
  const date = time ? parseIsoInstant(time) : new Date();
@@ -124,10 +162,7 @@ export class EphemerisService {
124
162
  const year = date.getUTCFullYear();
125
163
  const { firstYear, lastYear } = SUPPORTED_SPAN;
126
164
  if (year < firstYear || year > lastYear) {
127
- throw invalidParams(`Time ${date.toISOString()} is outside the high-accuracy span (${firstYear}–${lastYear}).`, {
128
- reason: 'time_out_of_range',
129
- recovery: { hint: `Use a date between ${firstYear} and ${lastYear}.` },
130
- });
165
+ throw invalidParams(`Time ${date.toISOString()} is outside the high-accuracy span (${firstYear}–${lastYear}).`, { reason: 'time_out_of_range' });
131
166
  }
132
167
  return date;
133
168
  }
@@ -288,100 +323,328 @@ export class EphemerisService {
288
323
  return pos;
289
324
  }
290
325
  // ---- Rise / set / transit + twilight ------------------------------------
291
- /** Rise/set/transit cycles for a body, searching forward from `start`. */
326
+ /** Rise/set/transit cycles for a body, searching forward from `start` — the cycles alone. */
292
327
  riseSet(body, observer, start, count, timezone) {
328
+ return this.riseSetSearch(body, observer, start, count, timezone).events;
329
+ }
330
+ /**
331
+ * Rise/set/transit cycles for a body, searching forward from `start`, plus where the search
332
+ * stopped and — for the Sun when `start` falls at night — the night already under way.
333
+ *
334
+ * A cycle is one of the body's days: a culmination with the rise before it and the set after
335
+ * it. A day with neither — the Sun's polar night or midnight sun, a day the Moon spends wholly
336
+ * below or above the horizon — is a cycle of its own, never folded into a neighbour, so
337
+ * consecutive cycles cover consecutive days. A Sun cycle also carries the night after its day,
338
+ * which ends where the next cycle's day begins, so each night falls in exactly one cycle.
339
+ */
340
+ riseSetSearch(body, observer, start, count, timezone) {
293
341
  const obs = this.toObserver(observer);
294
- const events = [];
295
- let cursor = start;
296
- for (let i = 0; i < count; i++) {
297
- const rise = SearchRiseSet(BODY_ENUM[body], obs, +1, cursor, RISE_SET_WINDOW_DAYS);
298
- const set = SearchRiseSet(BODY_ENUM[body], obs, -1, cursor, RISE_SET_WINDOW_DAYS);
299
- /**
300
- * Both searches run forward from the cursor, so when the body is already up the next
301
- * set arrives before the next rise and the two belong to different cycles — pairing
302
- * them reports a set hours before its own rise. The interval in progress is the one
303
- * the caller is standing in, and its rise is behind the cursor where a forward-only
304
- * search cannot reach it, so report that interval as a partial cycle naming the
305
- * imminent set. Beginning at the next complete cycle instead would be chronologically
306
- * tidy and quietly drop tonight's set, which is the event a caller asking during the
307
- * day most needs.
308
- */
309
- const alreadyUp = set !== null && (rise === null || set.date < rise.date);
310
- const cycleRise = alreadyUp ? null : rise;
311
- let transitUtc = null;
312
- let transitAlt = null;
313
- try {
314
- const transit = SearchHourAngle(BODY_ENUM[body], obs, 0, cursor, +1);
315
- /**
316
- * The meridian crossing is found regardless of altitude, so the next one after the
317
- * cursor can belong to a neighbouring cycle — before this cycle's rise, or after
318
- * its set. Report it only when it falls inside the interval it is attached to.
319
- */
320
- const at = transit.time.date;
321
- if ((cycleRise === null || at > cycleRise.date) && (set === null || at < set.date)) {
322
- transitUtc = transit.time.toString();
323
- transitAlt = transit.hor.altitude;
324
- }
325
- }
326
- catch {
327
- transitUtc = null;
342
+ const target = BODY_ENUM[body];
343
+ const isSun = body === 'sun';
344
+ /**
345
+ * The next rise from a cursor, searched once per cursor: a Sun cycle that closes with a set
346
+ * looks ahead for the following sunrise to place its resume point, and the cycle resumed
347
+ * there opens with that same search.
348
+ */
349
+ const rises = new Map();
350
+ const riseFrom = (cursor) => {
351
+ const key = cursor.getTime();
352
+ if (!rises.has(key)) {
353
+ rises.set(key, this.horizonCrossing(target, obs, +1, cursor, RISE_SET_WINDOW_DAYS));
328
354
  }
355
+ return rises.get(key) ?? null;
356
+ };
357
+ const cycleAt = (cursor, crossings = this.crossingsFrom(target, obs, cursor, riseFrom)) => this.dayCycle(target, obs, cursor, crossings, isSun, riseFrom);
358
+ const opening = this.crossingsFrom(target, obs, start, riseFrom);
359
+ const sunsetBefore = isSun && !opening.alreadyUp
360
+ ? this.horizonCrossing(Body.Sun, obs, -1, start, -RISE_SET_WINDOW_DAYS)
361
+ : null;
362
+ let cycle = (isSun ? this.restOfDarkDay(obs, start, opening, sunsetBefore) : undefined) ??
363
+ cycleAt(start, opening);
364
+ const opener = cycle;
365
+ const cycles = [cycle];
366
+ let resumeAt = cycle.resume();
367
+ while (cycles.length < count) {
368
+ cycle = cycleAt(resumeAt);
369
+ cycles.push(cycle);
370
+ resumeAt = cycle.resume();
371
+ }
372
+ /**
373
+ * A Sun cycle's night runs from its own day to the start of the next cycle's: dusk after its
374
+ * set (or, with no set, after its culmination) and dawn before the next cycle's rise or
375
+ * culmination. The search stops there, so a crossing absent from this night is null rather
376
+ * than a later night's time. The last cycle's night ends where the cycle a continuation from
377
+ * `resumeAt` opens with begins, so a series served across calls splits its cycles' nights
378
+ * exactly as one search does. `nightInProgress` is the exception: a continuation that
379
+ * resumes past a set starts at night, so it reports again the night the last cycle carried.
380
+ */
381
+ const nightEnds = isSun
382
+ ? [...cycles.slice(1).map((c) => c.nightFrom), cycleAt(resumeAt).nightFrom]
383
+ : [];
384
+ const events = cycles.map((c, i) => {
329
385
  const event = {
330
- riseUtc: cycleRise ? cycleRise.toString() : null,
331
- setUtc: set ? set.toString() : null,
332
- transitUtc,
333
- transitAltitudeDegrees: transitAlt,
386
+ riseUtc: c.rise ? c.rise.toString() : null,
387
+ setUtc: c.set ? c.set.toString() : null,
388
+ transitUtc: c.transit ? c.transit.time.toString() : null,
389
+ transitAltitudeDegrees: c.transit ? c.transit.hor.altitude : null,
334
390
  };
335
- if (cycleRise === null && set === null) {
336
- // Circumpolar or never-rises: distinguish by transit altitude.
337
- event.note =
338
- transitAlt !== null && transitAlt > 0
339
- ? 'Circumpolar — never sets at this latitude/date.'
340
- : 'Never rises above the horizon at this latitude/date.';
341
- }
342
- else if (cycleRise === null) {
343
- event.note = 'Already above the horizon at the search start — no rise in this cycle.';
344
- }
345
- else if (set === null) {
346
- event.note = 'Does not set before the next rise — circumpolar window.';
347
- }
348
- if (body === 'sun') {
349
- /**
350
- * Anchor the pair to this cycle's own rise, not the resume cursor: the cursor sits
351
- * just past the previous set, which is still short of that evening's dusk, so a
352
- * cursor-anchored search hands the next cycle the previous evening's twilight while
353
- * its rise and set have already moved on a day.
354
- */
355
- event.twilight = this.twilight(obs, cycleRise?.date ?? cursor, timezone);
356
- }
391
+ if (c.note)
392
+ event.note = c.note;
393
+ const nightEnd = nightEnds[i];
394
+ if (nightEnd)
395
+ event.twilight = this.twilight(obs, c.nightFrom, nightEnd, timezone);
357
396
  if (timezone) {
358
- if (cycleRise)
359
- event.riseLocal = this.formatLocal(cycleRise.date, timezone);
360
- if (set)
361
- event.setLocal = this.formatLocal(set.date, timezone);
362
- if (transitUtc)
363
- event.transitLocal = this.formatLocal(new Date(transitUtc), timezone);
397
+ if (c.rise)
398
+ event.riseLocal = this.formatLocal(c.rise.date, timezone);
399
+ if (c.set)
400
+ event.setLocal = this.formatLocal(c.set.date, timezone);
401
+ if (c.transit)
402
+ event.transitLocal = this.formatLocal(c.transit.time.date, timezone);
364
403
  }
365
- events.push(event);
404
+ return event;
405
+ });
406
+ const search = { events, resumeAt };
407
+ /**
408
+ * The opener owns the night after its day. If that day begins after `start`, the preceding
409
+ * night has no cycle in this result and is reported separately. A sunset after the previous
410
+ * culmination anchors an ordinary night; otherwise that culmination anchors a polar night.
411
+ * An opener beginning before `start` already owns the night, including a rest-of-dark-day
412
+ * opener, so it must not also appear here.
413
+ */
414
+ if (isSun && this.horizonResidual(Body.Sun, obs, start) < 0 && opener.nightFrom > start) {
415
+ const noonBefore = SearchHourAngle(Body.Sun, obs, 0, start, -1).time.date;
416
+ const anchor = sunsetBefore && sunsetBefore.date > noonBefore ? sunsetBefore.date : noonBefore;
417
+ search.nightInProgress = this.twilight(obs, anchor, opener.nightFrom, timezone);
418
+ }
419
+ return search;
420
+ }
421
+ /** The next rise, set, and culmination searched forward from one cursor. */
422
+ crossingsFrom(target, obs, cursor, riseFrom) {
423
+ const rise = riseFrom(cursor);
424
+ const set = this.horizonCrossing(target, obs, -1, cursor, RISE_SET_WINDOW_DAYS);
425
+ return {
426
+ rise,
427
+ set,
366
428
  /**
367
- * Resume just past this cycle's set, so the next search finds the following rise and
368
- * the set that closes it. Advancing a whole day from the rise instead overshot the
369
- * next day's set for any body that rises earlier each day, dropping a full cycle from
370
- * a multi-count call. With no set to resume from the body is circumpolar for this
371
- * window, where a day is the only meaningful step.
429
+ * Both searches run forward from the cursor, so when the body is already up the next set
430
+ * arrives before the next rise and the two belong to different cycles — pairing them
431
+ * reports a set hours before its own rise. The interval in progress is the one the caller
432
+ * is standing in, and its rise is behind the cursor where a forward-only search cannot
433
+ * reach it, so that interval is reported as a partial cycle naming the imminent set.
434
+ * Beginning at the next complete cycle instead would be chronologically tidy and quietly
435
+ * drop tonight's set, which is the event a caller asking during the day most needs.
372
436
  */
373
- cursor = set
374
- ? new Date(set.date.getTime() + 1000)
375
- : new Date(cursor.getTime() + 24 * 3600 * 1000);
437
+ alreadyUp: set !== null && (rise === null || set.date < rise.date),
438
+ culmination: SearchHourAngle(target, obs, 0, cursor, +1),
439
+ };
440
+ }
441
+ /**
442
+ * Certify the engine's upper-limb crossing before it participates in a cycle. A shallow
443
+ * quadratic estimate can have the wrong direction; retain ordinary estimates unchanged,
444
+ * and recover an invalid estimate with directed bisection in the original search window.
445
+ */
446
+ horizonCrossing(target, obs, direction, start, limitDays) {
447
+ const candidate = SearchRiseSet(target, obs, direction, start, limitDays);
448
+ if (!candidate)
449
+ return null;
450
+ const residual = (ms) => direction * this.horizonResidual(target, obs, new Date(ms));
451
+ const estimate = candidate.date.getTime();
452
+ const end = start.getTime() + limitDays * 86_400_000;
453
+ const low = Math.min(start.getTime(), end);
454
+ const high = Math.max(start.getTime(), end);
455
+ if (estimate >= low &&
456
+ estimate <= high &&
457
+ residual(estimate - 100) < 0 &&
458
+ residual(estimate + 100) >= 0)
459
+ return candidate;
460
+ /**
461
+ * Envelope of the engine's body-specific altitude slope bounds, in degrees/ms.
462
+ * It bounds the round trip from either same-sign endpoint to a hidden short interval.
463
+ */
464
+ const latitude = (obs.latitude * Math.PI) / 180;
465
+ const slope = (370 * Math.abs(Math.cos(latitude)) + 9 * Math.abs(Math.sin(latitude))) / 86_400_000;
466
+ const backwards = limitDays < 0;
467
+ const bracket = (a, b, fa, fb) => {
468
+ if (fa < 0 && fb >= 0) {
469
+ while (b - a > 10) {
470
+ const middle = Math.floor((a + b) / 2);
471
+ const fm = residual(middle);
472
+ if (fm < 0)
473
+ a = middle;
474
+ else
475
+ b = middle;
476
+ }
477
+ return MakeTime(new Date((a + b) / 2));
478
+ }
479
+ if (b - a <= 50 || Math.min(Math.abs(fa), Math.abs(fb)) > (slope * (b - a)) / 2)
480
+ return null;
481
+ const middle = Math.floor((a + b) / 2);
482
+ const fm = residual(middle);
483
+ return backwards
484
+ ? (bracket(middle, b, fm, fb) ?? bracket(a, middle, fa, fm))
485
+ : (bracket(a, middle, fa, fm) ?? bracket(middle, b, fm, fb));
486
+ };
487
+ let cursor = start.getTime();
488
+ let value = residual(cursor);
489
+ while (backwards ? cursor > end : cursor < end) {
490
+ const next = backwards
491
+ ? Math.max(end, cursor - 0.42 * 86_400_000)
492
+ : Math.min(end, cursor + 0.42 * 86_400_000);
493
+ const nextValue = residual(next);
494
+ const found = backwards
495
+ ? bracket(next, cursor, nextValue, value)
496
+ : bracket(cursor, next, value, nextValue);
497
+ if (found)
498
+ return found;
499
+ cursor = next;
500
+ value = nextValue;
376
501
  }
377
- return events;
502
+ return null;
503
+ }
504
+ /** Apparent upper-limb height using SearchRiseSet's ground-level horizon convention. */
505
+ horizonResidual(target, obs, date) {
506
+ /**
507
+ * metersAboveGround defaults to zero: no horizon dip, even at a high ground elevation.
508
+ * Only Sun and Moon have a radius in the engine's rise/set model (constants in km).
509
+ */
510
+ const radiusAu = (target === Body.Sun ? 695700 : target === Body.Moon ? 1738.1 : 0) / KM_PER_AU;
511
+ const equator = Equator(target, date, obs, true, true);
512
+ return (Horizon(date, obs, equator.ra, equator.dec).altitude +
513
+ (180 / Math.PI) * Math.asin(radiusAu / equator.dist) +
514
+ (34 / 60) * Atmosphere(obs.height).density);
378
515
  }
379
- /** Civil/nautical/astronomical dawn+dusk pairs for the Sun on the search day. */
380
- twilight(obs, start, timezone) {
516
+ /**
517
+ * The cycle that opens at `cursor`: the day of the next culmination, or — when the body is
518
+ * already up — the interval in progress.
519
+ */
520
+ dayCycle(target, obs, cursor, crossings, isSun, riseFrom) {
521
+ const { alreadyUp, culmination } = crossings;
522
+ const noon = culmination.time;
523
+ const pastMidnight = () => this.pastLowerCulmination(target, obs, noon);
524
+ const next = alreadyUp ? crossings.set : crossings.rise;
525
+ /**
526
+ * No crossing inside the search window, or the first one belongs to a later day: the body
527
+ * neither rises nor sets on this culmination's day. That day is a cycle of its own — taking
528
+ * the later day's crossing here instead folded this day into it and dropped it. Its night is
529
+ * the one after its culmination, where a set would have put it.
530
+ */
531
+ if (next === null || this.inLaterDay(target, obs, noon, next, alreadyUp ? 'set' : 'rise')) {
532
+ return {
533
+ rise: null,
534
+ set: null,
535
+ transit: culmination,
536
+ note: culmination.hor.altitude > 0
537
+ ? 'Circumpolar — never sets at this latitude/date.'
538
+ : 'Never rises above the horizon at this latitude/date.',
539
+ nightFrom: noon.date,
540
+ resume: pastMidnight,
541
+ };
542
+ }
543
+ const rise = alreadyUp ? null : crossings.rise;
544
+ const set = crossings.set && (alreadyUp || !this.inLaterDay(target, obs, noon, crossings.set, 'set'))
545
+ ? crossings.set
546
+ : null;
547
+ /**
548
+ * The meridian crossing is found regardless of altitude, so the next one after the cursor
549
+ * can belong to a neighbouring cycle — before this cycle's rise, or after its set. Report it
550
+ * only when it falls inside the interval it is attached to.
551
+ */
552
+ const inside = (rise === null || noon.date > rise.date) && (set === null || noon.date < set.date);
553
+ return {
554
+ rise,
555
+ set,
556
+ transit: inside ? culmination : null,
557
+ note: rise === null
558
+ ? 'Already above the horizon when this cycle opens — no rise in this cycle.'
559
+ : set === null
560
+ ? 'Does not set before the next rise — circumpolar window.'
561
+ : undefined,
562
+ nightFrom: rise?.date ?? cursor,
563
+ resume: set ? () => this.pastSet(target, obs, set, isSun, riseFrom) : pastMidnight,
564
+ };
565
+ }
566
+ /**
567
+ * The rest of a dark day, as the first cycle of a Sun search: `start` falls after the day's
568
+ * culmination, the Sun is below the horizon, and nothing else would carry the night that
569
+ * follows — a polar-night afternoon, or the evening of the last sunset before a polar night.
570
+ * Neither has a sunrise ahead that opens the next cycle within a day, so without this cycle
571
+ * the night under way falls between the cycles. Its night runs from the day's culmination,
572
+ * so a dusk `start` has already passed is kept, as `nightInProgress` keeps passed times. A
573
+ * rise before the day's lower culmination means the day is not dark for its rest — near the
574
+ * pole at an equinox the Sun can rise and set again after a culmination below the horizon —
575
+ * so the ordinary cycle from `start` reports them instead.
576
+ */
577
+ restOfDarkDay(obs, start, crossings, sunsetBefore) {
578
+ const { alreadyUp, rise, culmination } = crossings;
579
+ if (alreadyUp || (rise === null && culmination.hor.altitude > 0))
580
+ return;
581
+ const midnight = SearchHourAngle(Body.Sun, obs, 12, start, +1).time;
582
+ // A lower culmination before the next culmination means `start` is past this day's.
583
+ if (midnight.date > culmination.time.date)
584
+ return;
585
+ if (rise !== null && rise.date < midnight.date)
586
+ return;
587
+ const noon = SearchHourAngle(Body.Sun, obs, 0, start, -1).time;
588
+ // An ordinary evening: the sunrise ahead opens the next cycle and nightInProgress carries this night.
589
+ if (rise !== null && sunsetBefore !== null && sunsetBefore.date > noon.date)
590
+ return;
591
+ return {
592
+ rise: null,
593
+ set: null,
594
+ transit: null,
595
+ note: 'Below the horizon for the rest of a day whose culmination precedes the search start: no rise, set, or transit remains, and the twilight is the night that follows it.',
596
+ nightFrom: noon.date,
597
+ resume: () => new Date(midnight.date.getTime() + RESUME_STEP_MS),
598
+ };
599
+ }
600
+ /**
601
+ * Whether a rise or set found after a culmination belongs to a later day than that
602
+ * culmination's. A rise opens the day whose culmination follows it, so one past this day's
603
+ * lower culmination opens a later day; a set closes the day whose culmination precedes it,
604
+ * so only one past the next culmination does.
605
+ */
606
+ inLaterDay(target, obs, noon, crossing, kind) {
607
+ if (crossing.date.getTime() - noon.date.getTime() < MIN_HALF_DAY_MS)
608
+ return false;
609
+ const midnight = SearchHourAngle(target, obs, 12, noon, +1).time;
610
+ if (crossing.date <= midnight.date)
611
+ return false;
612
+ return (kind === 'rise' || crossing.date > SearchHourAngle(target, obs, 0, midnight, +1).time.date);
613
+ }
614
+ /**
615
+ * Resume just past a cycle's set, so the next search finds the following rise and the set
616
+ * that closes it. Advancing a whole day from the rise instead overshot the next day's set
617
+ * for any body that rises earlier each day, dropping a full cycle from a multi-count call.
618
+ * A sunset with no sunrise in the window after it is the last before a polar night: resuming
619
+ * past that day's lower culmination keeps a continuation from opening on the same evening,
620
+ * which `restOfDarkDay` would report again as the rest of that day.
621
+ */
622
+ pastSet(target, obs, set, isSun, riseFrom) {
623
+ const next = new Date(set.date.getTime() + RESUME_STEP_MS);
624
+ return isSun && riseFrom(next) === null ? this.pastLowerCulmination(target, obs, next) : next;
625
+ }
626
+ /**
627
+ * Resume just past the lower culmination after `from`, where a cycle with no set ends: the
628
+ * next culmination is then the next day's, and any rise on that day still lies ahead.
629
+ * Stepping a fixed 24 h instead drifts against the culminations — the Moon's come about 50
630
+ * minutes later each day, a planet's about 4 minutes earlier — so one culmination came back
631
+ * in two cycles, or one was stepped over.
632
+ */
633
+ pastLowerCulmination(target, obs, from) {
634
+ const midnight = SearchHourAngle(target, obs, 12, from, +1).time;
635
+ return new Date(midnight.date.getTime() + RESUME_STEP_MS);
636
+ }
637
+ /**
638
+ * Civil/nautical/astronomical dawn+dusk pairs for the Sun, searched forward from `start` and
639
+ * stopping at `until` — the sunrise, or the culmination of a day without one, that ends the
640
+ * night the pairs belong to — so a crossing absent from that night comes back null.
641
+ */
642
+ twilight(obs, start, until, timezone) {
643
+ const limitDays = (until.getTime() - start.getTime()) / 86_400_000;
381
644
  const pair = (altitude) => {
382
645
  // Dawn = Sun ascending (+1) through the altitude; dusk = descending (-1).
383
- const dawn = SearchAltitude(Body.Sun, obs, +1, start, 2, altitude);
384
- const dusk = SearchAltitude(Body.Sun, obs, -1, start, 2, altitude);
646
+ const dawn = SearchAltitude(Body.Sun, obs, +1, start, limitDays, altitude);
647
+ const dusk = SearchAltitude(Body.Sun, obs, -1, start, limitDays, altitude);
385
648
  const out = {
386
649
  dawnUtc: dawn ? dawn.toString() : null,
387
650
  duskUtc: dusk ? dusk.toString() : null,
@@ -453,9 +716,13 @@ export class EphemerisService {
453
716
  * Search forward for the next `count` occurrences of an event class. Every search stops
454
717
  * at the end of the supported span, which is the only reason fewer than `count` come back.
455
718
  * An observer adds local circumstances to either eclipse class, and for solar eclipses it
456
- * switches the search from global to observer-local.
719
+ * switches the search from global to observer-local. `body2` turns a conjunction with
720
+ * the Sun into a conjunction of two bodies, and is rejected on every other class.
457
721
  */
458
722
  findEvents(event, opts) {
723
+ if (opts.body2 !== undefined && event !== 'conjunction') {
724
+ throw invalidBodyPair(`body2 applies only to the conjunction event, not "${event}".`);
725
+ }
459
726
  switch (event) {
460
727
  case 'equinox':
461
728
  case 'solstice':
@@ -468,6 +735,9 @@ export class EphemerisService {
468
735
  return this.solarEclipseEvents(opts.start, opts.count, opts.observer, opts.timezone);
469
736
  case 'opposition':
470
737
  case 'conjunction':
738
+ if (opts.body2 !== undefined) {
739
+ return this.pairConjunctionEvents(...resolvePair(opts.body, opts.body2), opts.start, opts.count, opts.timezone);
740
+ }
471
741
  return this.relativeLongitudeEvents(event, resolveBody(event, opts.body), opts.start, opts.count, opts.timezone);
472
742
  case 'max_elongation':
473
743
  return this.maxElongationEvents(resolveBody(event, opts.body), opts.start, opts.count, opts.timezone);
@@ -523,7 +793,10 @@ export class EphemerisService {
523
793
  lunarEclipseEvents(start, count, observer, timezone) {
524
794
  const obs = observer ? this.toObserver(observer) : undefined;
525
795
  const out = [];
526
- let ecl = SearchLunarEclipse(start);
796
+ // Eclipse searches seed from syzygy; the peak can fall on either side of it.
797
+ let ecl = SearchLunarEclipse(new Date(start.getTime() - 86_400_000));
798
+ while (ecl.peak.date < start)
799
+ ecl = NextLunarEclipse(ecl.peak);
527
800
  for (let i = 0; i < count && withinSpan(ecl.peak.date); i++) {
528
801
  const peak = ecl.peak;
529
802
  /**
@@ -572,7 +845,10 @@ export class EphemerisService {
572
845
  const out = [];
573
846
  if (observer) {
574
847
  const obs = this.toObserver(observer);
575
- let ecl = SearchLocalSolarEclipse(start, obs);
848
+ // The engine searches for the local peak within 0.2 days of new moon.
849
+ let ecl = SearchLocalSolarEclipse(new Date(start.getTime() - 86_400_000), obs);
850
+ while (ecl.peak.time.date < start)
851
+ ecl = NextLocalSolarEclipse(ecl.peak.time, obs);
576
852
  for (let i = 0; i < count && withinSpan(ecl.peak.time.date); i++) {
577
853
  const peakTime = ecl.peak.time;
578
854
  const contacts = [
@@ -597,7 +873,9 @@ export class EphemerisService {
597
873
  }
598
874
  }
599
875
  else {
600
- let ecl = SearchGlobalSolarEclipse(start);
876
+ let ecl = SearchGlobalSolarEclipse(new Date(start.getTime() - 86_400_000));
877
+ while (ecl.peak.date < start)
878
+ ecl = NextGlobalSolarEclipse(ecl.peak);
601
879
  for (let i = 0; i < count && withinSpan(ecl.peak.date); i++) {
602
880
  const rec = {
603
881
  event: 'solar_eclipse',
@@ -657,6 +935,52 @@ export class EphemerisService {
657
935
  }
658
936
  return out;
659
937
  }
938
+ /**
939
+ * Conjunctions of two bodies: the instants they share an ecliptic longitude seen from
940
+ * Earth's center. The longitude offset is sampled forward and each zero crossing refined
941
+ * with `Search`. Each step lasts as long as the offset cannot reach zero at the pair's
942
+ * fastest combined motion, and never less than `PAIR_SCAN_MIN_STEP_DAYS`, so a step holds
943
+ * at most one conjunction.
944
+ */
945
+ pairConjunctionEvents(body, body2, start, count, timezone) {
946
+ const [b1, b2] = [BODY_ENUM[body], BODY_ENUM[body2]];
947
+ const maxRate = MAX_LONGITUDE_RATE_DEG_PER_DAY[body] + MAX_LONGITUDE_RATE_DEG_PER_DAY[body2];
948
+ /** `body`'s longitude minus `body2`'s in (−180°, 180°]: 0 at conjunction, ±180 opposite. */
949
+ const offset = (t) => {
950
+ const d = PairLongitude(b1, b2, t);
951
+ return d > 180 ? d - 360 : d;
952
+ };
953
+ const end = MakeTime(SPAN_END);
954
+ const out = [];
955
+ let t1 = MakeTime(start);
956
+ let f1 = offset(t1);
957
+ while (out.length < count && t1.ut < end.ut) {
958
+ const t2 = t1.AddDays(Math.max(PAIR_SCAN_MIN_STEP_DAYS, Math.abs(f1) / maxRate));
959
+ const f2 = offset(t2);
960
+ // A sign change smaller than 180° passes through 0; a larger one is the wrap at ±180°.
961
+ if (f1 < 0 !== f2 < 0 && Math.abs(f1 - f2) < 180) {
962
+ const rising = f1 < 0;
963
+ const time = Search((t) => (rising ? offset(t) : -offset(t)), t1, t2);
964
+ if (!time)
965
+ throw new Error(`Conjunction search found no crossing between ${t1} and ${t2}.`);
966
+ if (!withinSpan(time.date))
967
+ break;
968
+ const rec = {
969
+ event: 'conjunction',
970
+ timeUtc: time.toString(),
971
+ body,
972
+ body2,
973
+ separationDegrees: AngleBetween(GeoVector(b1, time, true), GeoVector(b2, time, true)),
974
+ };
975
+ if (timezone)
976
+ rec.timeLocal = this.formatLocal(time.date, timezone);
977
+ out.push(rec);
978
+ }
979
+ t1 = t2;
980
+ f1 = f2;
981
+ }
982
+ return out;
983
+ }
660
984
  maxElongationEvents(body, start, count, timezone) {
661
985
  const out = [];
662
986
  let cursor = start;
@@ -927,7 +1251,7 @@ const EVENT_BODIES = {
927
1251
  },
928
1252
  conjunction: {
929
1253
  bodies: new Set(PLANETS),
930
- hint: 'Use a planet — mercury through pluto. Conjunction measures a planet against the Sun, so the Sun, Moon, and Earth have none.',
1254
+ hint: 'Use a planet — mercury through pluto. Without body2, conjunction measures a planet against the Sun, so the Sun, Moon, and Earth have none; for the Moon meeting a planet, add that planet as body2.',
931
1255
  },
932
1256
  max_elongation: {
933
1257
  bodies: INNER_PLANETS,
@@ -944,12 +1268,8 @@ const EVENT_BODIES = {
944
1268
  * `body_not_supported` contract reason.
945
1269
  */
946
1270
  function resolveBody(event, body) {
947
- if (!body) {
948
- throw invalidParams(`The "${event}" event requires a target body.`, {
949
- reason: 'body_required',
950
- recovery: { hint: 'Add the target body (e.g. "mars" or "jupiter") and retry.' },
951
- });
952
- }
1271
+ if (!body)
1272
+ throw bodyRequired(event);
953
1273
  const spec = EVENT_BODIES[event];
954
1274
  if (!spec.bodies.has(body)) {
955
1275
  throw invalidParams(`The "${event}" event is not defined for ${body}.`, {
@@ -959,6 +1279,41 @@ function resolveBody(event, body) {
959
1279
  }
960
1280
  return body;
961
1281
  }
1282
+ /** A body-relative event searched without its target body — the `body_required` reason. */
1283
+ function bodyRequired(event) {
1284
+ return invalidParams(`The "${event}" event requires a target body.`, {
1285
+ reason: 'body_required',
1286
+ recovery: { hint: 'Add the target body (e.g. "mars" or "jupiter") and retry.' },
1287
+ });
1288
+ }
1289
+ /**
1290
+ * A `body2` the search cannot pair — the `invalid_body_pair` reason. The hint is written
1291
+ * here, with no ctx to resolve it from, so astronomy_find_events declares the same string.
1292
+ */
1293
+ function invalidBodyPair(message) {
1294
+ return invalidParams(message, {
1295
+ reason: 'invalid_body_pair',
1296
+ recovery: {
1297
+ hint: 'body2 applies only to event "conjunction" and pairs two different bodies among the Moon and the planets (mercury through pluto). For a planet\'s conjunction with the Sun, pass the planet as body and omit body2; for the Moon\'s, search moon_quarter for the new moon.',
1298
+ },
1299
+ });
1300
+ }
1301
+ /**
1302
+ * Resolve the two bodies of a two-body conjunction: require `body`, and reject one that
1303
+ * cannot be paired (the Sun or Earth) or a pair of the same body twice. Throws with the
1304
+ * `body_required` or `invalid_body_pair` contract reason.
1305
+ */
1306
+ function resolvePair(body, body2) {
1307
+ if (!body)
1308
+ throw bodyRequired('conjunction');
1309
+ if (!isPairBody(body)) {
1310
+ throw invalidBodyPair(`A two-body conjunction pairs the Moon and the planets; body "${body}" is not one of them.`);
1311
+ }
1312
+ if (body === body2) {
1313
+ throw invalidBodyPair(`body and body2 are both "${body}"; a conjunction needs two different bodies.`);
1314
+ }
1315
+ return [body, body2];
1316
+ }
962
1317
  // --- Init / accessor pattern ------------------------------------------------
963
1318
  let _service;
964
1319
  /** Initialize the ephemeris service. Pure compute — no config or storage needed. */