Files
PaperClipAI/server/src/services/native-runtime/native-startup-retry.ts
T
DottaandClaude Opus 5.5 3ad8f00192 feat(antigravity): trusted /swarm from the task composer, behind an experimental flag (#22733)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` (a
coordinator, helpers and a verifier) only on the Antigravity CLI
> - #22731 adds a verified CLI route to the Runner, but nothing selects
it yet
> - A swarm must start only when the signed-in user asks for it, only
when an admin turned the experimental feature on, and never silently run
as an ordinary request when it cannot run
> - This pull request adds the trusted `/swarm` request in the task
composer, the server checks and run selection behind an experimental
flag, removes Paperclip delegation tools from a swarm turn, and adds the
attended catalog cells, docs and ledger
> - The benefit is that a user can start a native swarm from a task, and
gets one plain message when it is not available

## Linked Issues or Issue Description

Refs #22731, #22727, #22728, #22701

**Subsystem affected**
Task composer (UI), issue comments API, run selection (server),
Paperclip Runner tool bridge, runner-e2e catalog, docs.

**Problem or motivation**
A user who writes `/swarm <request>` to a Google Antigravity agent
should get a real native swarm in the task folder. Today `/swarm` is
neutralised text, and the task runs as an ordinary request.

**Proposed solution**
Read a leading `/swarm` with the shared rule from #22727 in the
composer, send it as a structured request, check it on the server, and
select the CLI route from #22731 for that run only.

## What Changed

- **Trusted start (UI).** `parseSwarmCommand` in `composer-commands.ts`
uses `parseLeadingUserCommand` (the one rule from #22727). A leading
`/swarm` in the task composer sends the request text with
`nativeCommand: "swarm"`; a bare `/swarm` asks for a request; `/swarm`
with an assignee change is refused; `/swarm` anywhere else stays text. A
resent draft keeps the structured request.
- **Contract.** `addIssueCommentSchema` gains `nativeCommand: "swarm"`.
`instance.experimental.enableAntigravitySwarm` (feature catalog,
settings page, server defaults), off by default. No Cloud policy in
Core.
- **Server (`services/antigravity-swarm.ts`, comments route, runtime
selection).**
- The comments route accepts `nativeCommand` only from a signed-in board
user. When a swarm cannot run it answers 422 with one plain message and
posts nothing: flag off, not a Google Antigravity assignee, a chat, Plan
mode.
- An accepted request is recorded in the activity log
(`issue.antigravity_swarm_requested`, server-written) and the assignee's
wake carries the comment id. Comment text is never read as a command.
- Run selection makes the run a swarm only when that activity record
exists. It refuses a remote or cloud environment and Plan mode with a
plain run failure, so a swarm is never run as an ordinary request. It
logs `issue.antigravity_swarm_started` in plain language: helper actions
are auto-approved, Paperclip does not sandbox the helpers and cannot see
their shell commands, and usage is one total.
- The native execution input sets the Antigravity provider mode `swarm`
for that run only, and carries the verified request in its own field,
`provider.swarmRequest` (the Runner contract accepts it only with that
mode and requires it there, 1 to 16,000 characters). The Runner copies
it into the model envelope as `swarmRequest`; the swarm route sends
exactly `/swarm <swarmRequest>` and never reads `task.prompt`, which
holds rendered wake comments, task context and text the Runner adds
(handoff, attachments, queued messages).
- The swarm turn contract (mode `swarm`, envelope
`paperclip.native-model-envelope.v3`, `swarmRequest` of 1 to 16,000
characters) is declared as `antigravitySwarmTurn` in
`protocol/provider-schemas/acpx-sidecar.schema.json` and generated into
TypeScript, so the pack `contractDigest` covers it (it changes; older
image packs are rebuilt rather than reused). Provider profile
`commandDigest`s and versions are unchanged, so no saved session is
reset.
- What the swarm sees of the task: only the request. The title, the
description (which other people or agents may have written) and other
comments are not part of the prompt; the coordinator can read them
through Paperclip's task tools as data if it needs context.
- An empty `/swarm` or one over 16,000 characters is refused in the
composer, by the comments route (422, nothing posted) and at run
selection (plain run failure), so it never runs as ordinary work.
- A swarm run never takes queued messages, and Interrupt treats it as
already started: it stops the swarm and delivers the queued message as
the next ordinary request, before or after the provider accepted the
turn.
- Retry after Stop, and past the three automatic attempts, counts only
when the signed-in user asked for it (their own Retry request on the
task after the last attempt). Wake reasons and copied run context are
not proof: a recovery that copies the request marker, an automatic retry
on the user's behalf, or an agent wake that names `task_retry` stay
bounded.
- **Runner.** For a swarm turn the Paperclip bridge drops delegation
tools (`paperclip_create_task`, `paperclip_create_issue`, hire/assign
tools); the instructions also tell the coordinator not to delegate.
- **runner-e2e.** `antigravity-swarm` suite, 5 local cells
(`two-helpers-and-verifier`, `stop-mid-swarm`, `process-loss-retry`,
`follow-up-after-swarm`, `flag-off-refusal`), explicit-only, never in
`--all` or CI matrix jobs. There is no automated executor yet: the
launcher refuses the cells and points at the live recipe. Catalog counts
updated (1392 cells).
- **Docs.** `tests/runner-e2e/SUITES.md`, `doc/evals.md`, and the
`/swarm` section, ledger row and live recipe in
`doc/plans/2026-11-22-antigravity-qualification.md`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/services/antigravity-swarm.test.ts`: 2 passed (red first: module
missing; Plan mode red then green).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-comment-reopen-routes.test.ts -t swarm`: 3 passed; 2
red against the route without this change.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/TaskChatComposer.test.tsx`: 164 passed,
including 4 new `/swarm` tests (red first).
- Runner: `vitest run src/drivers/acpx/antigravity-swarm-*.test.ts`: 69
passed (route tool filter red first).
- runner-e2e: `antigravity-swarm.test.ts` (red first) plus the catalog,
selector and Antigravity tests: 28 files passed.
- Typecheck: server, UI (except generated Storybook files absent from a
worktree) and runner: no errors.
- Live, real CLI 1.5.15 with the owner's sign-in, through the driver:
the receipt verified (pinned identity, task folder, `auto` read back,
`gemini-3.8-flash` + `low`). Google then refused the prompt with its 429
quota text; the driver reported it as a typed "out of quota" failure,
retired the CLI and nothing was written.
- **Not run live yet:** the full Paperclip proof (swarm to Done, Stop,
kill and Retry, follow-up, flag off). This PR is merged only after it
passes. Recipe:
`doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof`.

## Risks

### Security notes: the trust boundary

Helpers are auto-approved and Paperclip does not sandbox the CLI on a
local computer, so the boundary is who asked and what text is sent.
Every input that can influence it:

**(a) Whether a run is a swarm**
- `nativeCommand: "swarm"` on the comment request: accepted only from a
signed-in board user; the request record
(`issue.antigravity_swarm_requested`, actor = that user, `commentId`)
commits in the same transaction as the comment. Paperclip-written.
- `antigravitySwarmCommentId` on the wake/run context: set only by the
comments route and by run selection. It is a pointer, never trusted
alone: selection re-verifies comment id + task + company + human author
(no agent author) + a matching record by the same user.
- The pending request for marker-less wakes: the task's latest human
comment, verified the same way.
- Retry inheritance: the run's `retryOfRunId` chain (server-written),
bounded to 8 hops on the same task.
- Manual vs automatic: a request's first run, or a user's own Retry
request (`task_retry` / `retry_failed_run`, requested by a user, not
`initiatedBy` automation) after the last attempt. Not the wake reason
string.
- Instance flag `enableAntigravitySwarm` (admin), the assignee's adapter
config (Google Antigravity), execution target (local only), work mode
(Standard only: Plan, Ask and any other mode are refused, at comment
time and at run time), chat vs task: all Paperclip-owned settings.
- Prior attempts on the same request (run status rows):
Paperclip-written.

**(b) What text and tools the swarm gets**
- The prompt: `/swarm ` + `provider.swarmRequest`, which is the recorded
comment body minus a leading `/swarm`, trimmed, byte for byte (tested
through the production input builder and envelope with a merged wake
that contains an agent comment). The verified request.
- The system prompt append: only Paperclip-authored text: Paperclip's
fixed execution prompt, the run's hand-in values (the server-written
completion revision and criterion IDs that
`paperclip_finish`/`paperclip_block` require; never a criterion's
requirement text), and the fixed swarm rules. **The swarm runs without
the agent's own instructions**: the instruction bundle and connection
instructions are left out, because an agent with an editable
instructions folder can rewrite its instructions in an earlier ordinary
run, the helpers act under auto mode, and Paperclip keeps no
user-approved copy of those instructions to trust instead.
- Tools: only Paperclip's own MCP bridge (any other assigned tool server
refuses the swarm), with delegation, hiring, routing and generic API
operations removed. Paperclip's permission handler approves a CLI
permission request only when its tool name is `mcp_paperclip_<tool>` and
`<tool>` is one the run's bridge admits; everything else is refused, and
the CLI then ends the turn. Tool descriptions are Paperclip-authored;
tool results (for example other comments) are data the coordinator
reads, not the request.
- Model and mode: the agent's configured model, Antigravity's `auto`
mode, both read back and pinned by the receipt.
- Not sent: task title, description, wake comments, continuation events,
attachments, queued messages, handoff text.

Known residual: a Retry or recovery run that has not yet been selected
(still preparing) does not carry the request marker, so an Interrupt in
that short window keeps the message for the turn boundary instead of
stopping the run; the message is delivered after the run ends.

- Off by default and local only. With the flag on, helpers act under
Antigravity's `auto` mode. **Paperclip does not sandbox them on a local
computer**, and their tool calls never reach Paperclip, so helper shell
commands can write outside the task folder where the CLI's own sandbox
allows (workspace plus temp directories). The settings text, the
activity log and the plan doc say so.
- On macOS the CLI uses its own Google sign-in from the login keychain,
not Paperclip's stored connection.
- Google's consumer terms have a clause about third-party tools that
access the service. A legal read is pending; this PR does not claim
compliance.
- `/swarm` as the first word of a composer message is now a swarm
request for every agent; for agents other than Google Antigravity the
server refuses it with a plain message. To send the literal text, put
other text first.
- The new runner-e2e cells are attended only and have no automated
executor.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

Review round 2 (head a2decc65f3): Greptile's "swarms must guess
completion fields" fixed as above (runner `nativeSystemInstructions`,
red first 1 in the fake-CLI swarm runtime test; request text to the CLI
still exactly `/swarm <request>`); CI typecheck failure was a TS18046 in
`acpx-runtime-sidecar.test.ts` (test-program typecheck), fixed; master
merged, its pruned `heartbeat-provider-limit-wait` and
`provider-failure-classification` suites dropped, with this branch's
swarm cases kept in `antigravity-swarm-provider-limit.test.ts` and
`antigravity-swarm.test.ts`. No protocol schema change. Round 3 (head
1444503e84, from live run6): CLI 1.5.15 names a client MCP call
`mcp_<server>_<tool>` with no `_meta` (payload recorded from the pinned
CLI, now the fake CLI's fixture), so Paperclip's permission handler
refused the coordinator's own `get_task_context` and the CLI ended the
turn on the denial. The handler now approves only tools the run's
Paperclip bridge admits, by that name, and fails closed otherwise; a
refused Paperclip tool is reported as such, not as a helper blocked
outside the task folder. A swarm turn without a hand-in fails plainly
(`ANTIGRAVITY_SWARM_NO_RESULT`: "The swarm ended without doing any
work"), every swarm-route failure code settles as
`antigravity_swarm_unavailable` (no automatic retry; Retry offered), and
selection never starts another swarm automatically after one; a lost CLI
process still recovers on its own. The run history always records
whether the CLI's sign-in matches the connection account (with the
reason when unknown). Usage-limit evidence is scoped by the executed
provider mode, so limits from pre-scope swarms hold only swarms. Red
first: runtime 5, server 3.

Then (head 74454a17f3): an empty `/swarm` body now gets the documented
422 `antigravity_swarm_unavailable` instead of a generic 400
(`addIssueSwarmCommentSchema`, route red first 1); an empty ordinary
comment keeps its 400.

Review round (earlier head):
- `pnpm --filter @paperclipai/server exec vitest run` on the swarm,
request-path, native-execution-input, first-turn, queued-comments and
comment-route tests: 475 passed. Red first: request path 1, execution
input 3, empty/over-long DB 3 and route 2, Interrupt during a swarm 2,
Retry proof 2.
- Runner `src/drivers/acpx src/contracts`: passed; swarm runtime red
first 6 (request field, verbatim text, empty, over-long, no field,
request only in the rendered prompt).
- UI `TaskChatComposer.test.tsx`: over-long `/swarm` refused (red first
1).
- Typecheck: server (layers), UI and runner: no errors.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
file edit) in Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:54:23 -06:00

285 lines
16 KiB
TypeScript

import { createHash } from "node:crypto";
import { and, desc, eq, gte, inArray, ne, or, sql } from "drizzle-orm";
import { connectionGrants, heartbeatRuns, type Db } from "@paperclipai/db";
import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared";
import { logger } from "../../middleware/logger.js";
import { infrastructureRetryDelayMs, PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js";
import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { ANTIGRAVITY_CLI_QUOTA_SCOPE } from "../antigravity-swarm-refusal.js";
/** Categories that report an exhausted account or request allowance. */
const PROVIDER_LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"];
/** Run errors that record an exhausted allowance without a typed provider failure. */
const PROVIDER_LIMIT_ERROR_CODES = ["native_provider_usage_limit", "provider_quota"];
/** Limit evidence older than this is ignored, and no limit holds a retry longer. */
const NATIVE_PROVIDER_LIMIT_WINDOW_MS = 24 * 60 * 60_000;
const LIMIT_EVIDENCE_ROWS = 20;
type ProviderLimitEvidence = { resetAt: number; resetReported: boolean; category: string; sourceRunId: string | null; grantId?: string | null };
function limitEvidence(failure: ProviderFailure | null, observedAt: Date, sourceRunId: string | null): ProviderLimitEvidence | null {
if (!failure || !PROVIDER_LIMIT_CATEGORIES.includes(failure.category)) return null;
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, observedAt)) return null;
const retryAt = failure.retryAt ? Date.parse(failure.retryAt) : Number.NaN;
if (Number.isFinite(retryAt)) return { resetAt: retryAt, resetReported: true, category: failure.category, sourceRunId };
// ACP harnesses report the reset only in the provider's own wording.
const clockReset = parseProviderQuotaClockReset(failure.message, observedAt);
return clockReset
? { resetAt: clockReset.getTime(), resetReported: true, category: failure.category, sourceRunId }
: { resetAt: observedAt.getTime() + PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS, resetReported: false, category: failure.category, sourceRunId };
}
/**
* The AI credential a provider limit is checked against. A limit belongs to
* the credential it was reported on, so evidence from another credential, or
* from one that was revoked or removed, does not hold work.
*/
export type ProviderLimitCredential =
/** No managed AI connection: the harness signs in with the host's own account. */
| { kind: "host" }
/** The managed connection grants the next run may use. */
| { kind: "grants"; grantIds: readonly string[] }
/** A managed connection whose account is chosen only when the run starts. */
| { kind: "unresolved" };
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* The run-context key naming the provider quota a run draws on when one
* credential reaches more than one quota (for example Google's Antigravity CLI,
* which bills a different pool than the same account's ordinary route). A limit
* holds only runs on the same credential AND the same quota scope. Absent (all
* rows saved before scopes existed, and every ordinary run) is the credential's
* default quota.
*/
export const PROVIDER_QUOTA_SCOPE_CONTEXT_KEY = "providerQuotaScope";
const QUOTA_SCOPE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
/**
* The quota scope a run drew on; null is the credential's default quota. A run
* that executed the Antigravity swarm route draws on the CLI's own pool even
* when its context lacks the field (runs started before scopes existed, and
* their retries), so the executed provider mode in its runner profile decides.
*/
export function runProviderQuotaScope(contextSnapshot: unknown, runnerProfileJson?: unknown): string | null {
const value = contextSnapshot && typeof contextSnapshot === "object"
? (contextSnapshot as Record<string, unknown>)[PROVIDER_QUOTA_SCOPE_CONTEXT_KEY] : undefined;
if (typeof value === "string" && QUOTA_SCOPE_PATTERN.test(value)) return value;
const profile = runnerProfileJson && typeof runnerProfileJson === "object" ? runnerProfileJson as Record<string, unknown> : {};
const input = profile.nativeExecutionInput && typeof profile.nativeExecutionInput === "object" ? profile.nativeExecutionInput as Record<string, unknown> : {};
const provider = input.provider && typeof input.provider === "object" ? input.provider as Record<string, unknown> : {};
return provider.kind === "acpx" && provider.agent === "antigravity" && provider.mode === "swarm" ? ANTIGRAVITY_CLI_QUOTA_SCOPE : null;
}
function quotaScopeEvidenceFilter(scope: string | null) {
// The same derivation as runProviderQuotaScope, in SQL, so old swarm evidence holds only swarms.
const executed = sql`${heartbeatRuns.runnerProfileJson} -> 'nativeExecutionInput' -> 'provider'`;
const recorded = sql`coalesce(${heartbeatRuns.contextSnapshot} ->> ${PROVIDER_QUOTA_SCOPE_CONTEXT_KEY},
case when ${executed} ->> 'kind' = 'acpx' and ${executed} ->> 'agent' = 'antigravity' and ${executed} ->> 'mode' = 'swarm'
then ${ANTIGRAVITY_CLI_QUOTA_SCOPE} end)`;
return scope === null ? sql`${recorded} is null` : sql`${recorded} = ${scope}`;
}
/** The credential a run used, from the account it recorded when it started. */
export function runProviderLimitCredential(contextSnapshot: unknown): ProviderLimitCredential {
const grantId = recordedGrantId(contextSnapshot);
return grantId ? { kind: "grants", grantIds: [grantId] } : { kind: "host" };
}
function recordedGrantId(contextSnapshot: unknown): string | null {
const snapshot = contextSnapshot && typeof contextSnapshot === "object" ? contextSnapshot as Record<string, unknown> : {};
const connection = snapshot.aiConnection && typeof snapshot.aiConnection === "object"
? snapshot.aiConnection as Record<string, unknown> : {};
return typeof connection.grantId === "string" && UUID_PATTERN.test(connection.grantId) ? connection.grantId : null;
}
/**
* Whether evidence recorded on `evidenceGrantId` (null: the host's account)
* still describes the credential the agent would use now.
*/
function evidenceApplies(evidenceGrantId: string | null, credential: ProviderLimitCredential, activeGrantIds: ReadonlySet<string>) {
if (evidenceGrantId === null) return credential.kind === "host";
if (!activeGrantIds.has(evidenceGrantId)) return false;
if (credential.kind === "grants") return credential.grantIds.includes(evidenceGrantId);
return credential.kind === "unresolved";
}
/** Narrows the evidence read to the checked credential, so other accounts never crowd it out. */
function credentialEvidenceFilter(credential: ProviderLimitCredential) {
const recorded = sql`${heartbeatRuns.contextSnapshot} -> 'aiConnection' ->> 'grantId'`;
if (credential.kind === "host") return [sql`${recorded} is null`];
if (credential.kind === "grants") return [inArray(recorded, [...credential.grantIds])];
return [];
}
/**
* Whether any recent run of the agent recorded a provider limit, on any
* account. Without one no account can be held, so callers skip resolving the
* account the next run would use. Never decides that a limit applies.
*/
export async function agentHasProviderLimitEvidence(db: Db, input: {
companyId: string; agentId: string; runId?: string; now: Date;
}): Promise<boolean> {
const [row] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.agentId, input.agentId),
gte(heartbeatRuns.startedAt, new Date(input.now.getTime() - NATIVE_PROVIDER_LIMIT_WINDOW_MS)),
...(input.runId ? [ne(heartbeatRuns.id, input.runId)] : []),
or(
inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES),
inArray(sql<string>`${heartbeatRuns.resultJson} #>> '{providerFailure,category}'`, PROVIDER_LIMIT_CATEGORIES),
),
)).limit(1);
return Boolean(row);
}
export type AgentProviderLimitCooldown = {
/** When the agent's provider allowance is expected to return. */
resetAt: Date;
/** False when no reset was reported and the default cooldown applies. */
resetReported: boolean;
category: string;
/** The run whose failure recorded the latest reset. */
sourceRunId: string | null;
/** The connection grant the limit was reported on; null for the host's own account. */
grantId: string | null;
};
/**
* The latest known provider limit for this agent's credential, from the
* current failure or from the agent's recent runs on that same credential. A
* later successful run on the credential clears older evidence. Evidence from
* another credential, or from a revoked or removed one, never applies.
*/
export async function agentProviderLimitCooldown(db: Db, input: {
companyId: string;
agentId: string;
/** Excluded from the evidence; the caller supplies its own failure. */
runId?: string;
failure?: ProviderFailure | null;
/** The credential being checked. The caller's failure was reported on it. */
credential: ProviderLimitCredential;
/** The quota scope being checked (see PROVIDER_QUOTA_SCOPE_CONTEXT_KEY); null or absent is the default quota. */
quotaScope?: string | null;
now: Date;
}): Promise<AgentProviderLimitCooldown | null> {
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null;
const now = input.now.getTime();
let latest = limitEvidence(input.failure ?? null, input.now, input.runId ?? null);
const rows = await db
.select({
id: heartbeatRuns.id,
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
observedAt: sql<Date>`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.updatedAt})`.mapWith(heartbeatRuns.updatedAt),
providerFailure: sql<unknown>`${heartbeatRuns.resultJson} -> 'providerFailure'`,
retryNotBefore: sql<string | null>`${heartbeatRuns.resultJson} ->> 'retryNotBefore'`,
contextSnapshot: sql<unknown>`jsonb_build_object('aiConnection', ${heartbeatRuns.contextSnapshot} -> 'aiConnection')`,
})
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.agentId, input.agentId),
gte(heartbeatRuns.startedAt, new Date(now - NATIVE_PROVIDER_LIMIT_WINDOW_MS)),
...(input.runId ? [ne(heartbeatRuns.id, input.runId)] : []),
...credentialEvidenceFilter(input.credential),
// Another quota's limits, and its successes, say nothing about this one.
quotaScopeEvidenceFilter(input.quotaScope ?? null),
or(
eq(heartbeatRuns.status, "succeeded"),
inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES),
inArray(sql<string>`${heartbeatRuns.resultJson} #>> '{providerFailure,category}'`, PROVIDER_LIMIT_CATEGORIES),
),
))
.orderBy(desc(sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.updatedAt})`))
.limit(LIMIT_EVIDENCE_ROWS);
const recordedGrantIds = [...new Set(rows.flatMap(row => recordedGrantId(row.contextSnapshot) ?? []))];
const activeGrantIds = new Set(recordedGrantIds.length === 0 ? [] : (await db
.select({ id: connectionGrants.id }).from(connectionGrants).where(and(
eq(connectionGrants.companyId, input.companyId),
inArray(connectionGrants.id, recordedGrantIds),
eq(connectionGrants.status, "active"),
))).map(row => row.id));
for (const row of rows) {
// Another credential's outcome says nothing about this one.
if (!evidenceApplies(recordedGrantId(row.contextSnapshot), input.credential, activeGrantIds)) continue;
// The provider accepted work after this point, so its allowance was restored.
if (row.status === "succeeded") break;
const failure = readProviderFailure(row.providerFailure);
// A newer billing refusal supersedes an older estimate or reported reset.
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, row.observedAt)) break;
let recorded = limitEvidence(failure, row.observedAt, row.id);
if (recorded === null && PROVIDER_LIMIT_ERROR_CODES.includes(row.errorCode ?? "")) {
const reset = row.retryNotBefore ? Date.parse(row.retryNotBefore) : Number.NaN;
recorded = Number.isFinite(reset)
? { resetAt: reset, resetReported: true, category: "quota_exhausted", sourceRunId: row.id }
: { resetAt: row.observedAt.getTime() + PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS, resetReported: false, category: "quota_exhausted", sourceRunId: row.id };
}
if (recorded) recorded.grantId = recordedGrantId(row.contextSnapshot);
if (recorded && (!latest || recorded.resetAt > latest.resetAt)) latest = recorded;
}
if (!latest || latest.resetAt <= now) return null;
return {
resetAt: new Date(Math.min(latest.resetAt, now + NATIVE_PROVIDER_LIMIT_WINDOW_MS)),
resetReported: latest.resetReported,
category: latest.category,
sourceRunId: latest.sourceRunId,
grantId: latest.grantId !== undefined ? latest.grantId
: input.credential.kind === "grants" && input.credential.grantIds.length === 1 ? input.credential.grantIds[0] : null,
};
}
/**
* Schedules a same-run bootstrap retry after a failure that provably came
* before provider work. The attempt budget stays with the coordinator; this
* adds exponential backoff and waits out a known provider limit.
*/
export async function planNativeStartupRetry(input: {
db: Db;
binding: { companyId: string; agentId: string; runId: string };
attempt: number;
retryable: boolean;
failure: ProviderFailure | null;
now: Date;
}): Promise<{ nextAttemptAt: Date | null; providerCooldownAt: Date | null }> {
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now))
return { nextAttemptAt: null, providerCooldownAt: null };
// Limit evidence only refines the schedule. A failed read must not stop the
// failure from settling, so the retry falls back to plain backoff.
const providerCooldownAt = await input.db
.select({ contextSnapshot: heartbeatRuns.contextSnapshot, runnerProfileJson: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.binding.companyId), eq(heartbeatRuns.id, input.binding.runId)))
.then(([run]) => agentProviderLimitCooldown(input.db, {
companyId: input.binding.companyId,
agentId: input.binding.agentId,
runId: input.binding.runId,
failure: input.failure,
// The failure was reported on the account this run started with.
credential: runProviderLimitCredential(run?.contextSnapshot),
quotaScope: runProviderQuotaScope(run?.contextSnapshot, run?.runnerProfileJson),
now: input.now,
})).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => {
logger.warn({ err: error, runId: input.binding.runId }, "native provider limit evidence unavailable");
return null;
});
if (!input.retryable) return { nextAttemptAt: null, providerCooldownAt };
// Persisted with the failure, so a restart keeps the same jitter.
const sample = createHash("sha256").update(`${input.binding.runId}:${input.attempt}`)
.digest().readUInt32BE(0) / 0xffffffff;
const from = Math.max(input.now.getTime(), providerCooldownAt?.getTime() ?? 0);
return {
nextAttemptAt: new Date(from + infrastructureRetryDelayMs(input.attempt, sample)),
providerCooldownAt,
};
}
export function nativeStartupRetryExhaustedAction(attempts: number, providerCooldownAt: Date | null) {
return `Provider startup failed on ${attempts} attempts before any provider work began. Automatic retries are stopped.${
providerCooldownAt ? ` The provider usage limit for this agent is expected to reset at ${providerCooldownAt.toISOString()}.` : ""
} Check the agent's AI connection and provider usage, then retry the task.`;
}
export function nativeStartupRetryWait(providerCooldownAt: Date | null) {
return providerCooldownAt ? ` after the provider usage limit resets at ${providerCooldownAt.toISOString()}` : "";
}