← Public packages
@noah/hey-email
HEY.com email integration with Kody: search threads, read messages/attachments, create drafts, and send with explicit confirmation.
Files
import { kody, packageStorage } from 'kody:runtime'
import { refreshAccessToken, heyFetch } from './client.js'
/**
* HEY token keepalive (job entry, daily at 9 AM ET).
*
* Why this exists: HEY access and refresh tokens both live ~14 days, so
* refresh-on-401 alone cannot save the account — by the time the access
* token 401s, the refresh token has usually expired in the same window
* (that zeroed the Nov 5, 2026 Morning Brief and the LEGO Inside Tour
* watcher). Refreshing proactively every day exercises the refresh token
* long before it can idle out, so the pair never ages out. Runs entirely
* on Kody: no Muse tokens, no human in the loop.
*
* How it works (2026-11-05 redesign): the keepalive mints a fresh access
* token via refreshAccessToken() and verifies it by fetching /identity
* with that fresh token. Nothing is stored: the minted token is a sealed
* handle and package code cannot keep sealed tokens across runs, so the
* fresh token is used in-run only and the stored heyToken secret is left
* as a first-try fallback (it 401s once aged out and any caller mints a
* fresh one and retries). See src/client.js for the full reasoning.
*
* Success is silent (returns the refreshed identity). Failure sends one
* alert email via Kody's own mailer (not HEY — HEY auth is what's broken)
* and returns the failure instead of throwing, so the job run records it.
* Alerts are throttled to one per 7 days so a dead token doesn't spam.
*
* NOTE: this file must stay TypeScript (.ts). A .js job entry fails the
* publish typecheck with TS7016 ("Could not find a declaration file for
* module './src/keepalive'") — the checker resolves new entrypoints
* extensionless and only .ts files carry their own declarations.
*
* @returns The refreshed identity on success, or the failure with whether an alert was sent.
*
* @example
* import keepalive from 'kody:@noah/hey-email/keepalive'
* await keepalive()
*/
const ALERT_TO = ['hithere@hey.com']
const ALERT_KEY = 'keepalive:lastAlertAt'
const ALERT_MIN_GAP_MS = 7 * 24 * 60 * 60 * 1000
function esc(value: unknown): string {
return String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
export default async function keepalive(): Promise<{
status: string
at: string
identity?: { id: number; name: string }
error?: string
alertSent?: boolean
}> {
const at = new Date().toISOString()
try {
const fresh = await refreshAccessToken()
const data = await heyFetch('/identity', {
headers: { Authorization: `Bearer ${fresh}` },
})
const me = { id: data.id as number, name: data.name as string }
return { status: 'refreshed', at, identity: me }
} catch (e) {
const error = String((e as Error)?.message || e).slice(0, 300)
let alertSent = false
try {
const bucket = packageStorage()
const last = await bucket.get(ALERT_KEY)
const lastAt = last ? Date.parse(last) : 0
if (!lastAt || Number.isNaN(lastAt) || Date.now() - lastAt > ALERT_MIN_GAP_MS) {
const subject = '[Kody] HEY token keepalive failed — re-authentication needed'
const text = [
subject,
'',
'What happened:',
`- The scheduled HEY token refresh failed: ${error}`,
'- The saved HEY access and refresh tokens are expired or invalid.',
'',
'Impact:',
'- HEY searches are down: the Morning Brief, LEGO watchers, and anything else reading HEY will fail until this is fixed.',
'',
'How to fix it:',
'- Re-authenticate HEY (hey auth login) and sync the fresh tokens into the heyToken / heyRefreshToken Kody user secrets — or ask Muse to do the sync.',
'- The keepalive job retries daily and will go quiet once the tokens are fresh again.',
].join('\n')
await kody.emailSend({ to: ALERT_TO, subject, text, html: `<pre>${esc(text)}</pre>` })
await bucket.set(ALERT_KEY, at)
alertSent = true
}
} catch {
// The alert path must never mask the original failure.
}
return { status: 'failed', at, error, alertSent }
}
}