Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add quota-burn scheduled automation

[._.]/ Adam Eivy74b36cd54a67
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4ad699cc39..0b9308ee2a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,10 @@
- **[issue-3124] Usage cost estimates now include pre-breakdown history** — Older activity is grouped as legacy usage, conflicting totals agree, missing provider IDs are labeled clearly, and the report explains which token costs remain uncounted.
+## Quota-burn automation
+
+- **[issue-3090] Provider quota can now be spent deliberately before a reset.** Configure a prompt, reserve, reset window, and dispatch cap for each CLI provider family; the opt-in scheduler checks usage without consuming tokens and only runs the selected provider when safe, known quota remains.
+
## Navigation
- Third-level Create navigation for Series and Universes can now be collapsed and expanded independently.
diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
index 43fde6a6b1..7810a90916 100644
--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
@@ -5,6 +5,7 @@ import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TY
import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';
import ToggleSwitch from '../../../ToggleSwitch';
import { INTERVAL_LABELS } from './scheduleConstants';
+import QuotaBurnFamilyEditor from './QuotaBurnFamilyEditor';
const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata, managedAgentOptions, override, onUpdate }) {
const [updating, setUpdating] = useState(false);
@@ -190,6 +191,18 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
ariaLabel={`${isEnabled ? 'Disable' : 'Enable'} ${taskType} for ${app.name}`}
/>
</div>
+
+ {taskType === 'quota-burn' && (
+ <QuotaBurnFamilyEditor
+ metadata={override?.taskMetadata}
+ disabled={updating}
+ onSave={async (taskMetadata) => {
+ setUpdating(true);
+ await onUpdate(app.id, taskType, { taskMetadata }).catch(() => {});
+ setUpdating(false);
+ }}
+ />
+ )}
</div>
</div>
);
diff --git a/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx b/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx
new file mode 100644
index 0000000000..e4ba70cc52
--- /dev/null
+++ b/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx
@@ -0,0 +1,41 @@
+import { useState } from 'react';
+
+const FAMILIES = ['claude', 'codex', 'agy', 'grok'];
+const defaults = { enabled: false, prompt: '', providerId: null, model: null, scope: null, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0 };
+
+export default function QuotaBurnFamilyEditor({ metadata, onSave, disabled }) {
+ const [expanded, setExpanded] = useState(null);
+ const families = metadata?.families || {};
+ const saveFamily = (id, patch) => {
+ const next = { ...defaults, ...(families[id] || {}), ...patch };
+ onSave({ ...(metadata || {}), families: { ...families, [id]: next } });
+ };
+
+ return (
+ <div className="w-full mt-2 rounded border border-port-border bg-port-card/30 p-3 space-y-2">
+ <p className="text-xs text-gray-300">Quota-burn families run only near reset, stay disabled until configured, and never dispatch on an unknown reset time.</p>
+ {FAMILIES.map((id) => {
+ const family = { ...defaults, ...(families[id] || {}) };
+ const open = expanded === id;
+ return (
+ <div key={id} className="rounded border border-port-border/70 p-2">
+ <div className="flex items-center gap-2">
+ <input id={`quota-burn-${id}`} type="checkbox" checked={family.enabled} disabled={disabled} onChange={(event) => saveFamily(id, { enabled: event.target.checked })} />
+ <label htmlFor={`quota-burn-${id}`} className="text-sm capitalize text-white flex-1">{id}</label>
+ <button type="button" className="text-xs text-port-accent hover:underline" onClick={() => setExpanded(open ? null : id)}>{open ? 'Hide settings' : 'Configure'}</button>
+ </div>
+ {open && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-3 text-xs">
+ <label className="text-gray-400">Reset window (hours)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="0" value={family.resetWithinHours} disabled={disabled} onChange={(event) => saveFamily(id, { resetWithinHours: Number(event.target.value) })} /></label>
+ <label className="text-gray-400">Reserve (%)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="0" max="100" value={family.reservePercent} disabled={disabled} onChange={(event) => saveFamily(id, { reservePercent: Number(event.target.value) })} /></label>
+ <label className="text-gray-400">Dispatch cap<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="1" value={family.maxDispatchesPerWindow} disabled={disabled} onChange={(event) => saveFamily(id, { maxDispatchesPerWindow: Number(event.target.value) })} /></label>
+ <label className="text-gray-400">Provider ID (optional)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" value={family.providerId || ''} disabled={disabled} onChange={(event) => saveFamily(id, { providerId: event.target.value || null })} /></label>
+ <label className="sm:col-span-2 text-gray-400">Work prompt<textarea className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white min-h-20" value={family.prompt} disabled={disabled} onChange={(event) => saveFamily(id, { prompt: event.target.value })} /></label>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
new file mode 100644
index 0000000000..8d0c411b81
--- /dev/null
+++ b/docs/QUOTA-BURN.md
@@ -0,0 +1,17 @@
+# Quota-burn automation
+
+Quota-burn is an opt-in perpetual scheduled task for installations that use
+subscription-backed CLI providers. It first performs only the existing
+zero-token usage checks. It dispatches an agent only when an enabled provider
+family is inside its configured reset window and still has quota above its
+reserve percentage.
+
+Each provider family has its own prompt, optional CLI/TUI provider pin, reset
+window, reserve, and per-window dispatch cap. Unknown reset times, unsupported
+providers, quota-read errors, and missing agent-capable providers all skip a
+dispatch safely. The feature is disabled by default; enabling it is explicit
+consent to spend that provider's subscription quota on a schedule.
+
+The configuration and dispatch ledger are machine-local under `data/cos/`.
+They are intentionally not federated: quota belongs to a particular machine
+and provider account, not to an app record shared with peers.
diff --git a/server/lib/README.md b/server/lib/README.md
index 016b462839..7a0b451021 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -26,6 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
+| `quotaReset.js` | Normalizes provider quota reset timestamps and computes time remaining without treating unknown values as imminent resets. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 0796db0ad1..a807d9049e 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -656,6 +656,31 @@ export const ISSUE_AUTHOR_FILTERS = ['self', 'owner', 'any'];
export const SWARM_COUNT_MIN = 2;
export const SWARM_COUNT_MAX = 6;
+const QUOTA_BURN_FAMILIES = new Set(['claude', 'codex', 'agy', 'grok']);
+
+function sanitizeQuotaBurnFamilies(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const clean = Object.create(null);
+ for (const [id, value] of Object.entries(raw)) {
+ if (!QUOTA_BURN_FAMILIES.has(id) || !value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const enabled = value.enabled === true;
+ const prompt = typeof value.prompt === 'string' ? value.prompt.slice(0, 8000) : '';
+ const resetWithinHours = Number(value.resetWithinHours ?? 24);
+ const reservePercent = Number(value.reservePercent ?? 0);
+ const maxDispatchesPerWindow = Number(value.maxDispatchesPerWindow ?? 5);
+ const priority = Number(value.priority ?? 0);
+ if (!Number.isFinite(resetWithinHours) || resetWithinHours < 0 || resetWithinHours > 168
+ || !Number.isFinite(reservePercent) || reservePercent < 0 || reservePercent > 100
+ || !Number.isInteger(maxDispatchesPerWindow) || maxDispatchesPerWindow < 1 || maxDispatchesPerWindow > 50
+ || !Number.isInteger(priority) || priority < 0 || priority > 100
+ || (value.providerId != null && typeof value.providerId !== 'string')
+ || (value.model != null && typeof value.model !== 'string')) return null;
+ clean[id] = { enabled, prompt, providerId: value.providerId || null, model: value.model || null,
+ scope: typeof value.scope === 'string' ? value.scope : null, resetWithinHours, reservePercent, maxDispatchesPerWindow, priority };
+ }
+ return clean;
+}
+
// POST /api/cos/tasks/slashdo — a `/do:*` button click from an app's Agent
// Operations panel. The run-settings fields are PICKED from createCosTaskSchema
// rather than restated, so the drawer's provider/model/effort/simplify/reviewer
@@ -694,6 +719,12 @@ export function sanitizeTaskMetadata(raw) {
hasKeys = true;
}
}
+ if (Object.prototype.hasOwnProperty.call(raw, 'families')) {
+ const families = sanitizeQuotaBurnFamilies(raw.families);
+ if (!families) return null;
+ clean.families = families;
+ hasKeys = true;
+ }
if (Object.prototype.hasOwnProperty.call(raw, 'prCompletion') && PR_COMPLETION_VALUES.includes(raw.prCompletion)) {
clean.prCompletion = raw.prCompletion;
hasKeys = true;
diff --git a/server/lib/index.js b/server/lib/index.js
index 1fe407b9bf..8e30079e7b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -106,6 +106,7 @@ export * from './promptPartials.js';
export * from './promptRunner.js';
export * from './promptTemplate.js';
export * from './providerModels.js';
+export * from './quotaReset.js';
export * from './opencodeConfig.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
// mediaModels.js — namespace it so the barrel surface is unambiguous.
diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.js
new file mode 100644
index 0000000000..fc4f0382b3
--- /dev/null
+++ b/server/lib/quotaReset.js
@@ -0,0 +1,62 @@
+/**
+ * Normalize the reset times emitted by the provider quota adapters. A missing
+ * or ambiguous reset is deliberately represented as null: a scheduled quota
+ * burn must park rather than guess that a provider is about to reset.
+ */
+
+const HOUR_MS = 60 * 60 * 1000;
+
+function hasExplicitZone(value) {
+ return /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value);
+}
+
+function zoneOffsetMs(epochMs, timeZone) {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ timeZoneName: 'longOffset',
+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
+ hourCycle: 'h23',
+ }).formatToParts(new Date(epochMs));
+ const offset = parts.find((part) => part.type === 'timeZoneName')?.value;
+ const match = /^GMT([+-])(\d{2}):(\d{2})$/.exec(offset || '');
+ if (!match) return null;
+ return (Number(match[2]) * 60 + Number(match[3])) * 60 * 1000 * (match[1] === '+' ? 1 : -1);
+}
+
+function parseInZone(value, timeZone) {
+ const parsed = Date.parse(`${value} UTC`);
+ if (!Number.isFinite(parsed)) return null;
+ const offset = zoneOffsetMs(parsed, timeZone);
+ return offset === null ? null : parsed - offset;
+}
+
+/**
+ * @returns {{ epochMs: number|null, source: 'iso'|'parsed'|'unknown' }}
+ */
+export function normalizeResetAt(limit, { now = Date.now(), timeZone } = {}) {
+ const value = typeof limit?.resetsAt === 'string' ? limit.resetsAt.trim() : '';
+ if (!value) return { epochMs: null, source: 'unknown' };
+
+ if (hasExplicitZone(value)) {
+ const epochMs = Date.parse(value);
+ return Number.isFinite(epochMs) ? { epochMs, source: 'iso' } : { epochMs: null, source: 'unknown' };
+ }
+
+ const zone = limit?.timezone || timeZone;
+ let epochMs = zone ? parseInZone(value, zone) : Date.parse(value);
+ if (!Number.isFinite(epochMs)) return { epochMs: null, source: 'unknown' };
+
+ // Grok omits a year. Treat an already-passed date as the next occurrence,
+ // avoiding the accidental "reset now" interpretation at year boundaries.
+ if (!/\b\d{4}\b/.test(value) && epochMs < now - HOUR_MS) {
+ const date = new Date(epochMs);
+ date.setUTCFullYear(date.getUTCFullYear() + 1);
+ epochMs = date.getTime();
+ }
+ return { epochMs, source: 'parsed' };
+}
+
+export function hoursUntilReset(limit, opts = {}) {
+ const { epochMs } = normalizeResetAt(limit, opts);
+ return epochMs === null ? null : (epochMs - (opts.now ?? Date.now())) / HOUR_MS;
+}
diff --git a/server/lib/quotaReset.test.js b/server/lib/quotaReset.test.js
new file mode 100644
index 0000000000..37077fb2a6
--- /dev/null
+++ b/server/lib/quotaReset.test.js
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+import { hoursUntilReset, normalizeResetAt } from './quotaReset.js';
+
+describe('quota reset normalization', () => {
+ const now = Date.parse('2026-07-26T12:00:00.000Z');
+
+ it('keeps an ISO reset instant exact', () => {
+ expect(normalizeResetAt({ resetsAt: '2026-07-27T12:00:00.000Z' }, { now }))
+ .toEqual({ epochMs: Date.parse('2026-07-27T12:00:00.000Z'), source: 'iso' });
+ });
+
+ it('uses null as the explicit unknown sentinel', () => {
+ expect(normalizeResetAt({ resetsAt: null }, { now })).toEqual({ epochMs: null, source: 'unknown' });
+ expect(hoursUntilReset({ resetsAt: 'not a date' }, { now })).toBeNull();
+ });
+
+ it('parses a local provider reset when a timezone is supplied', () => {
+ const result = normalizeResetAt({ resetsAt: 'July 27, 2026 08:00:00', timezone: 'America/Los_Angeles' }, { now });
+ expect(result).toEqual({ epochMs: Date.parse('2026-07-27T15:00:00.000Z'), source: 'parsed' });
+ });
+});
diff --git a/server/services/autonomousJobs/quotaBurnHooks.js b/server/services/autonomousJobs/quotaBurnHooks.js
new file mode 100644
index 0000000000..630245c4a6
--- /dev/null
+++ b/server/services/autonomousJobs/quotaBurnHooks.js
@@ -0,0 +1,57 @@
+import { getAllProviders } from '../providers.js';
+import { getProviderQuotas } from '../providerUsage.js';
+import { getQuotaBurnDispatches, recordQuotaBurnDispatch, selectBurnCandidates, quotaBurnConfig, QUOTA_BURN_TASK_TYPE } from '../quotaBurn.js';
+
+function providerForFamily(providers, family) {
+ const available = (providers || []).filter((provider) =>
+ provider?.enabled && (provider.type === 'cli' || provider.type === 'tui'));
+ if (family.providerId) return available.find((provider) => provider.id === family.providerId) || null;
+ const familyName = family.id.toLowerCase();
+ return available.find((provider) => String(provider.id || '').toLowerCase().includes(familyName)) || null;
+}
+
+function renderPrompt(candidate) {
+ const { family, limit, hoursUntilReset } = candidate;
+ return [
+ `# ${family.id} quota-burn task`,
+ '',
+ `This configured ${family.id} quota window resets in about ${Math.max(0, Math.ceil(hoursUntilReset))} hours.`,
+ `Window: ${limit.label || limit.scope || 'provider window'}; remaining: ${limit.percentRemaining}%; reserve: ${family.reservePercent}%.`,
+ `Dispatch cap: ${family.maxDispatchesPerWindow} for this reset window.`,
+ '',
+ 'Carry out the configured work below. Do not use another provider family as a substitute.',
+ '',
+ family.prompt.trim(),
+ ].join('\n');
+}
+
+/**
+ * Programmatic pre-agent hook. It refreshes quota readings immediately before
+ * dispatch, pins an agent-capable provider in the selected family, and returns
+ * a skip instead of spawning when any prerequisite is missing.
+ */
+export async function buildTaskInput({ app } = {}) {
+ if (!app) return { skip: { reason: 'no-app' } };
+ const config = quotaBurnConfig(app);
+ const ledger = await getQuotaBurnDispatches();
+ const quotas = await getProviderQuotas({ refresh: true });
+ const candidates = selectBurnCandidates(quotas, config, { dispatches: ledger });
+ const candidate = candidates[0];
+ if (!candidate) return { skip: { reason: 'no-burnable-provider-quota' } };
+
+ const providerResult = await getAllProviders();
+ const provider = providerForFamily(
+ Array.isArray(providerResult) ? providerResult : providerResult?.providers,
+ candidate.family,
+ );
+ if (!provider) return { skip: { reason: 'no-enabled-agent-provider-in-family' } };
+
+ await recordQuotaBurnDispatch(candidate.dispatchKey);
+ return {
+ prompt: renderPrompt(candidate),
+ providerId: provider.id,
+ model: candidate.family.model || null,
+ };
+}
+
+export const __test = { providerForFamily, renderPrompt, QUOTA_BURN_TASK_TYPE };
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 3d3b9e6e26..1538be2cec 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -482,6 +482,10 @@ export function hasWorkDetector(taskType) {
registerWorkDetector('claim-issue', detectGithubIssues);
registerWorkDetector('claim-issue-gitlab', detectGitlabIssues);
registerWorkDetector('plan-task', detectPlanTask);
+registerWorkDetector('quota-burn', async (app) => {
+ const { detectQuotaBurn } = await import('./quotaBurn.js');
+ return detectQuotaBurn(app);
+});
/**
* Probe whether `taskType` has actionable work for `app`. Always resolves to a
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
new file mode 100644
index 0000000000..7a3d93c0d0
--- /dev/null
+++ b/server/services/quotaBurn.js
@@ -0,0 +1,97 @@
+import { getProviderQuotas } from './providerUsage.js';
+import { join } from 'path';
+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
+
+export const QUOTA_BURN_TASK_TYPE = 'quota-burn';
+const LEDGER_FILE = join(PATHS.cos, 'quota-burn-dispatches.json');
+export const DEFAULT_QUOTA_BURN_FAMILY = {
+ enabled: false,
+ providerId: null,
+ model: null,
+ scope: null,
+ resetWithinHours: 24,
+ reservePercent: 0,
+ maxDispatchesPerWindow: 5,
+ priority: 0,
+ prompt: '',
+};
+
+export function quotaBurnConfig(app) {
+ const metadata = app?.taskTypeOverrides?.[QUOTA_BURN_TASK_TYPE]?.taskMetadata;
+ return metadata && typeof metadata === 'object' ? metadata : { families: {} };
+}
+
+export async function getQuotaBurnDispatches() {
+ const loaded = await readJSONFile(LEDGER_FILE, {});
+ return loaded && typeof loaded === 'object' ? loaded : {};
+}
+
+export async function recordQuotaBurnDispatch(key) {
+ const ledger = await getQuotaBurnDispatches();
+ const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
+ await atomicWrite(LEDGER_FILE, next);
+ return next;
+}
+
+function normalizedFamily(id, value) {
+ if (!value || typeof value !== 'object' || value.enabled !== true) return null;
+ const config = { ...DEFAULT_QUOTA_BURN_FAMILY, ...value };
+ return {
+ id,
+ ...config,
+ resetWithinHours: Math.max(0, Number(config.resetWithinHours) || 24),
+ reservePercent: Math.min(100, Math.max(0, Number(config.reservePercent) || 0)),
+ maxDispatchesPerWindow: Math.max(1, Math.floor(Number(config.maxDispatchesPerWindow) || 5)),
+ priority: Number(config.priority) || 0,
+ };
+}
+
+function selectLimit(card, family, now) {
+ const scoped = (card.limits || []).filter((limit) => !family.scope || limit.scope === family.scope);
+ return scoped
+ .map((limit) => ({ limit, hours: hoursUntilReset(limit, { now, timeZone: family.timeZone }) }))
+ .filter((entry) => entry.hours !== null)
+ .sort((a, b) => a.hours - b.hours)[0] || null;
+}
+
+export function burnBudgetRemaining(limit, family) {
+ return Math.max(0, Number(limit?.percentRemaining) - family.reservePercent);
+}
+
+/** Select only safely-known, still-burnable provider windows. */
+export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {} } = {}) {
+ const cards = new Map((quotas || []).map((card) => [card.family, card]));
+ return Object.entries(config?.families || {})
+ .map(([id, value]) => normalizedFamily(id, value))
+ .filter(Boolean)
+ .map((family) => {
+ const card = cards.get(family.id);
+ if (!card || card.supported === false || card.error) return null;
+ const selected = selectLimit(card, family, now);
+ if (!selected || selected.hours < 0 || selected.hours > family.resetWithinHours) return null;
+ const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now, timeZone: family.timeZone }).epochMs}`;
+ if (Number(dispatches[dispatchKey] || 0) >= family.maxDispatchesPerWindow) return null;
+ if (burnBudgetRemaining(selected.limit, family) <= 0) return null;
+ return { family, card, limit: selected.limit, hoursUntilReset: selected.hours, dispatchKey };
+ })
+ .filter(Boolean)
+ .sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);
+}
+
+export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, now = Date.now(), dispatches } = {}) {
+ const config = quotaBurnConfig(app);
+ const configured = Object.entries(config.families || {})
+ .filter(([, family]) => family?.enabled === true)
+ .map(([id, family]) => ({ id, ...family }));
+ if (!configured.length) return { actionable: false, count: 0, reason: 'no-enabled-families' };
+ const quotas = await getQuotas({ refresh: false });
+ const configuredCards = quotas.filter((card) => configured.some((family) => family?.id === card?.family));
+ if (configuredCards.length && configuredCards.every((card) => card?.error)) {
+ return { actionable: false, count: 0, transient: true, reason: 'all-provider-quota-checks-failed' };
+ }
+ const candidates = selectBurnCandidates(quotas, config, { now, dispatches: dispatches || await getQuotaBurnDispatches() });
+ return candidates.length
+ ? { actionable: true, count: candidates.length, reason: `${candidates[0].family.id} resets in ${Math.ceil(candidates[0].hoursUntilReset)}h`, candidates }
+ : { actionable: false, count: 0, reason: 'no-family-within-reset-window' };
+}
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
new file mode 100644
index 0000000000..7fd81cefe1
--- /dev/null
+++ b/server/services/quotaBurn.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+import { detectQuotaBurn, selectBurnCandidates } from './quotaBurn.js';
+import { sanitizeTaskMetadata } from '../lib/validation.js';
+
+const NOW = Date.parse('2026-07-26T12:00:00.000Z');
+const config = {
+ families: {
+ grok: { enabled: true, prompt: 'Animate eligible sprites.', resetWithinHours: 24, reservePercent: 20, maxDispatchesPerWindow: 2 },
+ codex: { enabled: true, prompt: 'Prepare assets.', resetWithinHours: 24, reservePercent: 0, priority: 1 },
+ },
+};
+const quota = (family, resetsAt, percentRemaining = 50, extras = {}) => ({
+ family, supported: true, limits: [{ key: 'week', scope: 'week', label: 'Weekly', resetsAt, percentRemaining }], ...extras,
+});
+
+describe('selectBurnCandidates', () => {
+ it('selects burnable windows by reset time then priority', () => {
+ const candidates = selectBurnCandidates([
+ quota('codex', '2026-07-27T00:00:00.000Z'),
+ quota('grok', '2026-07-26T18:00:00.000Z'),
+ ], config, { now: NOW });
+ expect(candidates.map((candidate) => candidate.family.id)).toEqual(['grok', 'codex']);
+ });
+
+ it('skips unknown, out-of-window, reserved, unsupported, and exhausted windows', () => {
+ expect(selectBurnCandidates([quota('grok', null)], config, { now: NOW })).toEqual([]);
+ expect(selectBurnCandidates([quota('grok', '2026-07-28T12:00:00.000Z')], config, { now: NOW })).toEqual([]);
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z', 20)], config, { now: NOW })).toEqual([]);
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z', 50, { supported: false })], config, { now: NOW })).toEqual([]);
+ const selected = selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], config, { now: NOW })[0];
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], config, {
+ now: NOW, dispatches: { [selected.dispatchKey]: 2 },
+ })).toEqual([]);
+ });
+});
+
+describe('detectQuotaBurn', () => {
+ it('parks an empty configuration without reading provider usage', async () => {
+ const getQuotas = vi.fn();
+ await expect(detectQuotaBurn({ taskTypeOverrides: {} }, { getQuotas, now: NOW }))
+ .resolves.toMatchObject({ actionable: false, reason: 'no-enabled-families' });
+ expect(getQuotas).not.toHaveBeenCalled();
+ });
+
+ it('reports a transient result when every configured quota probe failed', async () => {
+ await expect(detectQuotaBurn({ taskTypeOverrides: { 'quota-burn': { taskMetadata: config } } }, {
+ getQuotas: async () => [quota('grok', null, 0, { error: 'signed out' })], now: NOW,
+ })).resolves.toMatchObject({ actionable: false, transient: true });
+ });
+});
+
+describe('quota-burn metadata validation', () => {
+ it('keeps valid family configuration and rejects unknown families or unsafe reserves', () => {
+ expect(sanitizeTaskMetadata({ families: { grok: { enabled: true, reservePercent: 20 } } }))
+ .toMatchObject({ families: { grok: { enabled: true, reservePercent: 20 } } });
+ expect(sanitizeTaskMetadata({ families: { unknown: { enabled: true } } })).toBeNull();
+ expect(sanitizeTaskMetadata({ families: { grok: { reservePercent: 101 } } })).toBeNull();
+ });
+});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index aa46c90b97..ea56312b3e 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -212,7 +212,10 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// stays in app.layeredIntelligence. Has NO DEFAULT_TASK_PROMPTS entry — the
// buildTaskInput hook renders the prompt. See taskTypeHooks.js +
// autonomousJobs/layeredIntelligenceHooks.js.
- 'layered-intelligence'
+ 'layered-intelligence',
+ // An opt-in perpetual task that runs a zero-token quota probe before it
+ // ever dispatches an agent. The hook owns its provider-specific prompt.
+ 'quota-burn'
];
// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
@@ -347,7 +350,8 @@ export const DEFAULT_TASK_INTERVALS = {
// agent runs in a worktree that is discarded without a commit/merge/PR
// (discardWorktree), so it can't land code — its `.agent-done` payload is the
// only sanctioned output (consumed by the processTaskOutput hook).
- 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } }
+ 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } },
+ 'quota-burn': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 */12 * * *', taskMetadata: { useWorktree: true, openPR: true, simplify: true, families: {} } }
};
// Agent-options that a task manages internally — UI locks the toggle, and
@@ -1867,7 +1871,8 @@ export const TASK_TYPE_DESCRIPTIONS = {
'jira-status-report': 'Generate JIRA weekly status report',
'reference-watch': 'Watch reference repos and append PLAN.md items for new upstream work',
'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
- 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent"
+ 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent",
+ 'quota-burn': 'When enabled, spend configured provider subscription quota only near its reset window using that provider family\'s prompt'
};
function getTaskTypeDescription(taskType) {
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 9d921e426a..ef99135b9b 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -34,6 +34,7 @@
// or both hooks; a missing export means "no hook of that kind for this type".
const HOOK_MODULES = {
'layered-intelligence': () => import('./autonomousJobs/layeredIntelligenceHooks.js'),
+ 'quota-burn': () => import('./autonomousJobs/quotaBurnHooks.js'),
};
async function loadHookModule(taskType) {