Skip to content
Merged
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
4 changes: 4 additions & 0 deletions sdk/typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,10 @@ Deep discovery retains its enforced deadline, with a default and maximum of
### Progress and cost

Use `onProgress` for scan progress and `onCost` for cost updates.
Use `onUsageObservation` for the last reported token measurement time
(`tokensUpdatedAt`) and account-wide allowance readings (`accountRateLimits`).
Each reading includes its own `observedAt` timestamp and the percentage used in
each reported window. A limit-only update can arrive before any token measurement.

Follow scans with `onWorkerEvent` and `onReconnect`. `onWorkerEvent` reports
persisted worker sessions discovered by the SDK's existing session tracker,
Expand Down
8 changes: 8 additions & 0 deletions sdk/typescript/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,14 @@ work could not be measured, including in-flight turns or missing earlier attempt
The parent can continue after report completion, so final CLI tokens can exceed
the saved measurement window.

During a scan, progress shows when Codex reported the displayed token and cost
totals, in UTC. If the report has no timestamp, progress says so.
In-flight requests may add tokens and cost after that time. When Codex supplies
account allowance, progress shows the percentage used in each reported window
and the time of that reading. On a short terminal, resize the window or press
`d` to scroll through the full readings in Details. With ChatGPT authentication,
progress also says when Codex has yet to report allowance.

`usage.accountRateLimits` saves the latest observed account-wide readings with
their own timestamps, window durations, and reset times. These are historical
observations, not a live allowance check or scan-only consumption. Empty readings
Expand Down
1 change: 1 addition & 0 deletions sdk/typescript/scripts/package-dist-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ const distModules = [
"scan-history-renderer",
"scan-inputs",
"scan-logs",
"scan-usage-display",
"security-policy",
"security-policy-cli",
"security-policy-diff",
Expand Down
8 changes: 8 additions & 0 deletions sdk/typescript/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ import {
ScanCostTracker,
type ScanCost,
type ScanSessionEvent,
type ScanUsageObservation,
type ScanWorkerEvent,
} from "./cost.js";
import type { ScanTokenUsage } from "./cost-model.js";
Expand Down Expand Up @@ -339,6 +340,8 @@ export interface ScanOptions extends ScanSettings {
onCost?: (cost: Readonly<ScanCost>, maxCostUsd?: number) => void;
/** Observed tokens, including models without a price estimate. */
onUsage?: (usage: Readonly<ScanTokenUsage>) => void;
/** The last reportable token total's measurement time and latest account limits from this scan's sessions. */
onUsageObservation?: (observation: ScanUsageObservation) => void;
onBudgetApproaching?: (
budget: ScanBudget,
) => number | undefined | Promise<number | undefined>;
Expand Down Expand Up @@ -587,6 +590,7 @@ type ScanObserverName =
| "onAuthentication"
| "onCost"
| "onUsage"
| "onUsageObservation"
| "onOutputArchived"
| "onOutputDirReady"
| "onScanRegistered"
Expand Down Expand Up @@ -2367,6 +2371,10 @@ export class CodexSecurity {
options.onUsage === undefined
? undefined
: (usage) => notifyObserver(options, "onUsage")(usage),
onUsageObservation:
options.onUsageObservation === undefined
? undefined
: notifyObserver(options, "onUsageObservation"),
onActivity:
options.onActivity === undefined
? undefined
Expand Down
53 changes: 52 additions & 1 deletion sdk/typescript/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,13 @@ import {
type HistoryCommand,
} from "./scan-history-renderer.js";
import { ScanDashboard } from "./scan-dashboard.js";
import {
ACCOUNT_LIMITS_UNAVAILABLE,
formatAccountLimits,
formatUsageFreshness,
isChatGptAuthentication,
USAGE_TIME_UNAVAILABLE,
} from "./scan-usage-display.js";
import {
policyDisplayData,
runPolicyCommand,
Expand Down Expand Up @@ -5100,10 +5107,12 @@ export async function main(
componentName,
event,
options.showCost || settings.maxCostUsd !== undefined,
settings.auth,
);
if (line !== null) errorOutput.write(line);
}
: (event) => dashboard?.recordComponentEvent(event),
: (event) =>
dashboard?.recordComponentEvent(event, settings.auth),
onDeduplicationStarted: () => {
if (dashboard !== null)
dashboard.showComponents("Combining duplicate findings");
Expand Down Expand Up @@ -9158,6 +9167,8 @@ async function executeScan(
let deepConsolidating = false;
let runningCost: Readonly<ScanCost> | null = null;
let runningUsage: Readonly<ScanTokenUsage> | null = null;
let usageFreshness: string | null = null;
let accountLimits: string | null = null;
let maxCostUsd = arguments_.maxCostUsd;
const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
let phase: string | null = null;
Expand Down Expand Up @@ -9392,6 +9403,9 @@ async function executeScan(
input: scanInput,
onInterrupt,
});
dashboard.setChatGptAuth(
isChatGptAuthentication(selectedAuthentication, auth),
);
}
const scope = scanScope(arguments_);
const runningMessage = (): string => {
Expand Down Expand Up @@ -9426,6 +9440,11 @@ async function executeScan(
if (showCost && runningCost !== null) {
details.push(`Cost: ${formatScanCost(runningCost)}`);
}
if (tokens !== null)
details.push(usageFreshness ?? USAGE_TIME_UNAVAILABLE);
if (accountLimits !== null) details.push(diagnosticValue(accountLimits));
else if (isChatGptAuthentication(selectedAuthentication, auth))
details.push(ACCOUNT_LIMITS_UNAVAILABLE);
return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
};
if (dashboard === null) {
Expand Down Expand Up @@ -9463,6 +9482,22 @@ async function executeScan(
archiveExisting: arguments_.archiveExisting,
parentScanId: arguments_.parentScanId,
expectedPluginVersion: arguments_.expectedPluginVersion,
onUsageObservation: async (observation) => {
if (dashboard !== null) {
dashboard.setUsageObservation(observation);
return;
}
usageFreshness = formatUsageFreshness(observation);
accountLimits = formatAccountLimits(observation);
const priorUsage = runningUsage;
const priorCost = runningCost;
// Usage and cost callbacks render the same poll. Refresh here for a receipt alone.
await Promise.resolve();
if (runningUsage === priorUsage && runningCost === priorCost) {
progress?.stopTimer();
progress?.startTimer(runningMessage());
}
},
onUsage: async (usage) => {
runningUsage = usage;
if (dashboard !== null) {
Expand Down Expand Up @@ -9539,6 +9574,9 @@ async function executeScan(
},
onAuthentication: (authentication) => {
selectedAuthentication = authentication;
dashboard?.setChatGptAuth(
isChatGptAuthentication(authentication, auth),
);
const bedrock =
providerOptions.provider === "amazon-bedrock" ||
authentication.method === "aws_credentials";
Expand Down Expand Up @@ -10669,7 +10707,13 @@ function componentScanEventLine(
componentName: string,
event: ComponentScanEvent,
showCost: boolean,
requestedAuth?: ScanAuthMode,
): string | null {
if (event.type === "authentication") {
return isChatGptAuthentication(event.value, requestedAuth)
? `codex-security: ${componentName} | ${ACCOUNT_LIMITS_UNAVAILABLE}\n`
: null;
}
if (event.type === "progress") {
const progress = event.value;
const count = scanProgressCount(progress);
Expand All @@ -10681,6 +10725,13 @@ function componentScanEventLine(
? null
: `codex-security: ${componentName} | Tokens: ${tokens}\n`;
}
if (event.type === "usage-observation") {
const details = [
formatUsageFreshness(event.value) ?? USAGE_TIME_UNAVAILABLE,
formatAccountLimits(event.value),
].filter((detail) => detail !== null);
return `codex-security: ${componentName} | ${diagnosticValue(details.join(" | "))}\n`;
}
if (event.type !== "cost" || !showCost) return null;
return `codex-security: ${componentName} | Cost: ${formatScanCost(event.value)}\n`;
}
Expand Down
13 changes: 12 additions & 1 deletion sdk/typescript/src/component-scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
scanAuthentication,
selectedScanEnvironment,
type CodexSecuritySurface,
type ScanAuthentication,
type ScanOptions,
} from "./api.js";
import {
Expand All @@ -22,7 +23,11 @@ import {
scanModelProvider,
type CodexSecurityConfig,
} from "./config.js";
import type { ScanCost, ScanSessionEvent } from "./cost.js";
import type {
ScanCost,
ScanSessionEvent,
ScanUsageObservation,
} from "./cost.js";
import type { ScanTokenUsage } from "./cost-model.js";
import { readThreatModelPath } from "./artifact-export.js";
import { errorMessage } from "./errors.js";
Expand Down Expand Up @@ -81,11 +86,13 @@ export interface ComponentReceipt {
}

type ComponentScanUpdate =
| { type: "authentication"; value: ScanAuthentication }
| { type: "progress"; value: ScanProgress }
| { type: "activity"; value: ScanActivity }
| { type: "session"; value: ScanSessionEvent }
| { type: "cost"; value: Readonly<ScanCost> }
| { type: "usage"; value: Readonly<ScanTokenUsage> }
| { type: "usage-observation"; value: Readonly<ScanUsageObservation> }
| { type: "workers"; value: ScanWorkerStatus }
| { type: "warning"; value: string };

Expand Down Expand Up @@ -217,11 +224,15 @@ export async function runComponentScans(
options.onScanEvent === undefined
? {}
: {
onAuthentication: (value) =>
emit({ type: "authentication", value }),
onProgress: (value) => emit({ type: "progress", value }),
onActivity: (value) => emit({ type: "activity", value }),
onSessionEvent: (value) => emit({ type: "session", value }),
onCost: (value) => emit({ type: "cost", value }),
onUsage: (value) => emit({ type: "usage", value }),
onUsageObservation: (value) =>
emit({ type: "usage-observation", value }),
onWorkerStatus: (value) => emit({ type: "workers", value }),
onWarning: (value) => emit({ type: "warning", value }),
};
Expand Down
Loading
Loading