Exported functions in state/lib/freshbooks.ts. .md file to compare - side-by-side diff against freshbooks
freshbooks
description: "Triggers on prompt mention of 'freshbooks', 'invoice', 'billing', etc."
What it does for you
Connects your assistant to your FreshBooks invoices and bookkeeping.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 3/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/freshbooks/SKILL.md
present
state/lib/freshbooks.ts
present
state/bin/freshbooks/
not present
state/skills/freshbooks/AGENTS.md
present
how it's graded - what counts as a good run 4 criteria · 3 deterministic · 1 judge
Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.
how it runs - the shared frame every skill uses 4/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
This skill doesn't fix its own gaps yet.
state/log/evals.ndjson - FreshBooks surfaces are OpenUI Lang programs. Do not introduce a FreshBooksInvoicePreview React component or per-skill .openui file.
- Use a stable app_slug for every compose_inline call. freshbooks-invoices for the list view, freshbooks-invoice-<invoice_number> for single invoice detail. This updates the same Live App tile instead of creating duplicates.
- Never invent line item descriptions. If lines is empty, say so and suggest get-invoice <invoiceid> to retrieve them.
- sendInvoice and markPaid are irreversible - keep scope-only unless Robert explicitly approves.
what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- who makes it, who checks it
SKILL.md- the skill, written out in plain English
freshbooks
FreshBooks operations via direct API for all snappy-* skills.
Ported from kernel snappy-freshbooks in Phase 0.5. See state/lib/freshbooks.ts for the full API surface.
Steps
listClients()- seestate/lib/freshbooks.tsgetOrCreateClient()- seestate/lib/freshbooks.tslistInvoices()- seestate/lib/freshbooks.tsgetOpenDraftsForClient()- seestate/lib/freshbooks.tslistOpenDrafts()- seestate/lib/freshbooks.tsgetLastPaidInvoice()- seestate/lib/freshbooks.tsdraftCatchupInvoice()- seestate/lib/freshbooks.tscreateInvoice()- seestate/lib/freshbooks.tsupdateInvoice()- seestate/lib/freshbooks.tssendInvoice()- seestate/lib/freshbooks.tsmarkPaid()- seestate/lib/freshbooks.tslistTimeEntries()- seestate/lib/freshbooks.tscreateTimeEntry()- seestate/lib/freshbooks.tslistExpenses()- seestate/lib/freshbooks.tscreateExpense()- seestate/lib/freshbooks.tscomputeFreshbooksMetric()- seestate/lib/freshbooks.ts
Eval
Actor: the exported functions in state/lib/freshbooks.ts. Auditor: none wired yet - eval is manual (Robert review). File a state/log/pending-eval.ndjson row on each run.
Score convention:
| Outcome | Score |
|---|---|
| Pass on first try | 1.0 |
| Failed first, auto-fix applied, re-check passed | 0.5 |
| Still failing or unrecoverable | 0.0 |
Gotchas
via the Phase 0.5 driver. Only these rewrites were applied: already in state/lib/)
realpathSync(process.argv[1])CLI guard wrapped in try/catch
- See the kernel SKILL.md for the original long-form guidance if you need it
(read-only reference at the kernel path above).
Graduation
This skill is prose. Graduate by defining a deterministic auditor and flipping eval: auto.
Rubric
criteria:
- name: api_surface_completeness
kind: deterministic
check: "The `state/lib/freshbooks.ts` file exports all specified functions: `listClients`, `getOrCreateClient`, `listInvoices`, `getOpenDraftsForClient`, `listOpenDrafts`, `getLastPaidInvoice`, `draftCatchupInvoice`, `createInvoice`, `updateInvoice`, `sendInvoice`, `markPaid`, `listTimeEntries`, `createTimeEntry`, `listExpenses`, `createExpense`, and `computeFreshbooksMetric`."
- name: input_schema_adherence
kind: deterministic
check: "The skill definition's `inputs` section accurately reflects the types required by the specified functions (e.g., `listClients_input`, `getOrCreateClient_input`, etc.) from `state/lib/freshbooks.ts`."
- name: freshbooks_api_connectivity
kind: judge
check: "Executing a basic query (e.g., `listClients()`) via the skill successfully connects to and retrieves data from the FreshBooks API without errors, indicating correct API key configuration and network access."
- name: deterministic_eval_readiness
kind: deterministic
check: "The skill has a defined `state/log/pending-eval.ndjson` row on execution, indicating activity that can be manually reviewed for graduation to a 'deterministic' eval."AGENTS.md- what the AI loads when this skill comes up
freshbooks - loader
Per-turn rules for the freshbooks skill. Full reference: state/skills/freshbooks/SKILL.md. Do not skip these.
Auth State (verified 2026-05-16)
BROKEN - refresh token invalid. Live call to npx tsx state/lib/freshbooks.ts invoices returns:
FreshBooks token refresh failed (400): {"error":"invalid_grant","error_description":"The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."}
FRESHBOOKS_REFRESH_TOKEN in .env.cache is expired or revoked. FreshBooks rotates refresh tokens on every use - if a previous call failed mid-rotation the token is gone.
Re-auth requires browser. FreshBooks OAuth requires an interactive authorization flow. Steps:
- Go to https://my.freshbooks.com/#/developer and open your app (
snappy) - Hit "Test" on the OAuth flow or use the app's redirect URI to re-authorize
- Exchange the new authorization code for tokens and update
.env.cache:
FRESHBOOKS_REFRESH_TOKEN=<new_refresh_token>
- Run
npx tsx state/lib/freshbooks.ts invoicesto verify.
No CLI subcommand exists in state/lib/freshbooks.ts for the initial authorization step - only token refresh is automated. Until re-authed, all FreshBooks operations will fail with invalid_grant.
BATCH RULE
Run all FreshBooks CLI calls in a single Bash sequence. Do NOT call them one by one. Collect all data first, then call compose_inline once with real values substituted in.
Invoice List Rendering (MANDATORY for "show invoices" / "outstanding invoices" / "what do I owe")
Steps:
- Fetch all invoices in one call:
npx tsx state/lib/freshbooks.ts invoices
Parse the JSON. Split into: outstanding (v3_status != "paid") and recently paid (last 3 by date_paid).
- Compose via
compose_inlinewith a stable slug:
compose_inline(app_slug="freshbooks-invoices", lang_body="""
root = Card([
CardHeader("FreshBooks - Invoices"),
Stack([
Callout("warning", "Outstanding", [
Table(
["Invoice #", "Client", "Amount", "Due Date", "Status"],
[
["0000058", "Orbiter Inc.", "$3,000.00", "May 14, 2026", "Draft"],
...one row per outstanding invoice, or TextContent("No outstanding invoices") if none...
]
)
]),
Callout("success", "Recently Paid", [
Table(
["Invoice #", "Client", "Amount", "Paid"],
[
["0000057", "Total", "$2,400.00", "May 8, 2026"],
...last 3 paid...
]
)
]),
]),
FollowUpBlock([
SnappyFollowUpItem("show invoice details and line items for 0000058", "View Line Items"),
SnappyFollowUpItem("draft a new invoice for Orbiter Inc.", "Draft Invoice"),
SnappyFollowUpItem("show overdue invoices only", "Overdue Only"),
])
])
""")
- Substitute real data from the CLI output. Never invent amounts, dates, or client names.
- Use
Callout(..., "warning")for outstanding/unpaid,Callout(..., "success")for paid. - If there are no outstanding invoices, render
TextContent("No outstanding invoices")inside the Callout body instead of an empty Table. - Always include the FollowUpBlock with the most recent invoice number filled in.
Single Invoice with Line Items (MANDATORY for "show invoice #X" / "invoice line items" / "view invoice details")
Steps:
- Fetch the single invoice with line items. You need the
invoiceid(numeric) from the list, NOT theinvoice_numberstring (e.g. "0000058"). Get it fromnpx tsx state/lib/freshbooks.ts invoices, find the row, takeinvoiceid.
Then fetch with line items:
npx tsx state/lib/freshbooks.ts get-invoice <invoiceid>
The lines array in the response contains each line item. Each line has:
name- the description of the workqty- quantity (usually "1")unit_cost.amount- per-unit priceamount.amount- line total
- Compose via
compose_inline:
compose_inline(app_slug="freshbooks-invoice-0000058", lang_body="""
root = Card([
CardHeader("Invoice #0000058 - Orbiter Inc."),
Stack([
Callout("info", "Invoice Details", [
Stack([
TextContent("Issued: May 9, 2026 Due: May 14, 2026 Status: Draft"),
Table(
["Description", "Qty", "Unit Price", "Total"],
[
["Copilot-baseline polish pass (waves 2-6) - PersonCard, OutcomesItem...", "1", "$1,200.00", "$1,200.00"],
["React performance refactor - bundle size, memo, lazy load", "1", "$900.00", "$900.00"],
...one row per line item...
]
),
TextContent("Total: $3,000.00 Outstanding: $3,000.00"),
], "column")
]),
Callout("neutral", "Notes", [TextContent("Catchup window: ...")]),
]),
FollowUpBlock([
SnappyFollowUpItem("show all invoices for Orbiter Inc.", "Client History"),
SnappyFollowUpItem("show all invoices", "All Invoices"),
SnappyFollowUpItem("draft a new invoice for Orbiter Inc.", "Draft Next"),
])
])
""")
- Use the invoice_number (e.g. "0000058") in the CardHeader and app_slug.
- Truncate long line item names to ~70 chars with "..." if needed for table fit.
- Show notes in a separate Callout only if
notesis non-empty. - If
linesis empty, renderTextContent("Line items not available for this invoice.")instead of the Table.
Critical Rules
- FreshBooks surfaces are OpenUI Lang programs. Do not introduce a
FreshBooksInvoicePreviewReact component or per-skill.openuifile. - Use a stable
app_slugfor everycompose_inlinecall.freshbooks-invoicesfor the list view,freshbooks-invoice-<invoice_number>for single invoice detail. This updates the same Live App tile instead of creating duplicates. - Never invent line item descriptions. If
linesis empty, say so and suggestget-invoice <invoiceid>to retrieve them. sendInvoiceandmarkPaidare irreversible - keep scope-only unless Robert explicitly approves.
Commands
| cli | npx tsx state/lib/freshbooks.ts <subcommand> | | subcommands | clients, invoices, get-invoice <invoiceid>, time-entries, expenses, create-invoice, update-invoice, mark-paid, log-time, log-expense | | key note | get-invoice <invoiceid> returns lines[] with full line items; invoices list does NOT include lines | | invoke | import { listClients, listInvoices, getInvoice, getOpenDraftsForClient, listOpenDrafts, getLastPaidInvoice, listTimeEntries, listExpenses, getOrCreateClient, draftCatchupInvoice, createInvoice, updateInvoice, markPaid, createTimeEntry, createExpense } from "state/lib/freshbooks.ts" | | verify | listOpenDrafts() before any createInvoice to avoid duplicate drafts | | eval log | state/log/pending-eval.ndjson (manual eval - skill: "freshbooks") |
Known Pitfalls
invoiceid(numeric, e.g.1688285) vsinvoice_number(string, e.g."0000058") -get-invoicetakes the numeric id, not the human-readable number. Get it from theinvoiceslist output.get-invoiceusesinclude[]=linesquery param - this is built intogetInvoice()and the CLI. Do not uselistInvoices()and expect lines; callgetInvoice(invoiceid)instead.sendInvoiceandmarkPaidare irreversible side-effects - keep behind scope-only default.getOrCreateClientis idempotent but checklistClientsif naming is fuzzy - duplicates are painful to clean up.draftCatchupInvoiceis the convenience fn for "client owes us catchup time" - prefer it over hand-stitchingcreateInvoice.
Self-Test
An agent reading this should correctly:
- [ ] Fetch
invoiceslist first to get theinvoiceidnumeric field - [ ] Call
get-invoice <invoiceid>(notinvoices) to get line items - [ ] Use
Table(["Description","Qty","Unit Price","Total"], [...])for line item rendering - [ ] Use stable
app_slugin everycompose_inlinecall - [ ] Check
listOpenDraftsbefore drafting a new invoice
Found a gap? Edit this file. <!-- footer-injection-point -->
api.ts- the code it can call
#!/usr/bin/env npx tsx
/**
* snappy-freshbooks/api.ts -- FreshBooks operations via direct API for all snappy-* skills.
*
* Direct FreshBooks API calls -- no Xano middleware.
* OAuth2 with refresh token. Access token cached in memory.
*
* Usage:
* npx tsx api.ts clients # list clients
* npx tsx api.ts invoices # list invoices
* npx tsx api.ts create-invoice '{"client_id":1,"lines":[...]}'
* npx tsx api.ts send-invoice '{"invoice_id":123}'
* npx tsx api.ts mark-paid '{"invoice_id":123,"payment_date":"2026-04-08"}'
*
* Or import as module:
* import { listClients, createInvoice, sendInvoice } from "./freshbooks.ts";
*/
import * as fs from "node:fs";
import * as path from "node:path";
import { env } from "./env.ts";
import { realpathSync } from "fs";
const FB_API = "https://api.freshbooks.com";
const ENV_PATH = `${process.env.HOME}/.claude/skills/snappy-settings/.env.cache`;
const STATE_DIR = `${process.env.HOME}/.claude/state`;
const TOKEN_CACHE_PATH = path.join(STATE_DIR, "freshbooks-token.json");
const LOCK_PATH = path.join(STATE_DIR, "freshbooks-token.lock");
let _refreshInFlight: Promise<string> | null = null;
function accountId(): string {
return env("FRESHBOOKS_ACCOUNT_ID");
}
type TokenCache = { access_token: string; expires_at: number };
function readTokenCache(): TokenCache | null {
try {
const raw = fs.readFileSync(TOKEN_CACHE_PATH, "utf8");
const data = JSON.parse(raw) as TokenCache;
if (data.access_token && Date.now() < data.expires_at) return data;
} catch { /* missing or stale */ }
return null;
}
function writeTokenCache(cache: TokenCache): void {
fs.mkdirSync(STATE_DIR, { recursive: true });
fs.writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(cache), { mode: 0o600 });
}
/**
* Cross-process exclusive lock via O_EXCL lockfile. Retries with backoff.
* Stale locks (>30s) are forcibly removed — a crashed process should not wedge
* every future FreshBooks call.
*/
async function acquireLock(): Promise<() => void> {
fs.mkdirSync(STATE_DIR, { recursive: true });
const deadline = Date.now() + 15000;
while (true) {
try {
const fd = fs.openSync(LOCK_PATH, "wx");
fs.writeSync(fd, String(process.pid));
fs.closeSync(fd);
return () => { try { fs.unlinkSync(LOCK_PATH); } catch { /* ignore */ } };
} catch (e: any) {
if (e.code !== "EEXIST") throw e;
try {
const st = fs.statSync(LOCK_PATH);
if (Date.now() - st.mtimeMs > 30000) {
fs.unlinkSync(LOCK_PATH);
continue;
}
} catch { /* disappeared, retry */ }
if (Date.now() > deadline) {
throw new Error(`FreshBooks refresh lock timeout (held at ${LOCK_PATH}).`);
}
await new Promise((r) => setTimeout(r, 100 + Math.random() * 200));
}
}
}
/**
* FreshBooks rotates refresh tokens on every use. The old one is invalidated
* atomically by the server. We must (a) serialize refreshes across processes
* so two callers don't both burn the same token, and (b) re-read .env.cache
* *inside* the lock in case another process just rotated it.
*/
function readCurrentRefreshToken(): string {
const raw = fs.readFileSync(ENV_PATH, "utf8");
const line = raw.split("\n").find((l) => l.startsWith("FRESHBOOKS_REFRESH_TOKEN="));
if (!line) throw new Error("FRESHBOOKS_REFRESH_TOKEN missing from .env.cache");
return line.slice("FRESHBOOKS_REFRESH_TOKEN=".length).trim();
}
function persistRefreshToken(newRefreshToken: string): void {
const raw = fs.readFileSync(ENV_PATH, "utf8");
const lines = raw.split("\n");
let found = false;
const updated = lines.map((line) => {
if (line.startsWith("FRESHBOOKS_REFRESH_TOKEN=")) {
found = true;
return `FRESHBOOKS_REFRESH_TOKEN=${newRefreshToken}`;
}
return line;
});
if (!found) updated.push(`FRESHBOOKS_REFRESH_TOKEN=${newRefreshToken}`);
fs.writeFileSync(ENV_PATH, updated.join("\n"), { mode: 0o600 });
}
async function refreshAccessToken(): Promise<string> {
const cached = readTokenCache();
if (cached) return cached.access_token;
if (_refreshInFlight) return _refreshInFlight;
_refreshInFlight = (async () => {
try {
const release = await acquireLock();
try {
const recheck = readTokenCache();
if (recheck) return recheck.access_token;
const refreshToken = readCurrentRefreshToken();
const res = await fetch(`${FB_API}/auth/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "refresh_token",
client_id: env("FRESHBOOKS_CLIENT_ID"),
client_secret: env("FRESHBOOKS_CLIENT_SECRET"),
refresh_token: refreshToken,
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(`FreshBooks token refresh failed (${res.status}): ${JSON.stringify(data)}`);
}
const expires_at = Date.now() + (data.expires_in - 60) * 1000;
writeTokenCache({ access_token: data.access_token, expires_at });
if (data.refresh_token && data.refresh_token !== refreshToken) {
persistRefreshToken(data.refresh_token);
}
return data.access_token as string;
} finally {
release();
}
} finally {
_refreshInFlight = null;
}
})();
return _refreshInFlight;
}
async function fb(method: string, path: string, body?: Record<string, unknown>) {
const token = await refreshAccessToken();
const res = await fetch(`${FB_API}${path}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"Api-Version": "alpha",
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json();
if (!res.ok) {
throw new Error(`FreshBooks ${method} ${path} failed (${res.status}): ${JSON.stringify(data)}`);
}
return data;
}
function acct(suffix: string): string {
return `/accounting/account/${accountId()}${suffix}`;
}
// --- Public API ---
export async function listClients() {
const data = await fb("GET", acct("/users/clients"));
return data.response?.result?.clients ?? data;
}
export async function getOrCreateClient(input: { name: string; email?: string; organization?: string }) {
// Search for existing client by organization or name
const searchTerm = input.organization || input.name;
const existing = await fb("GET", acct(`/users/clients?search[organization_like]=${encodeURIComponent(searchTerm)}`));
const clients = existing.response?.result?.clients ?? [];
if (clients.length > 0) return clients[0];
// Create new client
const data = await fb("POST", acct("/users/clients"), {
client: {
fname: input.name.split(" ")[0] || input.name,
lname: input.name.split(" ").slice(1).join(" ") || "",
email: input.email || "",
organization: input.organization || input.name,
},
});
return data.response?.result?.client ?? data;
}
export async function listInvoices() {
const data = await fb("GET", acct("/invoices/invoices"));
return data.response?.result?.invoices ?? data;
}
/**
* Return every OPEN (non-paid) invoice for a client created since a given date.
* Used by catchup recipes to warn "you already drafted something in this window"
* so we don't double-bill.
*/
export async function getOpenDraftsForClient(client_id: number, since_date: string) {
const invoices = await listInvoices();
return (invoices as any[])
.filter((i) =>
i.customerid === client_id &&
i.v3_status !== "paid" &&
(i.create_date || "") >= since_date,
)
.map((i) => ({
invoice_number: i.invoice_number,
invoiceid: i.invoiceid,
create_date: i.create_date,
v3_status: i.v3_status,
amount: i.amount?.amount,
description: i.description,
review_url: `https://my.freshbooks.com/#/invoices/${i.invoiceid}`,
}));
}
/**
* Return every OPEN (non-paid) invoice across ALL clients, optionally since
* a given date. Used by morning-brief / catchup / ops status to show "what's
* currently in flight on the books" in one call.
*/
export async function listOpenDrafts(since_date?: string) {
const invoices = await listInvoices();
return (invoices as any[])
.filter((i) =>
i.v3_status !== "paid" &&
(!since_date || (i.create_date || "") >= since_date),
)
.map((i) => ({
invoice_number: i.invoice_number,
invoiceid: i.invoiceid,
customerid: i.customerid,
organization: i.organization,
create_date: i.create_date,
v3_status: i.v3_status,
amount: i.amount?.amount,
description: i.description,
review_url: `https://my.freshbooks.com/#/invoices/${i.invoiceid}`,
}))
.sort((a, b) => (b.create_date || "").localeCompare(a.create_date || ""));
}
/**
* Return the most recent PAID invoice for a given FreshBooks client id.
* Used as the anchor for catchup recipes — "bill everything since this date".
* Returns null if the client has never had a paid invoice.
*/
export async function getLastPaidInvoice(client_id: number) {
const invoices = await listInvoices();
const paid = (invoices as any[])
.filter((i) => i.customerid === client_id && i.v3_status === "paid")
.sort((a, b) => (b.date_paid || b.create_date).localeCompare(a.date_paid || a.create_date));
return paid[0] ?? null;
}
/**
* Thin wrapper over createInvoice used by per-client catchup recipes.
* Enforces non-empty lines, non-zero total, and stamps a notes line with the
* evidence window so the draft carries provenance into the FreshBooks UI.
*/
export async function draftCatchupInvoice(input: {
client_id: number;
since_date: string; // ISO YYYY-MM-DD, inclusive
window_end?: string; // ISO, defaults to today
lines: Array<{ name: string; amount: number; quantity?: number }>;
notes?: string;
due_offset_days?: number;
}) {
if (!input.lines.length) throw new Error("draftCatchupInvoice: lines is empty");
const total = input.lines.reduce((s, l) => s + l.amount * (l.quantity ?? 1), 0);
if (total <= 0) throw new Error("draftCatchupInvoice: line total must be > 0");
const end = input.window_end || new Date().toISOString().slice(0, 10);
const stamp = `Catchup window: ${input.since_date} → ${end}`;
const notes = input.notes ? `${input.notes}\n\n${stamp}` : stamp;
return createInvoice({
client_id: input.client_id,
lines: input.lines,
due_offset_days: input.due_offset_days ?? 5,
notes,
});
}
/**
* Create a DRAFT invoice. Never auto-sends.
*
* Policy: this skill only creates and updates drafts. A human sends invoices
* from the FreshBooks UI after reviewing the draft. There is intentionally no
* `sendInvoice` function — see the refusing stub below.
*/
export async function createInvoice(input: {
client_id: number;
lines: Array<{ name: string; amount: number; quantity?: number }>;
due_offset_days?: number;
notes?: string;
}) {
const data = await fb("POST", acct("/invoices/invoices"), {
invoice: {
customerid: input.client_id,
create_date: new Date().toISOString().slice(0, 10),
due_offset_days: input.due_offset_days ?? 30,
lines: input.lines.map((l) => ({
name: l.name,
unit_cost: { amount: String(l.amount), code: "USD" },
qty: l.quantity ?? 1,
type: 0,
})),
notes: input.notes || "",
status: 1, // draft — NEVER change
},
});
return data.response?.result?.invoice ?? data;
}
/**
* Update an existing DRAFT invoice. Refuses to touch non-draft invoices and
* strips any `action_*` or `status` keys the caller may try to pass through.
*/
export async function updateInvoice(input: {
invoice_id: number;
lines?: Array<{ name: string; amount: number; quantity?: number }>;
notes?: string;
due_offset_days?: number;
}) {
const current = await fb("GET", acct(`/invoices/invoices/${input.invoice_id}`));
const invoice = current.response?.result?.invoice;
if (!invoice) throw new Error(`Invoice ${input.invoice_id} not found`);
// FreshBooks v3Status: "draft" | "sent" | "viewed" | "paid" | ...
if (invoice.v3_status && invoice.v3_status !== "draft") {
throw new Error(
`Refusing to update invoice ${input.invoice_id}: status is "${invoice.v3_status}", not "draft". ` +
`This skill only touches drafts.`,
);
}
const patch: Record<string, unknown> = {};
if (input.lines) {
patch.lines = input.lines.map((l) => ({
name: l.name,
unit_cost: { amount: String(l.amount), code: "USD" },
qty: l.quantity ?? 1,
type: 0,
}));
}
if (input.notes !== undefined) patch.notes = input.notes;
if (input.due_offset_days !== undefined) {
const d = new Date();
d.setDate(d.getDate() + input.due_offset_days);
patch.due_date = d.toISOString().slice(0, 10);
}
const data = await fb("PUT", acct(`/invoices/invoices/${input.invoice_id}`), {
invoice: patch,
});
return data.response?.result?.invoice ?? data;
}
/**
* Fetch a single invoice by id, including line items (the `lines` array).
* listInvoices() does NOT return line items; this call does because it adds
* the `include[]=lines` query param that the list endpoint omits.
*
* Line item shape: { name, description, qty, unit_cost: { amount, code }, amount: { amount, code }, type }
*/
export async function getInvoice(invoice_id: number) {
const data = await fb("GET", acct(`/invoices/invoices/${invoice_id}?include[]=lines`));
return data.response?.result?.invoice ?? data;
}
/**
* Intentionally refuses. The snappy-freshbooks skill never sends invoices —
* Robert (or another human) sends them from the FreshBooks UI after reviewing
* the draft. If you are tempted to call this, draft the invoice instead and
* tell Robert it is ready for review.
*/
export function sendInvoice(_input: { invoice_id: number; subject?: string; body?: string }): never {
throw new Error(
"snappy-freshbooks: sendInvoice is disabled by policy. " +
"This skill only creates and updates DRAFT invoices. " +
"A human reviews the draft in FreshBooks and sends it from the UI.",
);
}
export async function markPaid(input: { invoice_id: number; payment_date: string }) {
// Create a payment on the invoice
const data = await fb("POST", acct("/payments/payments"), {
payment: {
invoiceid: input.invoice_id,
date: input.payment_date,
type: "Check",
note: "Marked paid via snappy-freshbooks",
},
});
return data.response?.result?.payment ?? data;
}
export async function listTimeEntries() {
const data = await fb("GET", acct("/time_entries"));
return data.response?.result?.time_entries ?? data;
}
export async function createTimeEntry(input: {
client_id: number;
hours: number;
note: string;
date?: string;
}) {
const data = await fb("POST", acct("/time_entries"), {
time_entry: {
client_id: input.client_id,
duration: input.hours * 3600,
note: input.note,
started_at: (input.date || new Date().toISOString().slice(0, 10)) + " 09:00:00",
is_logged: true,
},
});
return data.response?.result?.time_entry ?? data;
}
export async function listExpenses() {
const data = await fb("GET", acct("/expenses/expenses"));
return data.response?.result?.expenses ?? data;
}
export async function createExpense(input: {
category: string;
amount: number;
vendor: string;
note?: string;
date?: string;
}) {
const data = await fb("POST", acct("/expenses/expenses"), {
expense: {
amount: { amount: String(input.amount), code: "USD" },
vendor: input.vendor,
date: input.date || new Date().toISOString().slice(0, 10),
notes: input.note || "",
category_name: input.category,
},
});
return data.response?.result?.expense ?? data;
}
// --- Metrics (Step 7a) ---
const STAGED_ACTIONS_LOG = `${process.env.HOME}/.claude/logs/staged-actions.ndjson`;
type StagedRun = { ts: string; name: string; action: string };
function readStagedRunsFreshbooks(): StagedRun[] {
if (!fs.existsSync(STAGED_ACTIONS_LOG)) return [];
const out: StagedRun[] = [];
for (const line of fs.readFileSync(STAGED_ACTIONS_LOG, "utf-8").split("\n")) {
if (!line.trim()) continue;
try {
const j = JSON.parse(line);
if (typeof j?.name === "string" && typeof j?.ts === "string") {
out.push({ ts: j.ts, name: j.name, action: j.action || "" });
}
} catch { /* skip */ }
}
return out;
}
function withinLastDays(tsIso: string, days: number): boolean {
const t = new Date(tsIso).getTime();
if (isNaN(t)) return false;
return t >= Date.now() - days * 86400_000;
}
export function computeFreshbooksMetric(name: string): number | null {
const runs = readStagedRunsFreshbooks().filter((r) => withinLastDays(r.ts, 7));
switch (name) {
case "catchup-per-week":
case "catchup_runs_per_week":
return runs.filter((r) => r.name === "catchup").length;
case "reconcile-per-week":
case "reconcile_runs_per_week":
return runs.filter((r) => r.name === "reconcile").length;
case "catchup-apply-rate":
case "catchup_apply_rate": {
const catchups = runs.filter((r) => r.name === "catchup");
if (!catchups.length) return null;
return catchups.filter((r) => r.action === "delivered").length / catchups.length;
}
default:
return null;
}
}
// --- CLI ---
if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
(async () => {
const [, , cmd, ...args] = process.argv;
switch (cmd) {
case "metrics": {
const [name, ...rest] = args;
if (!name) {
console.error("Usage: api.ts metrics <name> [--json]");
console.error("Names: catchup-per-week, reconcile-per-week, catchup-apply-rate");
process.exit(1);
}
const value = computeFreshbooksMetric(name);
if (rest.includes("--json")) console.log(JSON.stringify({ value }));
else console.log(value == null ? "null" : String(value));
break;
}
case "clients": {
const data = await listClients();
console.log(JSON.stringify(data, null, 2));
break;
}
case "invoices": {
const data = await listInvoices();
console.log(JSON.stringify(data, null, 2));
break;
}
case "time-entries": {
const data = await listTimeEntries();
console.log(JSON.stringify(data, null, 2));
break;
}
case "expenses": {
const data = await listExpenses();
console.log(JSON.stringify(data, null, 2));
break;
}
case "create-invoice": {
if (!args[0]) { console.error("Usage: api.ts create-invoice '{...}'"); process.exit(1); }
const data = await createInvoice(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "get-invoice": {
if (!args[0]) { console.error("Usage: api.ts get-invoice <invoice_id>"); process.exit(1); }
const data = await getInvoice(Number(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "update-invoice": {
if (!args[0]) { console.error("Usage: api.ts update-invoice '{\"invoice_id\":123,\"notes\":\"...\"}'"); process.exit(1); }
const data = await updateInvoice(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "send-invoice": {
console.error(
"snappy-freshbooks: send-invoice is disabled by policy. " +
"Drafts only. A human sends from the FreshBooks UI.",
);
process.exit(2);
}
case "mark-paid": {
if (!args[0]) { console.error("Usage: api.ts mark-paid '{\"invoice_id\":123,\"payment_date\":\"2026-04-08\"}'"); process.exit(1); }
const data = await markPaid(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "log-time": {
if (!args[0]) { console.error("Usage: api.ts log-time '{\"client_id\":1,\"hours\":2,\"note\":\"...\"}'"); process.exit(1); }
const data = await createTimeEntry(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
case "log-expense": {
if (!args[0]) { console.error("Usage: api.ts log-expense '{\"category\":\"software_saas\",\"amount\":99,\"vendor\":\"...\"}'"); process.exit(1); }
const data = await createExpense(JSON.parse(args[0]));
console.log(JSON.stringify(data, null, 2));
break;
}
default:
console.log("Usage: npx tsx api.ts [clients|invoices|time-entries|expenses|create-invoice|send-invoice|mark-paid|log-time|log-expense] ...");
}
})();
}
scripts- helper scripts it can run
prose-only skill - 1 inline code block live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 10 runs
no recent runs logged - the eval contract is declared but nothing has been graded yet