Skip to content
Closed
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
10 changes: 5 additions & 5 deletions packages/void/src/cli/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ type PlatformVersionProbe =
| { kind: 'unknown' };

/**
* Returns whether `version` is older than MIN_PLATFORM_VERSION, or null when
* it is not a release version. A prerelease sorts before its release.
* Returns whether `version` is older than the release `minimumVersion`, or null
* when it is not a release version. A prerelease sorts before its release.
*/
function isOlderThanMinimumPlatform(version: string): boolean | null {
export function isOlderPlatformVersion(version: string, minimumVersion: string): boolean | null {
const actual = RELEASE_VERSION.exec(version);
const minimum = RELEASE_VERSION.exec(MIN_PLATFORM_VERSION)!;
const minimum = RELEASE_VERSION.exec(minimumVersion)!;
if (!actual) {
return null;
}
Expand Down Expand Up @@ -99,7 +99,7 @@ function assertSupportedPlatform(apiUrl: string, probe: PlatformVersionProbe): v
// comes from a hosted deployment that does not set PLATFORM_VERSION yet.
// Any other value that is not a release version comes from a custom or
// development build and cannot be ordered. Both pass.
if (version === 'hosted' || isOlderThanMinimumPlatform(version) !== true) {
if (version === 'hosted' || isOlderPlatformVersion(version, MIN_PLATFORM_VERSION) !== true) {
return;
}
throw new Error(
Expand Down
9 changes: 6 additions & 3 deletions packages/void/src/cli/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ const HELP_TREE: HelpTree = {
},
{
command: 'set <id>',
description: 'Edit a plan name, limits, or build instance size',
description: 'Edit a plan name, limits, build size, or AI Gateway logging default',
},
{
command: 'reset <id>',
Expand All @@ -356,7 +356,10 @@ const HELP_TREE: HelpTree = {
description: 'Remove an unused plan or move its accounts to a replacement',
},
{ command: 'default <id>', description: 'Choose the plan new accounts receive' },
{ command: 'sync', description: 'Continue pending account limit updates' },
{
command: 'sync',
description: 'Continue pending account limit and AI logging updates',
},
],
options: [
{
Expand All @@ -365,7 +368,7 @@ const HELP_TREE: HelpTree = {
},
{
command: '--file <path>',
description: 'Read plan settings and partial limits from JSON',
description: 'Read plan settings, partial limits, and aiLogging from JSON',
},
{
command: '--name <name>',
Expand Down
169 changes: 169 additions & 0 deletions packages/void/src/cli/operator-ai-logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { AI_LOGGING_SETTLE_MS } from '@void/platform/ai-logging';
import { cfAccessHeaders } from '../shared/cf-access.ts';
import { ensurePlatformAccessToken } from './cf-access.ts';
import { OperatorClientError } from './operator-client.ts';
import { sanitizeTerminalText } from './output.ts';
import { readPlatformDiscoveryResponse } from './platform-discovery.ts';

/** The first platform release with per-project AI logging settings. */
export const AI_LOGGING_PLATFORM_VERSION = '1.8.0';

type Fields = Record<string, unknown>;

function text(value: unknown): string {
return typeof value === 'string' ? sanitizeTerminalText(value) : '';
}

function record(value: unknown): Fields | null {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Fields) : null;
}

/** `14:03:20 UTC`, or null when the value is not a time. */
export function utcTime(value: unknown, offsetMs = 0): string | null {
const time = typeof value === 'string' ? Date.parse(value) : Number.NaN;
if (Number.isNaN(time)) {
return null;
}
return `${new Date(time + offsetMs).toISOString().slice(11, 19)} UTC`;
}

/** `plan "pro"`, naming the default plan an unknown plan ID follows. */
function planLabel(fields: Fields): string {
const plan = `plan "${text(fields.planId)}"`;
if (fields.planKnown === false) {
return `${plan} (not in catalog; uses default plan "${text(fields.defaultPlanId)}")`;
}
return plan;
}

/** Where the effective mode comes from, or null for a platform that does not say. */
function sourceText(fields: Fields): string | null {
if (typeof fields.planId !== 'string') {
return null;
}
const planDefault = `${planLabel(fields)} default: ${text(fields.planMode) || 'inherit'}`;
switch (fields.source) {
case 'project':
return `set on project; ${planDefault}`;
case 'plan':
return `from ${planLabel(fields)}`;
case 'gateway':
return `AI Gateway setting; ${planDefault}`;
default:
return null;
}
}

function effective(fields: Fields): string {
return text(fields.effective) || text(fields.mode);
}

function withSource(mode: string, fields: Fields): string {
const source = sourceText(fields);
return source ? `${mode} (${source})` : mode;
}

/** The `project ai-logging` result: the setting and when new requests follow it. */
export function aiLoggingChangeLines(projectId: string, result: Fields): Array<string> {
const lines = [
`AI logging for ${sanitizeTerminalText(projectId)}: ${withSource(effective(result), result)}`,
];
const expectedBy = utcTime(result.expectedBy);
if (expectedBy) {
lines.push(
`New AI requests are expected to follow it by ${expectedBy} (normally within 2 minutes).`,
);
}
return lines;
}

/** The `project ai-logging --plan` preview: current and new effective modes. */
export function aiLoggingPreviewLines(projectId: string, preview: Fields): Array<string> {
const previous = text(preview.previous);
const next = effective(preview);
const change = previous ? `${previous} → ${next}` : next;
return [
`AI logging for ${sanitizeTerminalText(projectId)}: ${withSource(change, preview)}`,
'No change was made. Run the command again without --plan to apply it.',
];
}

const STATES: Record<string, (fields: Fields) => string> = {
applied: () => 'applied',
pending: (fields) => {
const by = utcTime(fields.publishedAt, AI_LOGGING_SETTLE_MS);
return by ? `pending (expected by ${by})` : 'pending (normally within 2 minutes)';
},
pending_plan_publish: () => 'pending (the plan default is still being published)',
drift: (fields) => `drift (published: ${text(fields.published) || 'unknown value'})`,
unknown: () => 'state unknown (the published setting could not be read)',
};

/**
* `project show` line, such as `metadata (from plan "pro") — applied`, or null
* when the response has no AI logging data.
*/
export function aiLoggingStatusLine(value: unknown): string | null {
const fields = record(value);
if (!fields || typeof fields.mode !== 'string') {
return null;
}
const state =
typeof fields.state === 'string' && Object.hasOwn(STATES, fields.state)
? STATES[fields.state]
: undefined;
const summary = withSource(effective(fields), fields);
return `AI Gateway logging: ${state ? `${summary} — ${state(fields)}` : summary}`;
}

type DiscoveryProbe = { kind: 'version'; version: string } | { kind: 'missing' | 'unknown' };

async function probePlatformVersion(origin: string): Promise<DiscoveryProbe> {
ensurePlatformAccessToken(origin);
let response: Response;
try {
response = await fetch(`${origin}/.well-known/void-platform`, {
headers: { Accept: 'application/json', ...cfAccessHeaders(process.env, origin) },
redirect: 'manual',
signal: AbortSignal.timeout(15_000),
});
} catch {
return { kind: 'unknown' };
}
if (response.status === 404) {
await response.body?.cancel();
return { kind: 'missing' };
}
try {
return {
kind: 'version',
version: (await readPlatformDiscoveryResponse(origin, response)).platformVersion,
};
} catch {
return { kind: 'unknown' };
}
}

/**
* Refuses `project ai-logging` on a platform before AI logging settings existed.
* It reads the platform version instead of guessing from a 404, because "Project
* not found" is also a 404. When the version cannot be read, the request runs and
* reports its own error.
*/
export async function assertAiLoggingPlatform(origin: string): Promise<void> {
const probe = await probePlatformVersion(origin);
if (probe.kind === 'unknown') {
return;
}
if (probe.kind === 'version') {
const { isOlderPlatformVersion } = await import('./client.ts');
// "hosted" and development builds are not release versions and pass.
if (isOlderPlatformVersion(probe.version, AI_LOGGING_PLATFORM_VERSION) !== true) {
return;
}
}
throw new OperatorClientError(
'This platform does not support AI logging policies. Run `void platform upgrade`.',
'unsupported',
);
}
6 changes: 4 additions & 2 deletions packages/void/src/cli/operator-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export const operatorCommands: Array<OperatorCommand> = [
{
group: 'project',
action: 'show',
description: 'Inspect a project and its resources',
description: 'Inspect a project, its resources, and its effective AI Gateway logging',
path: '/projects/:id',
positional: ['id'],
},
Expand All @@ -127,9 +127,11 @@ export const operatorCommands: Array<OperatorCommand> = [
{
group: 'project',
action: 'ai-logging',
description: 'Set AI Gateway logging: inherit, off, metadata, or full',
description:
'Set AI Gateway logging (inherit, off, metadata, or full); new AI requests normally follow it within 2 minutes',
path: '/projects/:id/ai-logging',
positional: ['id', 'mode'],
usage: ['void platform project ai-logging <project-id> <inherit|off|metadata|full> [options]'],
method: 'POST',
},
{
Expand Down
38 changes: 34 additions & 4 deletions packages/void/src/cli/operator-cmd.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { createHash } from 'node:crypto';
import { createInterface } from 'node:readline/promises';
import { setTimeout as delay } from 'node:timers/promises';
import {
aiLoggingChangeLines,
aiLoggingPreviewLines,
aiLoggingStatusLine,
assertAiLoggingPlatform,
} from './operator-ai-logging.ts';
import type { OperatorArgs } from './operator-args.ts';
import {
exchangeOperatorSession,
Expand Down Expand Up @@ -649,6 +655,11 @@ async function migrateDeploymentAssets(
}
}

/** The project ID from the request path `/projects/:id/ai-logging`. */
function aiLoggingProjectId(args: OperatorArgs): string {
return decodeURIComponent(args.path.slice('/projects/'.length, -'/ai-logging'.length));
}

export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
if (!args.action) {
const { printHelpPage } = await import('./help.ts');
Expand All @@ -671,6 +682,10 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
if (args.group === 'deployment' && args.action === 'migrate-assets') {
return migrateDeploymentAssets(client, origin, args);
}
const aiLogging = args.group === 'project' && args.action === 'ai-logging';
if (aiLogging) {
await assertAiLoggingPlatform(origin);
}
// Read once for preview and apply; the server excludes the token from audit output.
if (
args.tokenStdin &&
Expand Down Expand Up @@ -725,6 +740,10 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
'unsupported',
);
}
if (aiLogging && args.plan && !args.json) {
console.log(aiLoggingPreviewLines(aiLoggingProjectId(args), preview).join('\n'));
return;
}
if (!(await confirmOperatorMutation(origin, preview, args))) {
return;
}
Expand All @@ -738,10 +757,16 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
: {}),
...recoveryFence,
};
outputMutation(
await client.request(args.path, { method: 'POST', body, timeoutMs: args.timeoutMs }),
args,
);
const result = await client.request(args.path, {
method: 'POST',
body,
timeoutMs: args.timeoutMs,
});
if (aiLogging && !args.json) {
console.log(aiLoggingChangeLines(aiLoggingProjectId(args), result).join('\n'));
return;
}
outputMutation(result, args);
} else if (args.follow) {
await followOperatorLogs(client, args);
} else {
Expand All @@ -762,6 +787,11 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
...eventLines(result.deployments, ' '),
].join('\n'),
);
} else if (args.group === 'project' && args.action === 'show' && !args.json) {
// One readable line instead of the raw AI logging fields; --json keeps them all.
const { aiLogging, ...project } = result;
const line = aiLoggingStatusLine(aiLogging);
console.log((line ? [...humanLines(project), line] : humanLines(result)).join('\n'));
} else {
output(result, args.json);
}
Expand Down
Loading
Loading