Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions apps/account-directory/src/cloud/accountState.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PHONE_CREDIT_MILLI_PER_MINUTE, liveUsedWithPhones } from "./credits";
import { sponsoredAccountState } from "./gravity";
import { cardRulesAccountState } from "./sponsoredCards";
import { freeModelsAccountState } from "./freeModels";
import { smallUsesNoHours, smallUsesNoHoursToday } from "./sponsoredSmall";
import { pricingAccountState } from "./adPrice";
Expand Down Expand Up @@ -123,19 +124,29 @@ export async function buildAccountState(env: CloudEnv, userId: string, now: numb
// account, and `sponsored` only on Free, by today's Free rule: it keeps its ads there (its card requests are
// proofs, and keep Small as free as today), and never shows an ad on a paid plan. The catalog's numbers are real.
const sponsored = pricing && !knowsV3 && shownPlan !== "free" ? undefined : sponsoredRead;
// ADE Free Models (`freeModels.ts`), any plan: left out while their switch doesn't reach the account or a key is missing.
const freeModels = await freeModelsAccountState(env, account, who, now).catch((error: unknown) => {
reportCloudFailure("cloud.free_models.state_failed", { userId, message: error instanceof Error ? error.message : "unknown" });
return undefined;
});
const macShown = await macReaches(env, userId).catch((error: unknown) => {
reportCloudFailure("cloud.mac_switch_read_failed", { message: error instanceof Error ? error.message : "unknown" });
return false;
});
// Three independent reads at once. ADE Free Models (`freeModels.ts`), any plan: left out while their switch
// doesn't reach the account or a key is missing. Timed and routed cards (`sponsoredCards.ts`): left out while
// neither setting reaches the account, or the account gets neither sponsored cards nor Free Models.
const [freeModels, cardRules, macShown] = await Promise.all([
freeModelsAccountState(env, account, who, now).catch((error: unknown) => {
reportCloudFailure("cloud.free_models.state_failed", { userId, message: error instanceof Error ? error.message : "unknown" });
return undefined;
}),
cardRulesAccountState(env, userId).catch((error: unknown) => {
reportCloudFailure("cloud.sponsored.card_rules_failed", { message: error instanceof Error ? error.message : "unknown" });
return undefined;
}),
macReaches(env, userId).catch((error: unknown) => {
reportCloudFailure("cloud.mac_switch_read_failed", { message: error instanceof Error ? error.message : "unknown" });
return false;
}),
]);
const sponsoredCards = sponsored || freeModels ? cardRules : undefined;
return {
...(pricing && knowsV3 ? { pricing } : {}),
...(sponsored ? { sponsored } : {}),
...(freeModels ? { freeModels } : {}),
...(sponsoredCards ? { sponsoredCards } : {}),
// Under Pricing v3 the iPhone is 500 a minute, so an older app's minutes left stay right.
credits: { phoneMilliPerMinute: pricing ? PHONE_MILLI_PER_MINUTE_V3 : PHONE_CREDIT_MILLI_PER_MINUTE },
plan: shownPlan === "free" ? "free" : "paid",
Expand Down
20 changes: 20 additions & 0 deletions apps/account-directory/src/cloud/adPrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,26 @@ export async function noteOutsideAgentWork(env: GravityEnv, computer: Pick<Compu
}
}

/**
* Routed cards (`sponsoredCards.ts`): for each of these computers of the
* account, its price now (as the account read shows it, the brain's work while
* it is awake included), when its ad time ends (null: it has none), and
* whether it has two prices at all. Reads only; moves nothing.
*/
export async function adTimesOf(env: GravityEnv, account: AccountRow, computers: readonly ComputerRow[], now: number): Promise<Array<{ computer: ComputerRow; decision: PriceDecision; until: number | null; twoPrices: boolean }>> {
if (computers.length === 0) return [];
const { ctx } = await adContextFor(env, account);
if (!ctx.v3) return [];
const targets = await targetsOf(env, computers.map((computer) => computer.instance_id));
return computers.map((computer) => {
const rates = computerRatesMilli(computer, ctx);
const smallLook = isChargedSmall(rates);
const target = withStoredFirstProof(targets.get(computer.instance_id) ?? null, computer);
const awake = computer.awake_since != null && isMeteredStatus(computer.status) ? computer.awake_since : null;
return { computer, decision: decidePrice(target, ctx, awake, now, { smallLook }), until: adWindow(target, ctx, smallLook).until, twoPrices: rates.fullMilli !== rates.adMilli };
});
}

/** One computer on the price it has now, after its brain, an outside agent or a resize changed what decides it. */
export async function syncComputerPrice(env: GravityEnv, computer: Pick<ComputerRow, "instance_id" | "user_id">, now: number): Promise<void> {
const account = await env.DB.prepare("select * from cloud_accounts where user_id = ?").bind(computer.user_id).first<AccountRow>();
Expand Down
2 changes: 1 addition & 1 deletion apps/account-directory/src/cloud/computerStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const STATUS_CACHE_TTL_S = 15;
/** The longest run of agents a report may claim; anything past it is not a real count. */
const MAX_RUNNING_AGENTS = 500;
/** A report's clock may run this far ahead of the server's. */
const REPORT_CLOCK_SKEW_MS = 2 * 60_000;
export const REPORT_CLOCK_SKEW_MS = 2 * 60_000;
/** How long after a change the minute tick may record it: an event this much older than the row's change is still that change. */
const TICK_LAG_MS = 3 * 60_000;

Expand Down
75 changes: 71 additions & 4 deletions apps/account-directory/src/cloud/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,12 @@ export type CloudAccountState = {
* client shows none of them.
*/
freeModels?: CloudFreeModelsState;
/**
* Timed and routed cards (`sponsoredCards.ts`): sent only while the
* server's `gravity_timed_cards` or `gravity_routed_cards` setting reaches
* this account; absent, a client asks for cards as before.
*/
sponsoredCards?: CloudSponsoredCardRules;
/**
* Credits: `hours` is one balance of credits (the same numbers: a Medium
* computer uses one an hour), and the ADE Cloud iPhone draws from it at
Expand Down Expand Up @@ -4360,6 +4366,34 @@ export type CloudSponsoredState = {
* Each is display only: nothing of a card is ever sent to the agent.
*/
export type CloudSponsoredFormat = "below_reply" | "above_prompt" | "inline";
/**
* How a client asks for timed and routed cards (`CloudAccountState.sponsoredCards`).
* The server enforces every spacing with its own clock; these numbers only
* keep a client from asking when it would be refused.
*/
export type CloudSponsoredCardRules = {
/**
* A timed or routed card is asked for only after key or pointer input in
* the window this many minutes ago at most (a person's send counts).
*/
activeMinutes: number;
/**
* Present while timed cards reach the account: a running turn's card,
* docked above the prompt box (`phase: "timed"`), once this many minutes
* passed since the chat's last card request or sent message. A finished
* reply's ask and its proof then also wait for input (`activeMinutes`).
*/
timed?: { everyMinutes: number };
/**
* Present while routed cards reach the account: the chat that made a lane
* on its own cloud computer asks (`phase: "routed"`) whether a card for
* that lane's computer is owed. At most one timed or routed card per
* account every `gapMinutes`, across its chats and devices. Only the chats
* in `parentChats` ask: the ones that made a lane on a computer the account
* still has (at most 20, latest first).
*/
routed?: { gapMinutes: number; parentChats: string[] };
};
export const CLOUD_SPONSORED_FORMATS = ["below_reply", "above_prompt", "inline"] as const satisfies readonly CloudSponsoredFormat[];
/** The app a card shows in: each surface and format is its own Gravity placement. */
export type CloudSponsoredSurface = "desktop" | "web" | "ios";
Expand Down Expand Up @@ -4522,9 +4556,23 @@ export type CloudSponsoredAdRequest = {
* Models chat's meter over, but it counts no ad price proof, delivers no
* notice, and the client draws nothing of it. Absent: the ask at the
* reply's end (every rule again, the proof, then the kept answer, or a new
* request for a turn nobody asked for yet), as older apps ask.
* request for a turn nobody asked for yet), as older apps ask. After a
* send's no card, the reply's end asks Gravity once more with its own text.
*
* `timed` (`CloudSponsoredCardRules.timed`): while `turnId`'s turn runs and a
* person is there, a card docked above the prompt box. Every rule of the
* ask at the reply's end, the same proof and daily limits, under a key the
* server makes (`key` in the answer). Refused (`too_soon`, `retryInMs`)
* sooner than the setting's minutes after the chat's last card request or
* sent message, or the account's gap after its last timed or routed card.
*
* `routed` (`CloudSponsoredCardRules.routed`): `chatId` is a chat that made
* a lane on its own cloud computer. The server picks at most one such
* computer whose ad time is ending, checks the link itself, and the card
* counts as that computer's proof only (`routed` in the answer). `none_owed`
* when none is.
*/
phase?: "send";
phase?: "send" | "timed" | "routed";
/** The latest request and reply; at the send, the turn's newest message (after the previous reply, if any). */
messages: CloudSponsoredMessage[];
device: CloudSponsoredDevice;
Expand Down Expand Up @@ -4613,8 +4661,27 @@ export type CloudSponsoredHideRequest = { chatId: string; turnId: string };
* no ad before it) and `unverified` (the request came from the network of the
* account's own cloud computers: it doesn't count, `CloudFullPriceReason`).
*/
export type CloudSponsoredNoAdReason = "off" | "plan" | "country" | "consent" | "not_cloud" | "limit" | "no_fill" | "unavailable" | "notice" | "unverified";
export type CloudSponsoredAdAnswer = { ad: CloudSponsoredAd | null; reason?: CloudSponsoredNoAdReason };
export type CloudSponsoredNoAdReason = "off" | "plan" | "country" | "consent" | "not_cloud" | "limit" | "no_fill" | "unavailable" | "notice" | "unverified"
/** `timed`/`routed` only: asked sooner than the spacing allows (`retryInMs`). */
| "too_soon"
/** `routed` only: no lane of this chat needs a card now. */
| "none_owed";
export type CloudSponsoredAdAnswer = {
ad: CloudSponsoredAd | null;
reason?: CloudSponsoredNoAdReason;
/** `timed`/`routed`: the server's key for the card: hide it with this as `turnId` (and `routed.chatId` for a routed one). */
key?: string;
/** `too_soon`, `none_owed`: the earliest a new ask could get a card, in ms from now (the server's clock). */
retryInMs?: number;
/** `routed`: the lane whose computer the card keeps at the ad price. */
routed?: CloudSponsoredRouted;
};
export type CloudSponsoredRouted = {
/** The id the card is kept under (the lane's chat, or its launch when the lane has none): `CloudSponsoredHideRequest.chatId`. */
chatId: string;
instanceId: string;
laneName: string | null;
};

/** `POST /cloud/sponsored/index`: an agent on an ADE Cloud computer asks for a service the person needs. */
export type CloudSponsoredIndexRequest = {
Expand Down
2 changes: 1 addition & 1 deletion apps/account-directory/src/cloud/freeModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ const STATUS: Record<CloudFreeModelsErrorCode, number> = {
* them with the wait after them ("… Next try in 37 s.").
*/
/** A slowed account's (`free_models_no_cards`). */
const SLOWED_MESSAGE = "DAEX Free Models are slowed because no ad was asked for during a long stretch of work. Keep this chat on screen in DAEX; your next message there brings back full speed.";
const SLOWED_MESSAGE = "DAEX Free Models are slowed because no ad was asked for during a long stretch of work. Keep this chat on screen in DAEX; after this reply, your next message there brings back full speed.";
/** The account's minute (`free_models`). */
const ACCOUNT_MINUTE_MESSAGE = "DAEX Free Models are at this account's limit for the minute.";
/** Every account's minute together (`free_models_all`). */
Expand Down
Loading
Loading