Skip to content

Commit d8a5aa6

Browse files
Brooooooklynclaude
andcommitted
Publish AI logging settings from the installer and show them in the CLI
- Every install, upgrade and repair copies each project's AI logging setting from Postgres to ROUTING KV, once before the Worker upload (the new proxy may go live first) and once after it (the old API may have saved changes meanwhile). It holds the same project row locks as the API, stamps keys with the database clock, and uses new bulk KV list, put and delete calls. - `void platform project ai-logging` prints where the setting comes from and when new requests are expected to follow it; `project show` prints the effective mode, its source and its state. - `void platform config plans` accepts `aiLogging` in plan files and the picker, shows it in diffs, and keeps running `sync` until the AI logging publish is complete. - The end-to-end test runs the built CLI against the real proxy without the uncached-database flag. Refs #793. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 44d6cab commit d8a5aa6

22 files changed

Lines changed: 1855 additions & 48 deletions

‎packages/void/src/cli/client.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,12 @@ type PlatformVersionProbe =
6161
| { kind: 'unknown' };
6262

6363
/**
64-
* Returns whether `version` is older than MIN_PLATFORM_VERSION, or null when
65-
* it is not a release version. A prerelease sorts before its release.
64+
* Returns whether `version` is older than the release `minimumVersion`, or null
65+
* when it is not a release version. A prerelease sorts before its release.
6666
*/
67-
function isOlderThanMinimumPlatform(version: string): boolean | null {
67+
export function isOlderPlatformVersion(version: string, minimumVersion: string): boolean | null {
6868
const actual = RELEASE_VERSION.exec(version);
69-
const minimum = RELEASE_VERSION.exec(MIN_PLATFORM_VERSION)!;
69+
const minimum = RELEASE_VERSION.exec(minimumVersion)!;
7070
if (!actual) {
7171
return null;
7272
}
@@ -99,7 +99,7 @@ function assertSupportedPlatform(apiUrl: string, probe: PlatformVersionProbe): v
9999
// comes from a hosted deployment that does not set PLATFORM_VERSION yet.
100100
// Any other value that is not a release version comes from a custom or
101101
// development build and cannot be ordered. Both pass.
102-
if (version === 'hosted' || isOlderThanMinimumPlatform(version) !== true) {
102+
if (version === 'hosted' || isOlderPlatformVersion(version, MIN_PLATFORM_VERSION) !== true) {
103103
return;
104104
}
105105
throw new Error(

‎packages/void/src/cli/help.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ const HELP_TREE: HelpTree = {
337337
},
338338
{
339339
command: 'set <id>',
340-
description: 'Edit a plan name, limits, or build instance size',
340+
description: 'Edit a plan name, limits, build size, or AI Gateway logging default',
341341
},
342342
{
343343
command: 'reset <id>',
@@ -356,7 +356,10 @@ const HELP_TREE: HelpTree = {
356356
description: 'Remove an unused plan or move its accounts to a replacement',
357357
},
358358
{ command: 'default <id>', description: 'Choose the plan new accounts receive' },
359-
{ command: 'sync', description: 'Continue pending account limit updates' },
359+
{
360+
command: 'sync',
361+
description: 'Continue pending account limit and AI logging updates',
362+
},
360363
],
361364
options: [
362365
{
@@ -365,7 +368,7 @@ const HELP_TREE: HelpTree = {
365368
},
366369
{
367370
command: '--file <path>',
368-
description: 'Read plan settings and partial limits from JSON',
371+
description: 'Read plan settings, partial limits, and aiLogging from JSON',
369372
},
370373
{
371374
command: '--name <name>',
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { AI_LOGGING_SETTLE_MS } from '@void/platform/ai-logging';
2+
import { cfAccessHeaders } from '../shared/cf-access.ts';
3+
import { ensurePlatformAccessToken } from './cf-access.ts';
4+
import { OperatorClientError } from './operator-client.ts';
5+
import { sanitizeTerminalText } from './output.ts';
6+
import { readPlatformDiscoveryResponse } from './platform-discovery.ts';
7+
8+
/** The first platform release with per-project AI logging settings. */
9+
export const AI_LOGGING_PLATFORM_VERSION = '1.8.0';
10+
11+
type Fields = Record<string, unknown>;
12+
13+
function text(value: unknown): string {
14+
return typeof value === 'string' ? sanitizeTerminalText(value) : '';
15+
}
16+
17+
function record(value: unknown): Fields | null {
18+
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Fields) : null;
19+
}
20+
21+
/** `14:03:20 UTC`, or null when the value is not a time. */
22+
export function utcTime(value: unknown, offsetMs = 0): string | null {
23+
const time = typeof value === 'string' ? Date.parse(value) : Number.NaN;
24+
if (Number.isNaN(time)) {
25+
return null;
26+
}
27+
return `${new Date(time + offsetMs).toISOString().slice(11, 19)} UTC`;
28+
}
29+
30+
/** `plan "pro"`, naming the default plan an unknown plan ID follows. */
31+
function planLabel(fields: Fields): string {
32+
const plan = `plan "${text(fields.planId)}"`;
33+
if (fields.planKnown === false) {
34+
return `${plan} (not in catalog; uses default plan "${text(fields.defaultPlanId)}")`;
35+
}
36+
return plan;
37+
}
38+
39+
/** Where the effective mode comes from, or null for a platform that does not say. */
40+
function sourceText(fields: Fields): string | null {
41+
if (typeof fields.planId !== 'string') {
42+
return null;
43+
}
44+
const planDefault = `${planLabel(fields)} default: ${text(fields.planMode) || 'inherit'}`;
45+
switch (fields.source) {
46+
case 'project':
47+
return `set on project; ${planDefault}`;
48+
case 'plan':
49+
return `from ${planLabel(fields)}`;
50+
case 'gateway':
51+
return `AI Gateway setting; ${planDefault}`;
52+
default:
53+
return null;
54+
}
55+
}
56+
57+
function effective(fields: Fields): string {
58+
return text(fields.effective) || text(fields.mode);
59+
}
60+
61+
function withSource(mode: string, fields: Fields): string {
62+
const source = sourceText(fields);
63+
return source ? `${mode} (${source})` : mode;
64+
}
65+
66+
/** The `project ai-logging` result: the setting and when new requests follow it. */
67+
export function aiLoggingChangeLines(projectId: string, result: Fields): Array<string> {
68+
const lines = [
69+
`AI logging for ${sanitizeTerminalText(projectId)}: ${withSource(effective(result), result)}`,
70+
];
71+
const expectedBy = utcTime(result.expectedBy);
72+
if (expectedBy) {
73+
lines.push(
74+
`New AI requests are expected to follow it by ${expectedBy} (normally within 2 minutes).`,
75+
);
76+
}
77+
return lines;
78+
}
79+
80+
/** The `project ai-logging --plan` preview: current and new effective modes. */
81+
export function aiLoggingPreviewLines(projectId: string, preview: Fields): Array<string> {
82+
const previous = text(preview.previous);
83+
const next = effective(preview);
84+
const change = previous ? `${previous} → ${next}` : next;
85+
return [
86+
`AI logging for ${sanitizeTerminalText(projectId)}: ${withSource(change, preview)}`,
87+
'No change was made. Run the command again without --plan to apply it.',
88+
];
89+
}
90+
91+
const STATES: Record<string, (fields: Fields) => string> = {
92+
applied: () => 'applied',
93+
pending: (fields) => {
94+
const by = utcTime(fields.publishedAt, AI_LOGGING_SETTLE_MS);
95+
return by ? `pending (expected by ${by})` : 'pending (normally within 2 minutes)';
96+
},
97+
pending_plan_publish: () => 'pending (the plan default is still being published)',
98+
drift: (fields) => `drift (published: ${text(fields.published) || 'unknown value'})`,
99+
unknown: () => 'state unknown (the published setting could not be read)',
100+
};
101+
102+
/**
103+
* `project show` line, such as `metadata (from plan "pro") — applied`, or null
104+
* when the response has no AI logging data.
105+
*/
106+
export function aiLoggingStatusLine(value: unknown): string | null {
107+
const fields = record(value);
108+
if (!fields || typeof fields.mode !== 'string') {
109+
return null;
110+
}
111+
const state =
112+
typeof fields.state === 'string' && Object.hasOwn(STATES, fields.state)
113+
? STATES[fields.state]
114+
: undefined;
115+
const summary = withSource(effective(fields), fields);
116+
return `AI Gateway logging: ${state ? `${summary} — ${state(fields)}` : summary}`;
117+
}
118+
119+
type DiscoveryProbe = { kind: 'version'; version: string } | { kind: 'missing' | 'unknown' };
120+
121+
async function probePlatformVersion(origin: string): Promise<DiscoveryProbe> {
122+
ensurePlatformAccessToken(origin);
123+
let response: Response;
124+
try {
125+
response = await fetch(`${origin}/.well-known/void-platform`, {
126+
headers: { Accept: 'application/json', ...cfAccessHeaders(process.env, origin) },
127+
redirect: 'manual',
128+
signal: AbortSignal.timeout(15_000),
129+
});
130+
} catch {
131+
return { kind: 'unknown' };
132+
}
133+
if (response.status === 404) {
134+
await response.body?.cancel();
135+
return { kind: 'missing' };
136+
}
137+
try {
138+
return {
139+
kind: 'version',
140+
version: (await readPlatformDiscoveryResponse(origin, response)).platformVersion,
141+
};
142+
} catch {
143+
return { kind: 'unknown' };
144+
}
145+
}
146+
147+
/**
148+
* Refuses `project ai-logging` on a platform before AI logging settings existed.
149+
* It reads the platform version instead of guessing from a 404, because "Project
150+
* not found" is also a 404. When the version cannot be read, the request runs and
151+
* reports its own error.
152+
*/
153+
export async function assertAiLoggingPlatform(origin: string): Promise<void> {
154+
const probe = await probePlatformVersion(origin);
155+
if (probe.kind === 'unknown') {
156+
return;
157+
}
158+
if (probe.kind === 'version') {
159+
const { isOlderPlatformVersion } = await import('./client.ts');
160+
// "hosted" and development builds are not release versions and pass.
161+
if (isOlderPlatformVersion(probe.version, AI_LOGGING_PLATFORM_VERSION) !== true) {
162+
return;
163+
}
164+
}
165+
throw new OperatorClientError(
166+
'This platform does not support AI logging policies. Run `void platform upgrade`.',
167+
'unsupported',
168+
);
169+
}

‎packages/void/src/cli/operator-args.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ export const operatorCommands: Array<OperatorCommand> = [
104104
{
105105
group: 'project',
106106
action: 'show',
107-
description: 'Inspect a project and its resources',
107+
description: 'Inspect a project, its resources, and its effective AI Gateway logging',
108108
path: '/projects/:id',
109109
positional: ['id'],
110110
},
@@ -127,9 +127,11 @@ export const operatorCommands: Array<OperatorCommand> = [
127127
{
128128
group: 'project',
129129
action: 'ai-logging',
130-
description: 'Set AI Gateway logging: inherit, off, metadata, or full',
130+
description:
131+
'Set AI Gateway logging (inherit, off, metadata, or full); new AI requests normally follow it within 2 minutes',
131132
path: '/projects/:id/ai-logging',
132133
positional: ['id', 'mode'],
134+
usage: ['void platform project ai-logging <project-id> <inherit|off|metadata|full> [options]'],
133135
method: 'POST',
134136
},
135137
{

‎packages/void/src/cli/operator-cmd.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { createHash } from 'node:crypto';
22
import { createInterface } from 'node:readline/promises';
33
import { setTimeout as delay } from 'node:timers/promises';
4+
import {
5+
aiLoggingChangeLines,
6+
aiLoggingPreviewLines,
7+
aiLoggingStatusLine,
8+
assertAiLoggingPlatform,
9+
} from './operator-ai-logging.ts';
410
import type { OperatorArgs } from './operator-args.ts';
511
import {
612
exchangeOperatorSession,
@@ -649,6 +655,11 @@ async function migrateDeploymentAssets(
649655
}
650656
}
651657

658+
/** The project ID from the request path `/projects/:id/ai-logging`. */
659+
function aiLoggingProjectId(args: OperatorArgs): string {
660+
return decodeURIComponent(args.path.slice('/projects/'.length, -'/ai-logging'.length));
661+
}
662+
652663
export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
653664
if (!args.action) {
654665
const { printHelpPage } = await import('./help.ts');
@@ -671,6 +682,10 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
671682
if (args.group === 'deployment' && args.action === 'migrate-assets') {
672683
return migrateDeploymentAssets(client, origin, args);
673684
}
685+
const aiLogging = args.group === 'project' && args.action === 'ai-logging';
686+
if (aiLogging) {
687+
await assertAiLoggingPlatform(origin);
688+
}
674689
// Read once for preview and apply; the server excludes the token from audit output.
675690
if (
676691
args.tokenStdin &&
@@ -725,6 +740,10 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
725740
'unsupported',
726741
);
727742
}
743+
if (aiLogging && args.plan && !args.json) {
744+
console.log(aiLoggingPreviewLines(aiLoggingProjectId(args), preview).join('\n'));
745+
return;
746+
}
728747
if (!(await confirmOperatorMutation(origin, preview, args))) {
729748
return;
730749
}
@@ -738,10 +757,16 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
738757
: {}),
739758
...recoveryFence,
740759
};
741-
outputMutation(
742-
await client.request(args.path, { method: 'POST', body, timeoutMs: args.timeoutMs }),
743-
args,
744-
);
760+
const result = await client.request(args.path, {
761+
method: 'POST',
762+
body,
763+
timeoutMs: args.timeoutMs,
764+
});
765+
if (aiLogging && !args.json) {
766+
console.log(aiLoggingChangeLines(aiLoggingProjectId(args), result).join('\n'));
767+
return;
768+
}
769+
outputMutation(result, args);
745770
} else if (args.follow) {
746771
await followOperatorLogs(client, args);
747772
} else {
@@ -762,6 +787,11 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
762787
...eventLines(result.deployments, ' '),
763788
].join('\n'),
764789
);
790+
} else if (args.group === 'project' && args.action === 'show' && !args.json) {
791+
// One readable line instead of the raw AI logging fields; --json keeps them all.
792+
const { aiLogging, ...project } = result;
793+
const line = aiLoggingStatusLine(aiLogging);
794+
console.log((line ? [...humanLines(project), line] : humanLines(result)).join('\n'));
765795
} else {
766796
output(result, args.json);
767797
}

0 commit comments

Comments
 (0)