Merge origin/master into feat/antigravity-swarm-command

Resolve the recovery service import conflict by keeping both the swarm
refusal code (non-retryable continuation) and master's dependency-wake
circuit breaker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 15:31:24 -06:00
commit 6f36e2a24a
139 files changed
+13035 -5187

No files matched your search

@@ -14,8 +14,15 @@ import { instanceSettingsService } from "../instance-settings.js";
import { issueService } from "../issues.js";
import * as nativeResponseNotifications from "../native-response-presentation-notifications.js";
import { compactRunLogChunk } from "../heartbeat/run-log.js";
import { CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON } from "../heartbeat-run-summary.js";
const runLogReads = vi.hoisted(() => [] as unknown[]);
const presentationAuthorization = vi.hoisted(() => ({ override: null as string | null }));
vi.mock("../chat-run-publications.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../chat-run-publications.js")>();
return { ...actual, resolveChatRunPresentationAuthorizationReason: (async (...args: Parameters<typeof actual.resolveChatRunPresentationAuthorizationReason>) =>
presentationAuthorization.override ?? actual.resolveChatRunPresentationAuthorizationReason(...args)) as typeof actual.resolveChatRunPresentationAuthorizationReason };
});
vi.mock("../run-log-store.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../run-log-store.js")>();
return { ...actual, getRunLogStore: () => {
@@ -703,6 +710,78 @@ describe.skipIf(!support.supported)("committed Agent Chat reply recovery", () =>
expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply })]);
expect((await issue(f.issueId)).conversationAgentId).toBeNull();
});
it.each([
["done", { source: "chat:github" }],
["needs_review", { source: "chat:github" }],
["done", { source: "automation", externalChatContinuation: true }],
] as const)("publishes an external-chat task's %s reply when copy-back failure skipped the live path (%j)", async (disposition, context) => {
// A run woken by an external chat message reaches its accepted final reply,
// then workspace copy-back fails, so the live completion path never posts
// it. Presentation recovery must still put that reply on the task.
const f = await fixture(false, { disposition });
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, ...context } })
.where(eq(heartbeatRuns.id, f.runId));
const work = nativeResponsePresentationWork(db), entries = await work.load(f.input);
expect(entries).toEqual([expect.objectContaining({ id: f.runId })]);
await expect(work.check(entries[0])).resolves.toBeNull();
expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply, createdByRunId: f.runId })]);
const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.resultJson).toMatchObject({ presentationDecision: { reasonCodes: expect.arrayContaining(["committed_task_response_recovered"]) } });
expect((run.resultJson as Record<string, unknown>).responsePublication).not.toMatchObject({ state: "failed" });
expect(await work.load(f.input)).toEqual([]);
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false);
expect(await comments(f.runId)).toHaveLength(1);
});
it("posts a non-GitHub external-chat task reply once with the provider presentation authorization", async () => {
const f = await fixture(false);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:slack" } })
.where(eq(heartbeatRuns.id, f.runId));
presentationAuthorization.override = CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON;
try {
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(true);
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false);
} finally { presentationAuthorization.override = null; }
expect(await comments(f.runId)).toEqual([expect.objectContaining({ body: f.reply,
metadata: expect.objectContaining({ authorizationReason: CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON }) })]);
});
it.each([false, true])("reuses an external-chat task reply the live path saved without recording it (deleted=%s)", async deleted => {
const f = await fixture(false);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } })
.where(eq(heartbeatRuns.id, f.runId));
const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId,
createdByRunId: f.runId, body: f.reply, ...(deleted ? { deletedAt: new Date("2020-01-01T00:03:00Z") } : {}) }).returning();
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false);
expect(await comments(f.runId)).toEqual([saved]);
const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.resultJson).toMatchObject({ presentationDecision: { commentAction: "reuse", commentId: saved.id } });
expect(await nativeResponsePresentationWork(db).load(f.input)).toEqual([]);
});
it.each([false, true])("posts an external-chat task's final answer after an earlier progress comment (deleted=%s)", async deleted => {
const f = await fixture(false);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } })
.where(eq(heartbeatRuns.id, f.runId));
const [progress] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId,
createdByRunId: f.runId, body: "Looking into the review comment now.",
...(deleted ? { deletedAt: new Date("2020-01-01T00:03:00Z") } : {}) }).returning();
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(true);
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false);
const saved = await comments(f.runId);
expect(saved).toHaveLength(2);
expect(saved).toEqual(expect.arrayContaining([progress, expect.objectContaining({ body: f.reply, deletedAt: null })]));
});
it("reuses the summary the live path saved when the final message is a structured result", async () => {
const summary = "A completed hire, with its final message preserved separately.";
const reply = JSON.stringify({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary });
const f = await fixture(false, { reply });
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentId: f.wakeId, source: "chat:github" } })
.where(eq(heartbeatRuns.id, f.runId));
const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId,
createdByRunId: f.runId, body: summary }).returning();
await expect(recoverCommittedNativeChatResponse(db, f.input)).resolves.toBe(false);
expect(await comments(f.runId)).toEqual([saved]);
const [run] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.resultJson).toMatchObject({ presentationDecision: { commentAction: "reuse", commentId: saved.id } });
});
it("recovers a deferred review reply once without resolving the review or rerunning work", async () => {
const f = await fixture(false, { disposition: "needs_review" });
const before = await issue(f.issueId);
@@ -137,6 +137,20 @@ describe.skipIf(!support.supported)("blocked task reply after a retried workspac
expect(await comments(f.issueId)).toHaveLength(1);
});
it("reuses a channel task's blocked reply that the live path saved without recording it", async () => {
const f = await blockedRun({ source: "chat:slack", finalReply: true });
await retryCopyBack(f.runId, { skipNativeResponsePresentation: true });
const [saved] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, authorAgentId: f.agentId,
createdByRunId: f.runId, body: finalReply }).returning();
const work = nativeResponsePresentationWork(db);
const [entry] = await work.load({ companyId: f.companyId, issueId: f.issueId });
expect(entry).toMatchObject({ id: f.runId });
await expect(work.check(entry)).resolves.toBeNull();
expect(await comments(f.issueId)).toEqual([saved]);
expect(((await run(f.runId)).resultJson as Record<string, any>).presentationDecision)
.toMatchObject({ commentAction: "reuse", commentId: saved.id });
});
it("does not present a stale blocker after a later status decision or once the task moved on", async () => {
const f = await blockedRun();
await retryCopyBack(f.runId, { skipNativeResponsePresentation: true });
@@ -6,6 +6,8 @@ import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embed
import { agentProviderLimitCooldown, planNativeStartupRetry } from "./native-startup-retry.js";
const HOUR_MS = 60 * 60_000;
/** These agents sign in with the host's own account. */
const HOST = { kind: "host" } as const;
const DAY_MS = 24 * HOUR_MS;
/** Claude ACP wording for an exhausted weekly allowance, such as "resets Nov 10, 3pm (UTC)". */
@@ -71,7 +73,7 @@ describe("native provider limit cooldown", () => {
it("holds an agent until a dated weekly-limit reset instead of the one-hour default", async () => {
const resetAt = new Date(Math.ceil((Date.now() + 20 * HOUR_MS) / HOUR_MS) * HOUR_MS);
const agentId = await limitedAgent(resetAt);
expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() }))
expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() }))
.toMatchObject({ resetAt, resetReported: true, category: "quota_exhausted" });
});
@@ -85,7 +87,7 @@ describe("native provider limit cooldown", () => {
category: "quota_exhausted", providerCode: "insufficient_quota",
message: "Check your plan and billing details.", retryability: "requires_action",
} } });
expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })).toBeNull();
expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() })).toBeNull();
});
it("keeps the default cooldown for a rate limit without a reset", async () => {
@@ -94,7 +96,7 @@ describe("native provider limit cooldown", () => {
schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
category: "rate_limit", message: "Try again later.", retryability: "unknown",
} } }).where(eq(heartbeatRuns.agentId, agentId));
expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() }))
expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() }))
.toMatchObject({ resetReported: false, category: "rate_limit" });
});
@@ -111,7 +113,7 @@ describe("native provider limit cooldown", () => {
it("re-checks a dated reset days away within one day", async () => {
const agentId = await limitedAgent(new Date(Math.ceil((Date.now() + 3 * DAY_MS) / HOUR_MS) * HOUR_MS));
const now = new Date();
const cooldown = await agentProviderLimitCooldown(db, { companyId, agentId, now });
const cooldown = await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now });
expect(cooldown).toMatchObject({ resetReported: true });
expect(cooldown!.resetAt.getTime()).toBe(now.getTime() + DAY_MS);
});
@@ -1210,8 +1210,12 @@ async function recoverCommittedNativeChatResponseInScope(
&& run.contextSnapshot.conversationSessionGeneration === issue.conversationSessionGeneration;
// A deferred ordinary-task review still needs its recorded final reply.
// Publishing that reply must not resolve the interaction or the task.
const ordinaryTaskReply = (!conversation || currentConversation) &&
!isExternalChatPresentationContext(run.contextSnapshot) &&
// A task woken by an external chat message (for example a GitHub review
// comment) gets the same final reply as on the live completion path,
// which a post-result failure such as copy-back can skip.
const externalChatContext = isExternalChatPresentationContext(run.contextSnapshot);
const externalChatTaskReply = !conversation && externalChatContext;
const ordinaryTaskReply = (!conversation || (currentConversation && !externalChatContext)) &&
((result.reportedWorkDisposition === "done" && terminal.reportedWorkDisposition === "done") ||
(!conversation && result.reportedWorkDisposition === "needs_review" && terminal.reportedWorkDisposition === "needs_review") ||
// A conversation turn can yield while an approval, an execution
@@ -1223,9 +1227,10 @@ async function recoverCommittedNativeChatResponseInScope(
terminal.turnTerminalState === "completed" &&
(ordinaryTaskReply || blockedTaskReply);
const replyAuthorization = taskReplyEligible ? await resolveChatRunPresentationAuthorizationReason(tx, input) : null;
const externalChatReply = blockedTaskReply &&
const externalChatBlockedReply = blockedTaskReply &&
isExternalChatPresentationContext(run.contextSnapshot, replyAuthorization === CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON);
if (taskReplyEligible && replyAuthorization && (blockedTaskReply || replyAuthorization === "internal_agent_write")) {
if (taskReplyEligible && replyAuthorization &&
(blockedTaskReply || externalChatTaskReply || replyAuthorization === "internal_agent_write")) {
const rows = await tx.select({ seq: heartbeatRunEvents.seq, payload: heartbeatRunEvents.payload })
.from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, input.companyId),
@@ -1259,7 +1264,8 @@ async function recoverCommittedNativeChatResponseInScope(
eq(issueComments.issueId, input.issueId),
eq(issueComments.createdByRunId, run.id),
)).orderBy(desc(issueComments.createdAt), desc(issueComments.id));
const resolved = resolveHeartbeatRunResponse({
const existingComment = findHeartbeatRunCompletionComment(comments, run.resultJson);
const responseInput = {
resultJson: { ...record(run.resultJson), nativeResult: result },
nativeConversationFinalResponse: conversation,
// The same answered rule as live run completion.
@@ -1267,9 +1273,20 @@ async function recoverCommittedNativeChatResponseInScope(
db: tx, ...input, finalizationPhase: coordinator.phase, finalizationReasonCode: decision.reasonCode,
}),
interactionOwnsResponse: conversation && await hasChatRunOwnedProviderInteraction(tx, input),
existingComment: findHeartbeatRunCompletionComment(comments, run.resultJson),
existingComment,
finalAgentMessage,
preferFinalResponseOverExistingComment: externalChatReply,
};
// An external-chat reply presents its final answer, as on the live
// path, over an earlier run comment such as a progress note. A saved
// copy of the text that answer resolves to, including a deleted one, is
// reused instead, so recovery never posts the same reply twice.
const preferredText = externalChatTaskReply || externalChatBlockedReply
? resolveHeartbeatRunResponse({ ...responseInput, existingComment: null, preferFinalResponseOverExistingComment: true }).text
: null;
const resolved = resolveHeartbeatRunResponse({
...responseInput,
preferFinalResponseOverExistingComment: Boolean(preferredText) &&
existingComment?.body.trim() !== preferredText?.trim(),
});
if (resolved.decision.commentAction === "reuse" && typeof resolved.decision.commentId === "string") {
// The reply is already on the task (for example, the live path wrote
@@ -1039,7 +1039,7 @@ describe("native provider startup retry", () => {
await failStartup(seeded, sessionOpenFailure());
const state = await read(seeded);
expect(state.coordinator.failureDetail).toMatchObject({ providerCooldownAt: expected.toISOString() });
expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() }))
expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: { kind: "host" }, now: new Date() }))
.toMatchObject({ resetAt: expected, resetReported: true });
});
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { and, desc, eq, gte, inArray, ne, or, sql } from "drizzle-orm";
import { heartbeatRuns, type Db } from "@paperclipai/db";
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";
@@ -14,7 +14,7 @@ const PROVIDER_LIMIT_ERROR_CODES = ["native_provider_usage_limit", "provider_quo
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 };
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;
@@ -28,6 +28,74 @@ function limitEvidence(failure: ProviderFailure | null, observedAt: Date, source
: { 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 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;
@@ -36,11 +104,15 @@ export type AgentProviderLimitCooldown = {
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, from the current failure or
* from the agent's recent runs. A later successful run clears older evidence.
* 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;
@@ -48,6 +120,8 @@ export async function agentProviderLimitCooldown(db: Db, input: {
/** 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;
now: Date;
}): Promise<AgentProviderLimitCooldown | null> {
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null;
@@ -61,6 +135,7 @@ export async function agentProviderLimitCooldown(db: Db, input: {
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(
@@ -68,6 +143,7 @@ export async function agentProviderLimitCooldown(db: Db, input: {
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),
or(
eq(heartbeatRuns.status, "succeeded"),
inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES),
@@ -76,7 +152,16 @@ export async function agentProviderLimitCooldown(db: Db, input: {
))
.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);
@@ -89,6 +174,7 @@ export async function agentProviderLimitCooldown(db: Db, input: {
? { 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;
@@ -97,6 +183,8 @@ export async function agentProviderLimitCooldown(db: Db, input: {
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,
};
}
@@ -117,13 +205,18 @@ export async function planNativeStartupRetry(input: {
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 agentProviderLimitCooldown(input.db, {
companyId: input.binding.companyId,
agentId: input.binding.agentId,
runId: input.binding.runId,
failure: input.failure,
now: input.now,
}).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => {
const providerCooldownAt = await input.db
.select({ contextSnapshot: heartbeatRuns.contextSnapshot }).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),
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;
});
@@ -192,6 +192,13 @@ if sys.argv[1] != "completion":
const context = { skills: [{ key: "assigned", runtimeName: "assigned", versionId: "version-1", bundle }] } as any;
expect(await readAssignedSkill(context, { skill: "assigned" })).toMatchObject({ versionId: "version-1", text: "# Assigned skill\nUse the pinned instructions." });
await expect(readAssignedSkill(context, { skill: "not-assigned" })).rejects.toThrow("not_assigned");
const saved = { skills: [{ key: "company/company-1/qa-saved-skill", runtimeName: "qa-saved-skill--33910b3ce6", versionId: "version-1", bundle }] } as any;
expect(await readAssignedSkill(saved, { skill: "qa-saved-skill" })).toMatchObject({ skill: "company/company-1/qa-saved-skill", versionId: "version-1" });
expect(await readAssignedSkill(saved, { skill: "/qa-saved-skill" })).toMatchObject({ skill: "company/company-1/qa-saved-skill" });
expect(await readAssignedSkill(saved, { skill: " /QA-Saved-Skill " })).toMatchObject({ skill: "company/company-1/qa-saved-skill" });
const twins = { skills: [saved.skills[0], { ...saved.skills[0], key: "paperclipai/paperclip/qa-saved-skill", runtimeName: "qa-saved-skill--aa" }] } as any;
await expect(readAssignedSkill(twins, { skill: "qa-saved-skill" })).rejects.toThrow("not_assigned");
expect(await readAssignedSkill(twins, { skill: "qa-saved-skill--aa" })).toMatchObject({ skill: "paperclipai/paperclip/qa-saved-skill" });
await expect(readAssignedSkill(context, { skill: "assigned", path: "../private" })).rejects.toThrow();
await expect(readAssignedSkill(context, { skill: "assigned", path: "not-pinned.txt" })).rejects.toThrow("not_pinned");
await expect(readAssignedSkill({ ...context, skills: [{ ...context.skills[0], bundle: { ...bundle, manifestDigest: createHash("sha256").update("different").digest("hex") } }] }, { skill: "assigned" })).rejects.toThrow("manifest_digest");
@@ -4,6 +4,7 @@ import { constants, existsSync } from "node:fs";
import * as fs from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { resolvePaperclipSkillReference } from "@paperclipai/adapter-utils/server-utils";
import type { NativeRuntimeContextSnapshot } from "../../vendor/paperclip-runner/index.js";
import { taskDocumentKeySchema } from "../../vendor/paperclip-runner/index.js";
import { openRunnerApiWorkspaceFile, openRunnerWorkspaceFile } from "./runner-api-files.js";
@@ -122,7 +123,8 @@ async function readFilePage(file: string, offset: number) {
}
export async function readAssignedSkill(context: NativeRuntimeContextSnapshot, raw: unknown) {
const args = RUNNER_BRIDGE_SCHEMAS.get("read_assigned_skill")!.parse(raw) as { skill: string; path: string; offset: number };
const skill = context.skills.find(skill => skill.key === args.skill || skill.runtimeName === args.skill);
const key = resolvePaperclipSkillReference(args.skill, context.skills);
const skill = key ? context.skills.find(entry => entry.key === key) : undefined;
if (!skill) throw new Error("runner_skill_not_assigned");
const manifestText = await fs.readFile(path.join(path.dirname(path.dirname(skill.bundle.rootPath)), "manifests", `${skill.bundle.digest}.json`), "utf8");
if (digest(manifestText) !== skill.bundle.manifestDigest) throw new Error("runner_skill_manifest_digest_mismatch");