@cyanheads/astronomy-mcp-server 0.4.0 → 0.4.2

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 (61) hide show
  1. package/AGENTS.md +17 -16
  2. package/CLAUDE.md +17 -16
  3. package/Dockerfile +91 -36
  4. package/README.md +69 -94
  5. package/changelog/0.4.x/0.4.1.md +27 -0
  6. package/changelog/0.4.x/0.4.2.md +37 -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/resources/definitions/body.resource.d.ts.map +1 -1
  10. package/dist/mcp-server/resources/definitions/body.resource.js +1 -3
  11. package/dist/mcp-server/resources/definitions/body.resource.js.map +1 -1
  12. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts +31 -4
  13. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts.map +1 -1
  14. package/dist/mcp-server/tools/definitions/find-events.tool.js +99 -25
  15. package/dist/mcp-server/tools/definitions/find-events.tool.js.map +1 -1
  16. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts +29 -7
  17. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts.map +1 -1
  18. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js +219 -49
  19. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js.map +1 -1
  20. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js +1 -0
  22. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts +49 -2
  24. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js +85 -43
  26. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts +28 -4
  28. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts.map +1 -1
  29. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js +97 -23
  30. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts.map +1 -1
  32. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js +2 -1
  33. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js.map +1 -1
  34. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts.map +1 -1
  35. package/dist/mcp-server/tools/definitions/list-visible.tool.js +1 -0
  36. package/dist/mcp-server/tools/definitions/list-visible.tool.js.map +1 -1
  37. package/dist/services/ephemeris/ephemeris-service.d.ts +78 -15
  38. package/dist/services/ephemeris/ephemeris-service.d.ts.map +1 -1
  39. package/dist/services/ephemeris/ephemeris-service.js +374 -98
  40. package/dist/services/ephemeris/ephemeris-service.js.map +1 -1
  41. package/dist/services/ephemeris/iso-time.d.ts +2 -2
  42. package/dist/services/ephemeris/iso-time.js +5 -5
  43. package/dist/services/ephemeris/types.d.ts +42 -1
  44. package/dist/services/ephemeris/types.d.ts.map +1 -1
  45. package/dist/services/ephemeris/types.js +16 -0
  46. package/dist/services/ephemeris/types.js.map +1 -1
  47. package/dist/services/horizons/horizons-service.d.ts +25 -3
  48. package/dist/services/horizons/horizons-service.d.ts.map +1 -1
  49. package/dist/services/horizons/horizons-service.js +154 -15
  50. package/dist/services/horizons/horizons-service.js.map +1 -1
  51. package/dist/services/horizons/types.d.ts +8 -4
  52. package/dist/services/horizons/types.d.ts.map +1 -1
  53. package/dist/services/satellite/satellite-service.d.ts +48 -10
  54. package/dist/services/satellite/satellite-service.d.ts.map +1 -1
  55. package/dist/services/satellite/satellite-service.js +215 -102
  56. package/dist/services/satellite/satellite-service.js.map +1 -1
  57. package/dist/services/satellite/types.d.ts +36 -2
  58. package/dist/services/satellite/types.d.ts.map +1 -1
  59. package/dist/services/satellite/types.js.map +1 -1
  60. package/package.json +12 -11
  61. package/server.json +10 -24
@@ -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, 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,10 +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: this method takes no `ctx`, so
111
- * `ctx.recoveryFor()` is unavailable and the hint has to be written at the throw
112
- * site to reach `data.recovery.hint` and the `Recovery:` line mirrored into
113
- * `content[]`.
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.
114
151
  */
115
152
  resolveTime(time) {
116
153
  const date = time ? parseIsoInstant(time) : new Date();
@@ -125,10 +162,7 @@ export class EphemerisService {
125
162
  const year = date.getUTCFullYear();
126
163
  const { firstYear, lastYear } = SUPPORTED_SPAN;
127
164
  if (year < firstYear || year > lastYear) {
128
- throw invalidParams(`Time ${date.toISOString()} is outside the high-accuracy span (${firstYear}–${lastYear}).`, {
129
- reason: 'time_out_of_range',
130
- recovery: { hint: `Use a date between ${firstYear} and ${lastYear}.` },
131
- });
165
+ throw invalidParams(`Time ${date.toISOString()} is outside the high-accuracy span (${firstYear}–${lastYear}).`, { reason: 'time_out_of_range' });
132
166
  }
133
167
  return date;
134
168
  }
@@ -289,100 +323,258 @@ export class EphemerisService {
289
323
  return pos;
290
324
  }
291
325
  // ---- Rise / set / transit + twilight ------------------------------------
292
- /** 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. */
293
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) {
294
341
  const obs = this.toObserver(observer);
295
- const events = [];
296
- let cursor = start;
297
- for (let i = 0; i < count; i++) {
298
- const rise = SearchRiseSet(BODY_ENUM[body], obs, +1, cursor, RISE_SET_WINDOW_DAYS);
299
- const set = SearchRiseSet(BODY_ENUM[body], obs, -1, cursor, RISE_SET_WINDOW_DAYS);
300
- /**
301
- * Both searches run forward from the cursor, so when the body is already up the next
302
- * set arrives before the next rise and the two belong to different cycles — pairing
303
- * them reports a set hours before its own rise. The interval in progress is the one
304
- * the caller is standing in, and its rise is behind the cursor where a forward-only
305
- * search cannot reach it, so report that interval as a partial cycle naming the
306
- * imminent set. Beginning at the next complete cycle instead would be chronologically
307
- * tidy and quietly drop tonight's set, which is the event a caller asking during the
308
- * day most needs.
309
- */
310
- const alreadyUp = set !== null && (rise === null || set.date < rise.date);
311
- const cycleRise = alreadyUp ? null : rise;
312
- let transitUtc = null;
313
- let transitAlt = null;
314
- try {
315
- const transit = SearchHourAngle(BODY_ENUM[body], obs, 0, cursor, +1);
316
- /**
317
- * The meridian crossing is found regardless of altitude, so the next one after the
318
- * cursor can belong to a neighbouring cycle — before this cycle's rise, or after
319
- * its set. Report it only when it falls inside the interval it is attached to.
320
- */
321
- const at = transit.time.date;
322
- if ((cycleRise === null || at > cycleRise.date) && (set === null || at < set.date)) {
323
- transitUtc = transit.time.toString();
324
- transitAlt = transit.hor.altitude;
325
- }
326
- }
327
- catch {
328
- 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, SearchRiseSet(target, obs, +1, cursor, RISE_SET_WINDOW_DAYS));
329
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 firstRise = opening.alreadyUp ? null : opening.rise;
360
+ const sunsetBefore = isSun && firstRise ? SearchRiseSet(Body.Sun, obs, -1, start, -RISE_SET_WINDOW_DAYS) : null;
361
+ let cycle = (isSun ? this.restOfDarkDay(obs, start, opening, sunsetBefore) : undefined) ??
362
+ cycleAt(start, opening);
363
+ const opener = cycle;
364
+ const cycles = [cycle];
365
+ let resumeAt = cycle.resume();
366
+ while (cycles.length < count) {
367
+ cycle = cycleAt(resumeAt);
368
+ cycles.push(cycle);
369
+ resumeAt = cycle.resume();
370
+ }
371
+ /**
372
+ * A Sun cycle's night runs from its own day to the start of the next cycle's: dusk after its
373
+ * set (or, with no set, after its culmination) and dawn before the next cycle's rise or
374
+ * culmination. The search stops there, so a depth this night never reaches is null rather
375
+ * than a later night's time. The last cycle's night ends where the cycle a continuation from
376
+ * `resumeAt` opens with begins, so a series served across calls splits its cycles' nights
377
+ * exactly as one search does. `nightInProgress` is the exception: a continuation that
378
+ * resumes past a set starts at night, so it reports again the night the last cycle carried.
379
+ */
380
+ const nightEnds = isSun
381
+ ? [...cycles.slice(1).map((c) => c.nightFrom), cycleAt(resumeAt).nightFrom]
382
+ : [];
383
+ const events = cycles.map((c, i) => {
330
384
  const event = {
331
- riseUtc: cycleRise ? cycleRise.toString() : null,
332
- setUtc: set ? set.toString() : null,
333
- transitUtc,
334
- transitAltitudeDegrees: transitAlt,
385
+ riseUtc: c.rise ? c.rise.toString() : null,
386
+ setUtc: c.set ? c.set.toString() : null,
387
+ transitUtc: c.transit ? c.transit.time.toString() : null,
388
+ transitAltitudeDegrees: c.transit ? c.transit.hor.altitude : null,
335
389
  };
336
- if (cycleRise === null && set === null) {
337
- // Circumpolar or never-rises: distinguish by transit altitude.
338
- event.note =
339
- transitAlt !== null && transitAlt > 0
340
- ? 'Circumpolar — never sets at this latitude/date.'
341
- : 'Never rises above the horizon at this latitude/date.';
342
- }
343
- else if (cycleRise === null) {
344
- event.note = 'Already above the horizon at the search start — no rise in this cycle.';
345
- }
346
- else if (set === null) {
347
- event.note = 'Does not set before the next rise — circumpolar window.';
348
- }
349
- if (body === 'sun') {
350
- /**
351
- * Anchor the pair to this cycle's own rise, not the resume cursor: the cursor sits
352
- * just past the previous set, which is still short of that evening's dusk, so a
353
- * cursor-anchored search hands the next cycle the previous evening's twilight while
354
- * its rise and set have already moved on a day.
355
- */
356
- event.twilight = this.twilight(obs, cycleRise?.date ?? cursor, timezone);
357
- }
390
+ if (c.note)
391
+ event.note = c.note;
392
+ const nightEnd = nightEnds[i];
393
+ if (nightEnd)
394
+ event.twilight = this.twilight(obs, c.nightFrom, nightEnd, timezone);
358
395
  if (timezone) {
359
- if (cycleRise)
360
- event.riseLocal = this.formatLocal(cycleRise.date, timezone);
361
- if (set)
362
- event.setLocal = this.formatLocal(set.date, timezone);
363
- if (transitUtc)
364
- event.transitLocal = this.formatLocal(new Date(transitUtc), timezone);
396
+ if (c.rise)
397
+ event.riseLocal = this.formatLocal(c.rise.date, timezone);
398
+ if (c.set)
399
+ event.setLocal = this.formatLocal(c.set.date, timezone);
400
+ if (c.transit)
401
+ event.transitLocal = this.formatLocal(c.transit.time.date, timezone);
365
402
  }
366
- events.push(event);
403
+ return event;
404
+ });
405
+ const search = { events, resumeAt };
406
+ /**
407
+ * A search that opens with a rise means the Sun was below the horizon at `start`, so the
408
+ * cycles begin at the next sunrise and their twilight is the night after it. The night under
409
+ * way is reported on its own, from the sunset that began it to where the first cycle's night
410
+ * begins — that sunrise, or the culmination of a day the Sun does not rise on; times in it
411
+ * before `start` have passed but stay, so null keeps meaning only "this night never reaches
412
+ * the depth". The sunset counts only when it follows the Sun's last culmination before
413
+ * `start`. A sunset before that culmination began an earlier night: a day the Sun did not
414
+ * rise on has come between, and the night under way began at its culmination, not at a
415
+ * sunset. That night is omitted, as is one with no sunset in the look-back window (the end of
416
+ * a polar night) or no sunrise in the forward window (its beginning); before that day's lower
417
+ * culmination the rest-of-day first cycle carries it instead.
418
+ */
419
+ if (firstRise &&
420
+ sunsetBefore &&
421
+ sunsetBefore.date > SearchHourAngle(Body.Sun, obs, 0, start, -1).time.date) {
422
+ search.nightInProgress = this.twilight(obs, sunsetBefore.date, opener.nightFrom, timezone);
423
+ }
424
+ return search;
425
+ }
426
+ /** The next rise, set, and culmination searched forward from one cursor. */
427
+ crossingsFrom(target, obs, cursor, riseFrom) {
428
+ const rise = riseFrom(cursor);
429
+ const set = SearchRiseSet(target, obs, -1, cursor, RISE_SET_WINDOW_DAYS);
430
+ return {
431
+ rise,
432
+ set,
367
433
  /**
368
- * Resume just past this cycle's set, so the next search finds the following rise and
369
- * the set that closes it. Advancing a whole day from the rise instead overshot the
370
- * next day's set for any body that rises earlier each day, dropping a full cycle from
371
- * a multi-count call. With no set to resume from the body is circumpolar for this
372
- * window, where a day is the only meaningful step.
434
+ * Both searches run forward from the cursor, so when the body is already up the next set
435
+ * arrives before the next rise and the two belong to different cycles — pairing them
436
+ * reports a set hours before its own rise. The interval in progress is the one the caller
437
+ * is standing in, and its rise is behind the cursor where a forward-only search cannot
438
+ * reach it, so that interval is reported as a partial cycle naming the imminent set.
439
+ * Beginning at the next complete cycle instead would be chronologically tidy and quietly
440
+ * drop tonight's set, which is the event a caller asking during the day most needs.
373
441
  */
374
- cursor = set
375
- ? new Date(set.date.getTime() + 1000)
376
- : new Date(cursor.getTime() + 24 * 3600 * 1000);
442
+ alreadyUp: set !== null && (rise === null || set.date < rise.date),
443
+ culmination: SearchHourAngle(target, obs, 0, cursor, +1),
444
+ };
445
+ }
446
+ /**
447
+ * The cycle that opens at `cursor`: the day of the next culmination, or — when the body is
448
+ * already up — the interval in progress.
449
+ */
450
+ dayCycle(target, obs, cursor, crossings, isSun, riseFrom) {
451
+ const { alreadyUp, culmination } = crossings;
452
+ const noon = culmination.time;
453
+ const pastMidnight = () => this.pastLowerCulmination(target, obs, noon);
454
+ const next = alreadyUp ? crossings.set : crossings.rise;
455
+ /**
456
+ * No crossing inside the search window, or the first one belongs to a later day: the body
457
+ * neither rises nor sets on this culmination's day. That day is a cycle of its own — taking
458
+ * the later day's crossing here instead folded this day into it and dropped it. Its night is
459
+ * the one after its culmination, where a set would have put it.
460
+ */
461
+ if (next === null || this.inLaterDay(target, obs, noon, next, alreadyUp ? 'set' : 'rise')) {
462
+ return {
463
+ rise: null,
464
+ set: null,
465
+ transit: culmination,
466
+ note: culmination.hor.altitude > 0
467
+ ? 'Circumpolar — never sets at this latitude/date.'
468
+ : 'Never rises above the horizon at this latitude/date.',
469
+ nightFrom: noon.date,
470
+ resume: pastMidnight,
471
+ };
377
472
  }
378
- return events;
473
+ const rise = alreadyUp ? null : crossings.rise;
474
+ const set = crossings.set && (alreadyUp || !this.inLaterDay(target, obs, noon, crossings.set, 'set'))
475
+ ? crossings.set
476
+ : null;
477
+ /**
478
+ * The meridian crossing is found regardless of altitude, so the next one after the cursor
479
+ * can belong to a neighbouring cycle — before this cycle's rise, or after its set. Report it
480
+ * only when it falls inside the interval it is attached to.
481
+ */
482
+ const inside = (rise === null || noon.date > rise.date) && (set === null || noon.date < set.date);
483
+ return {
484
+ rise,
485
+ set,
486
+ transit: inside ? culmination : null,
487
+ note: rise === null
488
+ ? 'Already above the horizon when this cycle opens — no rise in this cycle.'
489
+ : set === null
490
+ ? 'Does not set before the next rise — circumpolar window.'
491
+ : undefined,
492
+ nightFrom: rise?.date ?? cursor,
493
+ resume: set ? () => this.pastSet(target, obs, set, isSun, riseFrom) : pastMidnight,
494
+ };
495
+ }
496
+ /**
497
+ * The rest of a dark day, as the first cycle of a Sun search: `start` falls after the day's
498
+ * culmination, the Sun is below the horizon, and nothing else would carry the night that
499
+ * follows — a polar-night afternoon, or the evening of the last sunset before a polar night.
500
+ * Neither has a sunrise ahead that opens the next cycle within a day, so without this cycle
501
+ * the night under way falls between the cycles. Its night runs from the day's culmination,
502
+ * so a dusk `start` has already passed is kept, as `nightInProgress` keeps passed times. A
503
+ * rise before the day's lower culmination means the day is not dark for its rest — near the
504
+ * pole at an equinox the Sun can rise and set again after a culmination below the horizon —
505
+ * so the ordinary cycle from `start` reports them instead.
506
+ */
507
+ restOfDarkDay(obs, start, crossings, sunsetBefore) {
508
+ const { alreadyUp, rise, culmination } = crossings;
509
+ if (alreadyUp || (rise === null && culmination.hor.altitude > 0))
510
+ return;
511
+ const midnight = SearchHourAngle(Body.Sun, obs, 12, start, +1).time;
512
+ // A lower culmination before the next culmination means `start` is past this day's.
513
+ if (midnight.date > culmination.time.date)
514
+ return;
515
+ if (rise !== null && rise.date < midnight.date)
516
+ return;
517
+ const noon = SearchHourAngle(Body.Sun, obs, 0, start, -1).time;
518
+ // An ordinary evening: the sunrise ahead opens the next cycle and nightInProgress carries this night.
519
+ if (rise !== null && sunsetBefore !== null && sunsetBefore.date > noon.date)
520
+ return;
521
+ return {
522
+ rise: null,
523
+ set: null,
524
+ transit: null,
525
+ 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.',
526
+ nightFrom: noon.date,
527
+ resume: () => new Date(midnight.date.getTime() + RESUME_STEP_MS),
528
+ };
529
+ }
530
+ /**
531
+ * Whether a rise or set found after a culmination belongs to a later day than that
532
+ * culmination's. A rise opens the day whose culmination follows it, so one past this day's
533
+ * lower culmination opens a later day; a set closes the day whose culmination precedes it,
534
+ * so only one past the next culmination does.
535
+ */
536
+ inLaterDay(target, obs, noon, crossing, kind) {
537
+ if (crossing.date.getTime() - noon.date.getTime() < MIN_HALF_DAY_MS)
538
+ return false;
539
+ const midnight = SearchHourAngle(target, obs, 12, noon, +1).time;
540
+ if (crossing.date <= midnight.date)
541
+ return false;
542
+ return (kind === 'rise' || crossing.date > SearchHourAngle(target, obs, 0, midnight, +1).time.date);
543
+ }
544
+ /**
545
+ * Resume just past a cycle's set, so the next search finds the following rise and the set
546
+ * that closes it. Advancing a whole day from the rise instead overshot the next day's set
547
+ * for any body that rises earlier each day, dropping a full cycle from a multi-count call.
548
+ * A sunset with no sunrise in the window after it is the last before a polar night: resuming
549
+ * past that day's lower culmination keeps a continuation from opening on the same evening,
550
+ * which `restOfDarkDay` would report again as the rest of that day.
551
+ */
552
+ pastSet(target, obs, set, isSun, riseFrom) {
553
+ const next = new Date(set.date.getTime() + RESUME_STEP_MS);
554
+ return isSun && riseFrom(next) === null ? this.pastLowerCulmination(target, obs, next) : next;
379
555
  }
380
- /** Civil/nautical/astronomical dawn+dusk pairs for the Sun on the search day. */
381
- twilight(obs, start, timezone) {
556
+ /**
557
+ * Resume just past the lower culmination after `from`, where a cycle with no set ends: the
558
+ * next culmination is then the next day's, and any rise on that day still lies ahead.
559
+ * Stepping a fixed 24 h instead drifts against the culminations — the Moon's come about 50
560
+ * minutes later each day, a planet's about 4 minutes earlier — so one culmination came back
561
+ * in two cycles, or one was stepped over.
562
+ */
563
+ pastLowerCulmination(target, obs, from) {
564
+ const midnight = SearchHourAngle(target, obs, 12, from, +1).time;
565
+ return new Date(midnight.date.getTime() + RESUME_STEP_MS);
566
+ }
567
+ /**
568
+ * Civil/nautical/astronomical dawn+dusk pairs for the Sun, searched forward from `start` and
569
+ * stopping at `until` — the sunrise, or the culmination of a day without one, that ends the
570
+ * night the pairs belong to — so a depth that night never reaches comes back null.
571
+ */
572
+ twilight(obs, start, until, timezone) {
573
+ const limitDays = (until.getTime() - start.getTime()) / 86_400_000;
382
574
  const pair = (altitude) => {
383
575
  // Dawn = Sun ascending (+1) through the altitude; dusk = descending (-1).
384
- const dawn = SearchAltitude(Body.Sun, obs, +1, start, 2, altitude);
385
- const dusk = SearchAltitude(Body.Sun, obs, -1, start, 2, altitude);
576
+ const dawn = SearchAltitude(Body.Sun, obs, +1, start, limitDays, altitude);
577
+ const dusk = SearchAltitude(Body.Sun, obs, -1, start, limitDays, altitude);
386
578
  const out = {
387
579
  dawnUtc: dawn ? dawn.toString() : null,
388
580
  duskUtc: dusk ? dusk.toString() : null,
@@ -454,9 +646,13 @@ export class EphemerisService {
454
646
  * Search forward for the next `count` occurrences of an event class. Every search stops
455
647
  * at the end of the supported span, which is the only reason fewer than `count` come back.
456
648
  * An observer adds local circumstances to either eclipse class, and for solar eclipses it
457
- * switches the search from global to observer-local.
649
+ * switches the search from global to observer-local. `body2` turns a conjunction with
650
+ * the Sun into a conjunction of two bodies, and is rejected on every other class.
458
651
  */
459
652
  findEvents(event, opts) {
653
+ if (opts.body2 !== undefined && event !== 'conjunction') {
654
+ throw invalidBodyPair(`body2 applies only to the conjunction event, not "${event}".`);
655
+ }
460
656
  switch (event) {
461
657
  case 'equinox':
462
658
  case 'solstice':
@@ -469,6 +665,9 @@ export class EphemerisService {
469
665
  return this.solarEclipseEvents(opts.start, opts.count, opts.observer, opts.timezone);
470
666
  case 'opposition':
471
667
  case 'conjunction':
668
+ if (opts.body2 !== undefined) {
669
+ return this.pairConjunctionEvents(...resolvePair(opts.body, opts.body2), opts.start, opts.count, opts.timezone);
670
+ }
472
671
  return this.relativeLongitudeEvents(event, resolveBody(event, opts.body), opts.start, opts.count, opts.timezone);
473
672
  case 'max_elongation':
474
673
  return this.maxElongationEvents(resolveBody(event, opts.body), opts.start, opts.count, opts.timezone);
@@ -658,6 +857,52 @@ export class EphemerisService {
658
857
  }
659
858
  return out;
660
859
  }
860
+ /**
861
+ * Conjunctions of two bodies: the instants they share an ecliptic longitude seen from
862
+ * Earth's center. The longitude offset is sampled forward and each zero crossing refined
863
+ * with `Search`. Each step lasts as long as the offset cannot reach zero at the pair's
864
+ * fastest combined motion, and never less than `PAIR_SCAN_MIN_STEP_DAYS`, so a step holds
865
+ * at most one conjunction.
866
+ */
867
+ pairConjunctionEvents(body, body2, start, count, timezone) {
868
+ const [b1, b2] = [BODY_ENUM[body], BODY_ENUM[body2]];
869
+ const maxRate = MAX_LONGITUDE_RATE_DEG_PER_DAY[body] + MAX_LONGITUDE_RATE_DEG_PER_DAY[body2];
870
+ /** `body`'s longitude minus `body2`'s in (−180°, 180°]: 0 at conjunction, ±180 opposite. */
871
+ const offset = (t) => {
872
+ const d = PairLongitude(b1, b2, t);
873
+ return d > 180 ? d - 360 : d;
874
+ };
875
+ const end = MakeTime(SPAN_END);
876
+ const out = [];
877
+ let t1 = MakeTime(start);
878
+ let f1 = offset(t1);
879
+ while (out.length < count && t1.ut < end.ut) {
880
+ const t2 = t1.AddDays(Math.max(PAIR_SCAN_MIN_STEP_DAYS, Math.abs(f1) / maxRate));
881
+ const f2 = offset(t2);
882
+ // A sign change smaller than 180° passes through 0; a larger one is the wrap at ±180°.
883
+ if (f1 < 0 !== f2 < 0 && Math.abs(f1 - f2) < 180) {
884
+ const rising = f1 < 0;
885
+ const time = Search((t) => (rising ? offset(t) : -offset(t)), t1, t2);
886
+ if (!time)
887
+ throw new Error(`Conjunction search found no crossing between ${t1} and ${t2}.`);
888
+ if (!withinSpan(time.date))
889
+ break;
890
+ const rec = {
891
+ event: 'conjunction',
892
+ timeUtc: time.toString(),
893
+ body,
894
+ body2,
895
+ separationDegrees: AngleBetween(GeoVector(b1, time, true), GeoVector(b2, time, true)),
896
+ };
897
+ if (timezone)
898
+ rec.timeLocal = this.formatLocal(time.date, timezone);
899
+ out.push(rec);
900
+ }
901
+ t1 = t2;
902
+ f1 = f2;
903
+ }
904
+ return out;
905
+ }
661
906
  maxElongationEvents(body, start, count, timezone) {
662
907
  const out = [];
663
908
  let cursor = start;
@@ -928,7 +1173,7 @@ const EVENT_BODIES = {
928
1173
  },
929
1174
  conjunction: {
930
1175
  bodies: new Set(PLANETS),
931
- hint: 'Use a planet — mercury through pluto. Conjunction measures a planet against the Sun, so the Sun, Moon, and Earth have none.',
1176
+ 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.',
932
1177
  },
933
1178
  max_elongation: {
934
1179
  bodies: INNER_PLANETS,
@@ -945,12 +1190,8 @@ const EVENT_BODIES = {
945
1190
  * `body_not_supported` contract reason.
946
1191
  */
947
1192
  function resolveBody(event, body) {
948
- if (!body) {
949
- throw invalidParams(`The "${event}" event requires a target body.`, {
950
- reason: 'body_required',
951
- recovery: { hint: 'Add the target body (e.g. "mars" or "jupiter") and retry.' },
952
- });
953
- }
1193
+ if (!body)
1194
+ throw bodyRequired(event);
954
1195
  const spec = EVENT_BODIES[event];
955
1196
  if (!spec.bodies.has(body)) {
956
1197
  throw invalidParams(`The "${event}" event is not defined for ${body}.`, {
@@ -960,6 +1201,41 @@ function resolveBody(event, body) {
960
1201
  }
961
1202
  return body;
962
1203
  }
1204
+ /** A body-relative event searched without its target body — the `body_required` reason. */
1205
+ function bodyRequired(event) {
1206
+ return invalidParams(`The "${event}" event requires a target body.`, {
1207
+ reason: 'body_required',
1208
+ recovery: { hint: 'Add the target body (e.g. "mars" or "jupiter") and retry.' },
1209
+ });
1210
+ }
1211
+ /**
1212
+ * A `body2` the search cannot pair — the `invalid_body_pair` reason. The hint is written
1213
+ * here, with no ctx to resolve it from, so astronomy_find_events declares the same string.
1214
+ */
1215
+ function invalidBodyPair(message) {
1216
+ return invalidParams(message, {
1217
+ reason: 'invalid_body_pair',
1218
+ recovery: {
1219
+ 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.',
1220
+ },
1221
+ });
1222
+ }
1223
+ /**
1224
+ * Resolve the two bodies of a two-body conjunction: require `body`, and reject one that
1225
+ * cannot be paired (the Sun or Earth) or a pair of the same body twice. Throws with the
1226
+ * `body_required` or `invalid_body_pair` contract reason.
1227
+ */
1228
+ function resolvePair(body, body2) {
1229
+ if (!body)
1230
+ throw bodyRequired('conjunction');
1231
+ if (!isPairBody(body)) {
1232
+ throw invalidBodyPair(`A two-body conjunction pairs the Moon and the planets; body "${body}" is not one of them.`);
1233
+ }
1234
+ if (body === body2) {
1235
+ throw invalidBodyPair(`body and body2 are both "${body}"; a conjunction needs two different bodies.`);
1236
+ }
1237
+ return [body, body2];
1238
+ }
963
1239
  // --- Init / accessor pattern ------------------------------------------------
964
1240
  let _service;
965
1241
  /** Initialize the ephemeris service. Pure compute — no config or storage needed. */