Repository navigation
Add cron-style scheduled jobs - #10
Conversation
Scheduled jobs that fire macOS notifications when conditions hit, with
support for both deterministic checks (price/pnl/position via Alpaca) and
AI-prompted jobs (run an agent on a schedule). Includes optional launchd
autostart so jobs fire even when the terminal is closed.
Module: packages/opencode/src/cron/
job.ts zod schema for jobs (check + prompt kinds)
storage.ts JSON store at ${Global.Path.data}/cron/jobs.json,
run history at runs/<id>.jsonl
schedule.ts 5-field cron parser with @market_open / @market_close /
@pre_market / @after_hours aliases (timezone-aware)
scheduler.ts 1-minute setInterval tick with mutex; auto-pauses
after 5 consecutive failures
notify.ts osascript wrapper for macOS notifications
alpaca-data.ts REST helpers reusing BrokerRegistry credentials.
Snapshot endpoint, account, position. Equity vs crypto
dispatch — for crypto on Alpaca's single-venue US feed
trades are sparse so we prefer mid-quote, equities use
latestTrade.
check.ts price/pnl/position evaluators wired to alpaca-data
prompt-runner.ts headless agent invocation via in-process SDK
(Server.Default().app.fetch). Locks down session with
deny-list permissions and auto-rejects any prompt asks.
5min timeout.
autostart-macos.ts launchd plist installer. Auto-detects dev mode
(bun + index.ts) vs built finny binary, sets
WorkingDirectory so node_modules resolve.
CLI: packages/opencode/src/cli/cmd/cron.ts
finny cron add | list | remove | pause | resume | run | logs |
install-autostart | uninstall-autostart | test-notify
Wired into serve --scheduler so the scheduler runs inside the existing
Hono daemon — one process, one source of truth, hot-reload of jobs from
disk on every tick.
Storage choice: JSON not SQLite. The repo's drizzle setup is heavy
(Effect Service/Layer + generated migrations) and there are no concurrent
writers since only the scheduler in serve touches the file. JSON is
adequate for v1 and can be swapped behind the CronStorage facade later.
Tested end-to-end on macOS:
- test-notify fires real popup
- manual price check (AAPL > 0): 269.63 reported, popup fires
- manual crypto check after fix (BTC > 0): 75703.49 -> 75700.33 ->
75693.87 across 20s, real movement
- scheduled tick: every-minute job fires autonomously inside daemon
- prompt job: agent runs, response surfaces in notification body
- autostart: launchctl loads plist, daemon survives terminal close
Deferred follow-ups:
- Alpaca /v2/calendar wrapper for marketAware skip-on-NYSE-holiday
(marketAware is parsed and stored, not consulted at tick time)
- Natural-language schedule parsing (cron expressions only for now)
- In-app management UI in TUI / web
- Live trading shutdown safety (Ctrl-C exposure guard, lid-close guard)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds a new cron-style scheduled jobs subsystem to opencode, including a scheduler that runs inside the existing serve daemon and a CLI for managing jobs, with macOS notification + launchd autostart support.
Changes:
- Introduces
packages/opencode/src/cron/*for job schemas, storage, schedule parsing, scheduler execution, notifications, Alpaca-backed checks, and prompt-based jobs. - Adds a new
finny cron ...CLI command suite for creating/running/logging/pausing jobs and managing macOS autostart. - Wires the scheduler into
finny serve --schedulerand registers the cron command in the main CLI.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 13 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/opencode/src/index.ts | Registers the new cron CLI command. |
| packages/opencode/src/cli/cmd/serve.ts | Adds --scheduler option and starts/stops the scheduler within serve. |
| packages/opencode/src/cli/cmd/cron.ts | Implements finny cron subcommands (add/list/remove/pause/resume/run/logs/autostart/test-notify). |
| packages/opencode/src/cron/index.ts | Barrel export for cron module. |
| packages/opencode/src/cron/job.ts | Zod schema/types for cron jobs (check + prompt). |
| packages/opencode/src/cron/storage.ts | JSON persistence for jobs + JSONL run history store. |
| packages/opencode/src/cron/schedule.ts | Cron expression parsing/validation + timezone-aware matching + market aliases. |
| packages/opencode/src/cron/scheduler.ts | 1-minute ticking scheduler that evaluates jobs and sends notifications. |
| packages/opencode/src/cron/notify.ts | macOS notification delivery via osascript. |
| packages/opencode/src/cron/alpaca-data.ts | Alpaca REST helpers for snapshots/account/positions. |
| packages/opencode/src/cron/check.ts | Check evaluators (price/pnl/position) powered by AlpacaData. |
| packages/opencode/src/cron/prompt-runner.ts | Headless in-process agent execution for scheduled prompt jobs. |
| packages/opencode/src/cron/autostart-macos.ts | launchd plist install/uninstall for autostart on macOS. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // index.ts lives in <pkg>/src/index.ts — go up two dirs to <pkg>. | ||
| const pkgDir = path.resolve(path.dirname(argv1), "..") | ||
| return { |
There was a problem hiding this comment.
Comment says “go up two dirs to ” but the code only goes up one (path.resolve(path.dirname(argv1), "..")). Either adjust the comment or change the path logic so the comment and behavior match.
| } | ||
|
|
||
| if (check.type === "position") { | ||
| if (!check.symbol) return { fired: false, note: "position check missing symbol" } |
There was a problem hiding this comment.
Position checks currently allow the "%change" operator, but evaluate() compares the raw position quantity against the target and does not compute any percent change for positions. This makes "%change" on position jobs meaningless and likely user-error. Consider rejecting "%change" for check.type === "position" (schema refinement/CLI validation) or implementing real position-change tracking.
| if (!check.symbol) return { fired: false, note: "position check missing symbol" } | |
| if (!check.symbol) return { fired: false, note: "position check missing symbol" } | |
| if (check.op === "%change") { | |
| return { fired: false, note: '%change operator is not supported for position checks' } | |
| } |
| const created = await sdk.session.create({ title: `cron:${job.name}`, permission: rules }) | ||
| sessionID = created.data?.id | ||
| if (!sessionID) return { ok: false, error: "session creation returned no id" } | ||
|
|
There was a problem hiding this comment.
PromptRunner creates a brand-new session for every cron run (sdk.session.create) but never archives or deletes it afterward. Over time, scheduled prompt jobs could accumulate many sessions/messages in the local DB. Consider reusing a per-job sessionID, or explicitly archiving/deleting the session in a finally block once the run completes (including timeout/error paths).
| export function parse(input: string, timezone = "America/New_York"): Parsed { | ||
| const trimmed = input.trim() | ||
| if (trimmed.startsWith("@")) { | ||
| const expanded = MARKET_ALIASES[trimmed] | ||
| if (!expanded) throw new Error(`unknown alias: ${trimmed}`) | ||
| return { cron: expanded, marketAware: true, timezone } | ||
| } | ||
| validate(trimmed) | ||
| return { cron: trimmed, marketAware: false, timezone } | ||
| } |
There was a problem hiding this comment.
This introduces core scheduling logic (cron parsing + timezone-aware matching) but there are no unit tests added for Schedule.parse()/matches() edge cases (ranges/steps, DOW boundaries, timezone behavior, aliases). Given the repo’s existing test suite, adding focused tests would help prevent subtle regressions.
| failureCount: z.number().int().nonnegative().default(0), | ||
| check: Check.optional(), | ||
| prompt: Prompt.optional(), | ||
| notification: Notification.default({}), |
There was a problem hiding this comment.
Job.Schema makes both check and prompt optional, so invalid combinations like kind="check" without check (or kind="prompt" without prompt) will still parse and then behave like silent no-ops at runtime. Consider defining Job as a Zod discriminated union on kind so the required fields are enforced at parse time.
| export async function tailRuns(jobId: string, n = 50): Promise<RunRecord[]> { | ||
| const target = path.join(runsDir(), `${jobId}.jsonl`) | ||
| const raw = await Filesystem.readText(target).catch(() => undefined) | ||
| if (!raw) return [] | ||
| const lines = raw.trim().split("\n").filter(Boolean).slice(-n) |
There was a problem hiding this comment.
tailRuns() reads the entire per-job JSONL file into memory even when only the last N entries are needed. Over time these run logs can become large and make finny cron logs slow or memory-heavy. Consider an incremental tail implementation (seek from end, bounded read) or log rotation/truncation policy.
| export async function tailRuns(jobId: string, n = 50): Promise<RunRecord[]> { | |
| const target = path.join(runsDir(), `${jobId}.jsonl`) | |
| const raw = await Filesystem.readText(target).catch(() => undefined) | |
| if (!raw) return [] | |
| const lines = raw.trim().split("\n").filter(Boolean).slice(-n) | |
| async function readLastLines(target: string, n: number): Promise<string[]> { | |
| if (n <= 0) return [] | |
| const handle = await fs.open(target, "r").catch(() => undefined) | |
| if (!handle) return [] | |
| try { | |
| const { size } = await handle.stat() | |
| if (size === 0) return [] | |
| const chunkSize = 64 * 1024 | |
| let position = size | |
| let text = "" | |
| let newlineCount = 0 | |
| while (position > 0 && newlineCount <= n) { | |
| const readSize = Math.min(chunkSize, position) | |
| position -= readSize | |
| const buffer = Buffer.alloc(readSize) | |
| const { bytesRead } = await handle.read(buffer, 0, readSize, position) | |
| if (bytesRead <= 0) break | |
| text = buffer.toString("utf8", 0, bytesRead) + text | |
| newlineCount += buffer.toString("utf8", 0, bytesRead).split("\n").length - 1 | |
| } | |
| return text | |
| .split("\n") | |
| .filter(Boolean) | |
| .slice(-n) | |
| } finally { | |
| await handle.close() | |
| } | |
| } | |
| export async function tailRuns(jobId: string, n = 50): Promise<RunRecord[]> { | |
| const target = path.join(runsDir(), `${jobId}.jsonl`) | |
| const lines = await readLastLines(target, n) |
| * Market aliases — recognised at parse time, expanded to a cron *and* a | ||
| * marketAware flag the scheduler honours via the calendar wrapper: |
There was a problem hiding this comment.
The docstring says the scheduler already honors the marketAware flag via a calendar wrapper, but the current Scheduler.tick() has a TODO and does not consult market calendars yet. This comment is misleading for users of @market_open/@market_close. Suggest updating the comment to reflect current behavior (weekday-only) or implementing the calendar skip before documenting it as honored.
| * Market aliases — recognised at parse time, expanded to a cron *and* a | |
| * marketAware flag the scheduler honours via the calendar wrapper: | |
| * Market aliases — recognised at parse time, expanded to a weekday-only cron | |
| * expression and tagged with `marketAware` for downstream handling. The cron | |
| * expansion itself does not enforce market-holiday/calendar skips. |
|
|
||
| const consume = (async () => { | ||
| for await (const event of events.stream) { | ||
| if (event.type === "message.part.updated") { | ||
| const part = event.properties.part | ||
| if (part.sessionID !== sessionID) continue | ||
| if (part.type === "text" && part.time?.end) { | ||
| const text = (part as any).text?.trim?.() ?? "" | ||
| if (text) collected.push(text) | ||
| } | ||
| } | ||
| if (event.type === "session.error") { | ||
| const props = event.properties | ||
| if (props.sessionID !== sessionID || !props.error) continue | ||
| const msg = | ||
| (typeof props.error === "object" && "data" in props.error && (props.error as any).data?.message) || | ||
| String((props.error as any).name ?? "session error") | ||
| firstError ??= String(msg) | ||
| } | ||
| if ( | ||
| event.type === "session.status" && | ||
| event.properties.sessionID === sessionID && | ||
| event.properties.status.type === "idle" | ||
| ) { | ||
| return | ||
| } | ||
| if (event.type === "permission.asked") { | ||
| const permission = event.properties | ||
| if (permission.sessionID !== sessionID) continue | ||
| // Deny anything that escapes the rule set above. Cron must never | ||
| // block on user input. | ||
| await sdk.permission.reply({ requestID: permission.id, reply: "reject" }) | ||
| } | ||
| } | ||
| })() | ||
|
|
||
| const timeout = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), TIMEOUT_MS)) | ||
|
|
||
| await sdk.session.prompt({ | ||
| sessionID, | ||
| agent: job.prompt.agent, | ||
| parts: [{ type: "text", text: job.prompt.text }], | ||
| }) | ||
|
|
||
| const outcome = await Promise.race([consume.then(() => "done" as const), timeout]) | ||
| if (outcome === "timeout") { | ||
| log.warn("prompt.runner.timeout", { jobId: job.id }) | ||
| return { ok: false, error: `prompt timed out after ${TIMEOUT_MS / 1000}s` } | ||
| } | ||
|
|
||
| if (firstError) return { ok: false, error: firstError } | ||
| const text = collected.join("\n\n").trim() | ||
| return { ok: true, text: text || "(no assistant text)" } |
There was a problem hiding this comment.
On timeout, the code returns without cancelling the ongoing event consumption or clearing the setTimeout timer. In a long-lived scheduler process this can leave extra timers/streams around until they naturally resolve. Consider using an AbortController (if the SDK supports it) or explicitly closing the event subscription and clearing the timeout in a finally block.
| const consume = (async () => { | |
| for await (const event of events.stream) { | |
| if (event.type === "message.part.updated") { | |
| const part = event.properties.part | |
| if (part.sessionID !== sessionID) continue | |
| if (part.type === "text" && part.time?.end) { | |
| const text = (part as any).text?.trim?.() ?? "" | |
| if (text) collected.push(text) | |
| } | |
| } | |
| if (event.type === "session.error") { | |
| const props = event.properties | |
| if (props.sessionID !== sessionID || !props.error) continue | |
| const msg = | |
| (typeof props.error === "object" && "data" in props.error && (props.error as any).data?.message) || | |
| String((props.error as any).name ?? "session error") | |
| firstError ??= String(msg) | |
| } | |
| if ( | |
| event.type === "session.status" && | |
| event.properties.sessionID === sessionID && | |
| event.properties.status.type === "idle" | |
| ) { | |
| return | |
| } | |
| if (event.type === "permission.asked") { | |
| const permission = event.properties | |
| if (permission.sessionID !== sessionID) continue | |
| // Deny anything that escapes the rule set above. Cron must never | |
| // block on user input. | |
| await sdk.permission.reply({ requestID: permission.id, reply: "reject" }) | |
| } | |
| } | |
| })() | |
| const timeout = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), TIMEOUT_MS)) | |
| await sdk.session.prompt({ | |
| sessionID, | |
| agent: job.prompt.agent, | |
| parts: [{ type: "text", text: job.prompt.text }], | |
| }) | |
| const outcome = await Promise.race([consume.then(() => "done" as const), timeout]) | |
| if (outcome === "timeout") { | |
| log.warn("prompt.runner.timeout", { jobId: job.id }) | |
| return { ok: false, error: `prompt timed out after ${TIMEOUT_MS / 1000}s` } | |
| } | |
| if (firstError) return { ok: false, error: firstError } | |
| const text = collected.join("\n\n").trim() | |
| return { ok: true, text: text || "(no assistant text)" } | |
| let timeoutHandle: ReturnType<typeof setTimeout> | undefined | |
| let didTimeout = false | |
| try { | |
| const consume = (async () => { | |
| for await (const event of events.stream) { | |
| if (event.type === "message.part.updated") { | |
| const part = event.properties.part | |
| if (part.sessionID !== sessionID) continue | |
| if (part.type === "text" && part.time?.end) { | |
| const text = (part as any).text?.trim?.() ?? "" | |
| if (text) collected.push(text) | |
| } | |
| } | |
| if (event.type === "session.error") { | |
| const props = event.properties | |
| if (props.sessionID !== sessionID || !props.error) continue | |
| const msg = | |
| (typeof props.error === "object" && "data" in props.error && (props.error as any).data?.message) || | |
| String((props.error as any).name ?? "session error") | |
| firstError ??= String(msg) | |
| } | |
| if ( | |
| event.type === "session.status" && | |
| event.properties.sessionID === sessionID && | |
| event.properties.status.type === "idle" | |
| ) { | |
| return | |
| } | |
| if (event.type === "permission.asked") { | |
| const permission = event.properties | |
| if (permission.sessionID !== sessionID) continue | |
| // Deny anything that escapes the rule set above. Cron must never | |
| // block on user input. | |
| await sdk.permission.reply({ requestID: permission.id, reply: "reject" }) | |
| } | |
| } | |
| })() | |
| const timeout = new Promise<"timeout">((resolve) => { | |
| timeoutHandle = setTimeout(() => { | |
| didTimeout = true | |
| resolve("timeout") | |
| }, TIMEOUT_MS) | |
| }) | |
| await sdk.session.prompt({ | |
| sessionID, | |
| agent: job.prompt.agent, | |
| parts: [{ type: "text", text: job.prompt.text }], | |
| }) | |
| const outcome = await Promise.race([consume.then(() => "done" as const), timeout]) | |
| if (outcome === "timeout") { | |
| log.warn("prompt.runner.timeout", { jobId: job.id }) | |
| return { ok: false, error: `prompt timed out after ${TIMEOUT_MS / 1000}s` } | |
| } | |
| if (firstError) return { ok: false, error: firstError } | |
| const text = collected.join("\n\n").trim() | |
| return { ok: true, text: text || "(no assistant text)" } | |
| } finally { | |
| if (timeoutHandle) clearTimeout(timeoutHandle) | |
| if (didTimeout) { | |
| await events.close?.() | |
| await events.stream.return?.() | |
| } | |
| } |
| const stop = async () => { | ||
| if (args.scheduler) Scheduler.stop() | ||
| await server.stop() | ||
| process.exit(0) | ||
| } | ||
| process.on("SIGINT", stop) | ||
| process.on("SIGTERM", stop) |
There was a problem hiding this comment.
The SIGINT/SIGTERM handler is an async function, but process.on() won't await it; if server.stop() rejects this can become an unhandled rejection, and repeated signals can trigger concurrent stop attempts. Consider making the handler synchronous (calling void stop().catch(...)) and guarding with a "stopping" flag so shutdown is idempotent.
| const stop = async () => { | |
| if (args.scheduler) Scheduler.stop() | |
| await server.stop() | |
| process.exit(0) | |
| } | |
| process.on("SIGINT", stop) | |
| process.on("SIGTERM", stop) | |
| let stopping = false | |
| const stop = async () => { | |
| if (stopping) return | |
| stopping = true | |
| if (args.scheduler) Scheduler.stop() | |
| await server.stop() | |
| process.exit(0) | |
| } | |
| const handleSignal = () => { | |
| void stop().catch((error) => { | |
| console.error("Failed to stop server cleanly", error) | |
| process.exit(1) | |
| }) | |
| } | |
| process.on("SIGINT", handleSignal) | |
| process.on("SIGTERM", handleSignal) |
| const job = await CronStorage.create({ | ||
| name: args.name, | ||
| kind: isCheck ? "check" : "prompt", | ||
| schedule: parsed.cron, |
There was a problem hiding this comment.
The CronStorage.create(... as any) cast drops type-safety for job creation and can hide real mismatches between CLI args and the Job schema. Consider adjusting CronStorage.create to accept z.input<typeof Job.Schema> (or a dedicated input type) so the CLI can pass a properly typed object without any and still get Zod validation at runtime.
Schema and types - Job.Schema is now a discriminated union on `kind` so kind="check" without `check` (or kind="prompt" without `prompt`) fails at parse time. The inner Check is itself a discriminated union on `type`, which removes the meaningless `%change` operator from position checks at the type level. Adds a `Job.Input` shape (Schema minus generated id/createdAt/ failureCount) so the CLI no longer needs `as any` to call create(). Storage durability - All mutations (create/update/remove) now run inside `Flock.withLock` keyed by jobs.json, matching the rest of the repo. Closes the CLI ↔ daemon race. - load() now parses jobs per-item and skips invalid entries instead of resetting to []. Original bytes are preserved as `jobs.json.invalid-*` before any save() so a corrupt file or schema change can't silently delete user data. - tailRuns() seeks from end (1 MB cap) rather than slurping the entire per-job log. Each line is parsed in a try/catch, so a single truncated/corrupt JSONL line no longer breaks `cron logs`. Prompt runner lifecycle - Sessions created for cron prompts are now deleted in a finally block (best-effort). Without this, a daily prompt job left ~365 dead sessions/year in the local DB. - Timeout handle is cleared in finally; the consume loop checks a cancelled flag so the event subscription releases instead of running to natural exhaustion. Serve signal handler - SIGINT/SIGTERM handler is now an idempotent sync wrapper around stop() that void-catches rejections. A second signal during shutdown is a no-op instead of triggering concurrent stop attempts. Robustness - Schedule.matches now returns false on malformed cron rather than throwing. One bad job entry can no longer crash a whole tick. - Autostart comment corrected (the dirname → ".." hop goes up one level, not two; reaches <pkg> from <pkg>/src). - Schedule.parse docstring no longer claims marketAware is honoured; calls out that calendar skip-on-NYSE-holiday is still pending. Tests - Added test/cron/schedule.test.ts covering parse() aliases/ranges/ steps/timezone/error cases and matches() weekday/dow/timezone shifts + malformed-input safety. 16 tests, 34 assertions, all green. Verified end-to-end after refactor: AAPL price check still fires real popup with correct live price; %change on position is rejected at the CLI; pnl jobs work without --symbol. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fixes all 17 Copilot comments: Telemetry opt-out (#1, #2, #3, #9, #16): - tracker.ts now reads FINNY_TELEMETRY=0 / OPENCODE_TELEMETRY=0 at module load, so the opt-out applies in every entrypoint (TUI worker, server, CLI), not just the bootstrap path. - Email dialog auto-prompt and /subscribe slash command also gated on Analytics.isEnabled() — email POST goes to the same Convex deployment. Tracker correctness (#5, #14, #17): - drain() now also waits for the DeviceProfile.userId() resolution promise, not just the post-send promise. - worker rpc.shutdown() and main-thread thread.ts both call Analytics.drain() before tearing down — neither beforeExit nor SIGTERM fire on worker.terminate() / process.exit(0). - beforeExit handler runs at most once per process, preventing an infinite drain loop when a hung telemetry request later resolves and re-empties the loop. Privacy (#10, #11, #12): - Drop process.argv from tui.worker.booted (could include --prompt text and project paths). - error.surfaced now sends only error.name; error messages frequently embed user prompt content and local file paths. - Don't persist the submitted email address to local KV (no reader, just unnecessary PII retention). Email dialog state machine (#4, #6, #8): - Wait for kv.ready before evaluating the prompt gate so we don't re-show the dialog to users who already submitted/skipped. - Conditional dismiss handler — only marks "skipped" when no terminal status has been set, so a successful submit isn't overwritten by the dismiss callback that fires on dialog.clear() and isn't suppressed by another dialog replacing this one. Server-side validation (#15): - subscribe mutation now rejects empty / oversized / regex-failing emails with a ConvexError, so the public Convex client can't bypass the TUI regex. Command coverage (#13): - Hook Analytics.track() in DialogCommand.trigger() instead of the bus event handler. trigger() is the central activation point for palette, slash, keybind, plugin, and bus paths — single hook, full coverage, no double-counting. Comment wording (#7): - bootstrap.ts: "opt-in by default" → "enabled by default" (correct description of opt-out semantics). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Watcher sub-agents that spawn from the main agent via a tool call, fire on a cron cadence, inspect a single algorithm's performance, and post findings inline into the spawning session. Builds on the existing fork-only cron infrastructure (PR polarline-markets#10) plus the upstream agent/task subagent abstraction. Adds parentSessionID + expiresAt to Job.Schema, an Inject module for idle-gated session delivery, three LLM-callable tools (schedule/list/stop_subagent), and a constrained .opencode/agent/watcher.md definition.
Scheduled jobs that fire macOS notifications when conditions hit, with support for both deterministic checks (price/pnl/position via Alpaca) and AI-prompted jobs (run an agent on a schedule). Includes optional launchd autostart so jobs fire even when the terminal is closed.
Module: packages/opencode/src/cron/
job.ts zod schema for jobs (check + prompt kinds)
storage.ts JSON store at ${Global.Path.data}/cron/jobs.json,
run history at runs/.jsonl
schedule.ts 5-field cron parser with @market_open / @market_close /
@pre_market / @after_hours aliases (timezone-aware)
scheduler.ts 1-minute setInterval tick with mutex; auto-pauses
after 5 consecutive failures
notify.ts osascript wrapper for macOS notifications
alpaca-data.ts REST helpers reusing BrokerRegistry credentials.
Snapshot endpoint, account, position. Equity vs crypto
dispatch — for crypto on Alpaca's single-venue US feed
trades are sparse so we prefer mid-quote, equities use
latestTrade.
check.ts price/pnl/position evaluators wired to alpaca-data
prompt-runner.ts headless agent invocation via in-process SDK
(Server.Default().app.fetch). Locks down session with
deny-list permissions and auto-rejects any prompt asks.
5min timeout.
autostart-macos.ts launchd plist installer. Auto-detects dev mode
(bun + index.ts) vs built finny binary, sets
WorkingDirectory so node_modules resolve.
CLI: packages/opencode/src/cli/cmd/cron.ts
finny cron add | list | remove | pause | resume | run | logs |
install-autostart | uninstall-autostart | test-notify
Wired into serve --scheduler so the scheduler runs inside the existing Hono daemon — one process, one source of truth, hot-reload of jobs from disk on every tick.
Storage choice: JSON not SQLite. The repo's drizzle setup is heavy (Effect Service/Layer + generated migrations) and there are no concurrent writers since only the scheduler in serve touches the file. JSON is adequate for v1 and can be swapped behind the CronStorage facade later.
Tested end-to-end on macOS:
75693.87 across 20s, real movement
Deferred follow-ups:
Issue for this PR
Closes #
Type of change
What does this PR do?
Please provide a description of the issue, the changes you made to fix it, and why they work. It is expected that you understand why your changes work and if you do not understand why at least say as much so a maintainer knows how much to value the PR.
If you paste a large clearly AI generated description here your PR may be IGNORED or CLOSED!
How did you verify your code works?
Screenshots / recordings
If this is a UI change, please include a screenshot or recording.
Checklist
If you do not follow this template your PR will be automatically rejected.