@oxygen-agent/cli 1.1028.9 → 1.1030.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,4 +34,4 @@ oxygen update
34
34
 
35
35
  For product documentation, visit https://oxygen-agent.com/docs. For support, visit https://oxygen-agent.com.
36
36
 
37
- Version: 1.1028.9
37
+ Version: 1.1030.9
@@ -5,6 +5,12 @@ export declare const AUTO_UPDATE_DISABLE_ENV = "OXYGEN_NO_AUTO_UPDATE";
5
5
  /** Set on the re-run after a floor-driven update; stops a second attempt. */
6
6
  export declare const AUTO_UPDATED_FROM_ENV = "OXYGEN_CLI_AUTO_UPDATED";
7
7
  export declare const BACKGROUND_CHECK_INTERVAL_MS: number;
8
+ /** No oxygen command may run for this long before a background update replaces the install. */
9
+ export declare const UPDATE_IDLE_MS: number;
10
+ /** A background update gives up waiting for an idle CLI after this long… */
11
+ export declare const UPDATE_IDLE_WAIT_MAX_MS: number;
12
+ /** …and the next command retries this soon instead of a day later. */
13
+ export declare const UPDATE_RETRY_AFTER_MS: number;
8
14
  export type AutoUpdateResult = {
9
15
  at: string;
10
16
  from: string;
@@ -16,6 +22,8 @@ export type AutoUpdateResult = {
16
22
  export type AutoUpdateState = {
17
23
  auto_update?: "on" | "off";
18
24
  last_check_at?: string;
25
+ /** Set when a background update gave up waiting for an idle CLI: check again from then on. */
26
+ retry_at?: string;
19
27
  latest_seen?: string;
20
28
  last_check_error?: string;
21
29
  last_result?: AutoUpdateResult;
@@ -54,6 +62,12 @@ export type AutoUpdateRuntime = {
54
62
  readInstalledVersion?: () => string | null;
55
63
  stderr?: (text: string) => void;
56
64
  exit?: (code: number) => never;
65
+ sleep?: (ms: number) => Promise<void>;
66
+ /** Whether another oxygen command's process still runs; defaults to a signal-0 probe. */
67
+ isAlive?: (pid: number) => boolean;
68
+ onExit?: (listener: () => void) => void;
69
+ /** Where running commands leave their markers; defaults to beside this global install. */
70
+ runningCommandsDir?: string;
57
71
  };
58
72
  export declare function recordMutatingRequestAnswered(): void;
59
73
  /** Call before reading piped stdin: a re-run could not read it a second time. */
@@ -75,6 +89,12 @@ export declare function autoUpdateEligibility(runtime?: AutoUpdateRuntime & {
75
89
  * binary and exits with its status.
76
90
  */
77
91
  export declare function recoverFromCliFloorRejection(error: OxygenError, endpoint: CliEndpoint, runtime?: AutoUpdateRuntime): Promise<OxygenError>;
92
+ /**
93
+ * Called once at CLI start: marks this command as running until it exits, so a
94
+ * background update never replaces the install under it. Only a global npm
95
+ * install is ever replaced, and the updater must not wait for itself.
96
+ */
97
+ export declare function trackCommandForAutoUpdate(runtime?: AutoUpdateRuntime): void;
78
98
  /**
79
99
  * The proactive path, called once at CLI start. Never blocks: it reads a small
80
100
  * state file, prints any pending notice to stderr, and — at most once a day —
@@ -91,6 +111,9 @@ export type BackgroundUpdateOutcome = {
91
111
  } | {
92
112
  action: "up_to_date";
93
113
  latest: string;
114
+ } | {
115
+ action: "deferred";
116
+ latest: string;
94
117
  } | {
95
118
  action: "updated";
96
119
  latest: string;
@@ -8,6 +8,7 @@ import { OXYGEN_VERSION } from "@oxygen/shared/version";
8
8
  import { resolveConfigDir } from "./credentials.js";
9
9
  import { resolveCliBinaryName, resolveCliUpdateGuidance } from "./runtime.js";
10
10
  import { detectCliInstall, installCliPackage, readInstalledCliVersion } from "./cli-install.js";
11
+ import { readCliActivity, runningCommandsDirFor, trackRunningCommand } from "./running-commands.js";
11
12
  // The npm `oxygen` CLI keeps itself current in two ways:
12
13
  //
13
14
  // 1. Floor rejection (reactive). When the API refuses this CLI with
@@ -17,7 +18,9 @@ import { detectCliInstall, installCliPackage, readInstalledCliVersion } from "./
17
18
  // mutating request of its own has been answered in this process.
18
19
  // 2. Background (proactive). At most once a day a detached child checks npm and
19
20
  // installs a newer release; the command that spawned it never waits, and the
20
- // next run prints one stderr line saying what happened.
21
+ // next run prints one stderr line saying what happened. npm replaces the
22
+ // install in place, so the child first waits until no oxygen command has run
23
+ // for UPDATE_IDLE_MS (running-commands.ts) and otherwise retries later.
21
24
  //
22
25
  // Neither ever runs for `oxygen-dev`, under CI, for a CLI that is not a global
23
26
  // npm install (npx, a source checkout), or once turned off with
@@ -26,6 +29,13 @@ export const AUTO_UPDATE_DISABLE_ENV = "OXYGEN_NO_AUTO_UPDATE";
26
29
  /** Set on the re-run after a floor-driven update; stops a second attempt. */
27
30
  export const AUTO_UPDATED_FROM_ENV = "OXYGEN_CLI_AUTO_UPDATED";
28
31
  export const BACKGROUND_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
32
+ /** No oxygen command may run for this long before a background update replaces the install. */
33
+ export const UPDATE_IDLE_MS = 5 * 60 * 1000;
34
+ /** A background update gives up waiting for an idle CLI after this long… */
35
+ export const UPDATE_IDLE_WAIT_MAX_MS = 30 * 60 * 1000;
36
+ /** …and the next command retries this soon instead of a day later. */
37
+ export const UPDATE_RETRY_AFTER_MS = 3 * 60 * 60 * 1000;
38
+ const UPDATE_IDLE_POLL_MS = 5_000;
29
39
  const CLI_PACKAGE_NAME = "@oxygen-agent/cli";
30
40
  const NPM_DIST_TAGS_URL = "https://registry.npmjs.org/-/package/@oxygen-agent%2Fcli/dist-tags";
31
41
  const NPM_CHECK_TIMEOUT_MS = 10_000;
@@ -241,6 +251,54 @@ function isUpdateCommand(args) {
241
251
  const first = args.find((arg) => !arg.startsWith("-"));
242
252
  return first === "update";
243
253
  }
254
+ /** The background updater and the skills refresh it runs afterwards, never a user's command. */
255
+ function isAutoUpdateWorker(args) {
256
+ return isUpdateCommand(args) && (args.includes("--background") || args.includes("--refresh-skills"));
257
+ }
258
+ /**
259
+ * Called once at CLI start: marks this command as running until it exits, so a
260
+ * background update never replaces the install under it. Only a global npm
261
+ * install is ever replaced, and the updater must not wait for itself.
262
+ */
263
+ export function trackCommandForAutoUpdate(runtime = {}) {
264
+ try {
265
+ const env = runtime.env ?? process.env;
266
+ const argv = runtime.argv ?? process.argv;
267
+ if (isAutoUpdateWorker(argv.slice(2)) || resolveCliBinaryName(env, argv) === "oxygen-dev")
268
+ return;
269
+ const install = detectCliInstall(runtime.modulePath ?? fileURLToPath(import.meta.url));
270
+ if (install.kind !== "global")
271
+ return;
272
+ trackRunningCommand(runtime.runningCommandsDir ?? runningCommandsDirFor(install.packageDir), { now: runtime.now, onExit: runtime.onExit });
273
+ }
274
+ catch {
275
+ // Keeping the CLI current must never break the command the user ran.
276
+ }
277
+ }
278
+ /** True once no other oxygen command has run for UPDATE_IDLE_MS; false after UPDATE_IDLE_WAIT_MAX_MS. */
279
+ async function waitForIdleCli(runtime) {
280
+ const install = detectCliInstall(runtime.modulePath ?? fileURLToPath(import.meta.url));
281
+ if (install.kind !== "global")
282
+ return true;
283
+ const dir = runtime.runningCommandsDir ?? runningCommandsDirFor(install.packageDir);
284
+ const sleep = runtime.sleep ?? ((ms) => new Promise((resolve) => { setTimeout(resolve, ms); }));
285
+ const startedAt = runtime.now().getTime();
286
+ // The command that spawned this worker is still starting up: begin busy.
287
+ let lastBusyAt = startedAt;
288
+ for (;;) {
289
+ const activity = readCliActivity(dir, { now: runtime.now, isAlive: runtime.isAlive, selfPid: process.pid });
290
+ const at = runtime.now().getTime();
291
+ if (activity.running.length > 0 || activity.reaped > 0)
292
+ lastBusyAt = at;
293
+ if (activity.lastExitAt !== null)
294
+ lastBusyAt = Math.max(lastBusyAt, activity.lastExitAt);
295
+ if (at - lastBusyAt >= UPDATE_IDLE_MS)
296
+ return true;
297
+ if (at - startedAt >= UPDATE_IDLE_WAIT_MAX_MS)
298
+ return false;
299
+ await sleep(UPDATE_IDLE_POLL_MS);
300
+ }
301
+ }
244
302
  /**
245
303
  * The proactive path, called once at CLI start. Never blocks: it reads a small
246
304
  * state file, prints any pending notice to stderr, and — at most once a day —
@@ -262,11 +320,18 @@ export function maybeScheduleBackgroundUpdate(runtime = {}) {
262
320
  }
263
321
  if (!autoUpdateEligibility({ ...runtime, env, argv, state }).eligible)
264
322
  return;
323
+ const at = now().getTime();
265
324
  const lastCheck = state.last_check_at ? Date.parse(state.last_check_at) : Number.NaN;
266
- if (Number.isFinite(lastCheck) && now().getTime() - lastCheck < BACKGROUND_CHECK_INTERVAL_MS)
325
+ const retryAt = state.retry_at ? Date.parse(state.retry_at) : Number.NaN;
326
+ const due = !Number.isFinite(lastCheck)
327
+ || at - lastCheck >= BACKGROUND_CHECK_INTERVAL_MS
328
+ || (Number.isFinite(retryAt) && at >= retryAt);
329
+ if (!due)
267
330
  return;
268
331
  // Claim the slot before spawning so concurrent commands don't stampede npm.
269
- if (!writeAutoUpdateState({ ...state, last_check_at: now().toISOString() }, env))
332
+ const claimed = { ...state, last_check_at: now().toISOString() };
333
+ delete claimed.retry_at;
334
+ if (!writeAutoUpdateState(claimed, env))
270
335
  return;
271
336
  const entry = argv[1];
272
337
  if (!entry)
@@ -308,9 +373,28 @@ export async function runBackgroundUpdate(runtime = {}) {
308
373
  writeAutoUpdateState({ ...readAutoUpdateState(env), last_check_error: message }, env);
309
374
  return { action: "check_failed", error: message };
310
375
  }
376
+ if (!isVersionGreater(latest, OXYGEN_VERSION)) {
377
+ const current = { ...readAutoUpdateState(env), latest_seen: latest };
378
+ delete current.last_check_error;
379
+ writeAutoUpdateState(current, env);
380
+ return { action: "up_to_date", latest };
381
+ }
382
+ if (!(await waitForIdleCli({ ...runtime, env, now }))) {
383
+ writeAutoUpdateState({
384
+ ...readAutoUpdateState(env),
385
+ latest_seen: latest,
386
+ retry_at: new Date(now().getTime() + UPDATE_RETRY_AFTER_MS).toISOString(),
387
+ }, env);
388
+ return { action: "deferred", latest };
389
+ }
390
+ // Waiting can take half an hour: the user may have turned updates off or updated by hand.
311
391
  const checked = { ...readAutoUpdateState(env), latest_seen: latest };
312
392
  delete checked.last_check_error;
313
- if (!isVersionGreater(latest, OXYGEN_VERSION)) {
393
+ const stillEligible = autoUpdateEligibility({ ...runtime, env, argv, state: checked });
394
+ if (!stillEligible.eligible)
395
+ return { action: "skipped", reason: stillEligible.reason };
396
+ const onDisk = readInstalledVersion(runtime);
397
+ if (onDisk && !isVersionGreater(latest, onDisk)) {
314
398
  writeAutoUpdateState(checked, env);
315
399
  return { action: "up_to_date", latest };
316
400
  }
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { maybeScheduleBackgroundUpdate } from "./auto-update.js";
1
+ import { maybeScheduleBackgroundUpdate, trackCommandForAutoUpdate } from "./auto-update.js";
2
2
  import { emitCliFailure, writeJson } from "./cli-output.js";
3
3
  import { createProgram } from "./command-families/program.js";
4
4
  import { beginCliDiagnostics, finishCliDiagnostics, setCliDiagnosticOperation, recordCliDiagnosticFailure } from "./diagnostics.js";
@@ -20,6 +20,7 @@ process.stdout.on("error", (error) => {
20
20
  void finishCliDiagnostics(1).finally(() => process.exit(1));
21
21
  });
22
22
  beginCliDiagnostics();
23
+ trackCommandForAutoUpdate();
23
24
  maybeScheduleBackgroundUpdate();
24
25
  const program = createProgram();
25
26
  installCommanderExitOverride(program);
@@ -0,0 +1,26 @@
1
+ /** A marker not refreshed for this long belongs to a command that is gone: killed, or its pid reused. This also bounds how long a reused pid can hold an update back. */
2
+ export declare const RUNNING_COMMAND_STALE_MS: number;
3
+ export type RunningCommandsRuntime = {
4
+ pid?: number | undefined;
5
+ now?: (() => Date) | undefined;
6
+ isAlive?: ((pid: number) => boolean) | undefined;
7
+ onExit?: ((listener: () => void) => void) | undefined;
8
+ };
9
+ export type CliActivity = {
10
+ /** Other commands running now. */
11
+ running: number[];
12
+ /** Markers removed because their command ended without exiting cleanly. */
13
+ reaped: number;
14
+ /** When an oxygen command last exited, in epoch milliseconds. */
15
+ lastExitAt: number | null;
16
+ };
17
+ /** Test-only: allow tracking again in this process. */
18
+ export declare function resetRunningCommandTracking(): void;
19
+ /** The hidden folder beside a global install's package, which npm leaves alone. */
20
+ export declare function runningCommandsDirFor(packageDir: string): string;
21
+ /** Mark this process as a running oxygen command until it exits. */
22
+ export declare function trackRunningCommand(dir: string, runtime?: RunningCommandsRuntime): void;
23
+ /** The other commands running now, reaping markers whose command is gone. */
24
+ export declare function readCliActivity(dir: string, runtime?: RunningCommandsRuntime & {
25
+ selfPid?: number | undefined;
26
+ }): CliActivity;
@@ -0,0 +1,144 @@
1
+ import { closeSync, mkdirSync, openSync, readdirSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ // npm replaces a global install in place: for the minutes it takes, the old
4
+ // files are gone, so any oxygen command running from them, or started between
5
+ // two calls of a script, fails. Each command therefore leaves a marker beside
6
+ // the install while it runs, refreshes it every minute and stamps its exit, and
7
+ // the background update waits until the CLI has been idle (auto-update.ts).
8
+ // The markers belong to the install, not to OXYGEN_CONFIG_DIR: every command
9
+ // npm would break counts, whichever profile directory it uses. Best-effort
10
+ // throughout: a directory nobody can write must never fail the command itself.
11
+ const RUNNING_COMMANDS_DIR = ".oxygen-cli-running";
12
+ const LAST_EXIT_FILE = "last-exit";
13
+ const HEARTBEAT_MS = 60_000;
14
+ /** A marker not refreshed for this long belongs to a command that is gone: killed, or its pid reused. This also bounds how long a reused pid can hold an update back. */
15
+ export const RUNNING_COMMAND_STALE_MS = 3 * HEARTBEAT_MS;
16
+ let tracked = false;
17
+ /** Test-only: allow tracking again in this process. */
18
+ export function resetRunningCommandTracking() {
19
+ tracked = false;
20
+ }
21
+ /** The hidden folder beside a global install's package, which npm leaves alone. */
22
+ export function runningCommandsDirFor(packageDir) {
23
+ return join(dirname(dirname(packageDir)), RUNNING_COMMANDS_DIR);
24
+ }
25
+ /** Mark this process as a running oxygen command until it exits. */
26
+ export function trackRunningCommand(dir, runtime = {}) {
27
+ if (tracked)
28
+ return;
29
+ tracked = true;
30
+ try {
31
+ const now = runtime.now ?? (() => new Date());
32
+ const pid = runtime.pid ?? process.pid;
33
+ const marker = join(dir, `${pid}.json`);
34
+ const startedAt = now().toISOString();
35
+ const write = () => {
36
+ mkdirSync(dir, { recursive: true });
37
+ writeFileSync(marker, JSON.stringify({ pid, started_at: startedAt }), { mode: 0o600 });
38
+ };
39
+ write();
40
+ // A marker reaped while this process was suspended or blocked comes back with the next beat.
41
+ const heartbeat = setInterval(() => {
42
+ try {
43
+ const at = now();
44
+ utimesSync(marker, at, at);
45
+ }
46
+ catch {
47
+ try {
48
+ write();
49
+ }
50
+ catch {
51
+ // Bookkeeping only.
52
+ }
53
+ }
54
+ }, HEARTBEAT_MS);
55
+ heartbeat.unref();
56
+ (runtime.onExit ?? ((listener) => { process.once("exit", listener); }))(() => {
57
+ clearInterval(heartbeat);
58
+ try {
59
+ unlinkSync(marker);
60
+ }
61
+ catch {
62
+ // Already reaped.
63
+ }
64
+ const stamp = join(dir, LAST_EXIT_FILE);
65
+ try {
66
+ closeSync(openSync(stamp, "a", 0o600));
67
+ }
68
+ catch {
69
+ // Bookkeeping only.
70
+ }
71
+ touch(stamp, now());
72
+ });
73
+ }
74
+ catch {
75
+ // Bookkeeping only.
76
+ }
77
+ }
78
+ function touch(path, at) {
79
+ try {
80
+ utimesSync(path, at, at);
81
+ }
82
+ catch {
83
+ // Bookkeeping only.
84
+ }
85
+ }
86
+ /** The other commands running now, reaping markers whose command is gone. */
87
+ export function readCliActivity(dir, runtime = {}) {
88
+ const now = (runtime.now ?? (() => new Date()))().getTime();
89
+ const isAlive = runtime.isAlive ?? isProcessAlive;
90
+ let lastExitAt = null;
91
+ try {
92
+ lastExitAt = statSync(join(dir, LAST_EXIT_FILE)).mtimeMs;
93
+ }
94
+ catch {
95
+ // No command has exited yet.
96
+ }
97
+ let names;
98
+ try {
99
+ names = readdirSync(dir);
100
+ }
101
+ catch {
102
+ return { running: [], reaped: 0, lastExitAt };
103
+ }
104
+ const running = [];
105
+ let reaped = 0;
106
+ for (const name of names) {
107
+ const match = /^(\d+)\.json$/.exec(name);
108
+ if (!match)
109
+ continue;
110
+ const pid = Number(match[1]);
111
+ if (pid === runtime.selfPid)
112
+ continue;
113
+ const marker = join(dir, name);
114
+ let refreshedAt;
115
+ try {
116
+ refreshedAt = statSync(marker).mtimeMs;
117
+ }
118
+ catch {
119
+ continue; // Removed meanwhile.
120
+ }
121
+ if (now - refreshedAt <= RUNNING_COMMAND_STALE_MS && isAlive(pid)) {
122
+ running.push(pid);
123
+ continue;
124
+ }
125
+ try {
126
+ unlinkSync(marker);
127
+ reaped += 1;
128
+ }
129
+ catch {
130
+ // A marker nobody can remove is ignored rather than holding updates back forever.
131
+ }
132
+ }
133
+ return { running, reaped, lastExitAt };
134
+ }
135
+ /** EPERM is a live process we may not signal, such as an elevated terminal's command. */
136
+ function isProcessAlive(pid) {
137
+ try {
138
+ process.kill(pid, 0);
139
+ return true;
140
+ }
141
+ catch (error) {
142
+ return error.code === "EPERM";
143
+ }
144
+ }
@@ -0,0 +1,75 @@
1
+ import { type GeoAnswer, type GeoDomainType, type GeoPageType } from "./geo.js";
2
+ /**
3
+ * Insights derived from stored answers alone: no supplier or model call. All of
4
+ * them read the current measurement definition's controlled answers, the same
5
+ * cohort as the headline metrics.
6
+ */
7
+ export type GeoMatrixCell = {
8
+ topic: string;
9
+ engine: string;
10
+ successful_samples: number;
11
+ /** Answers naming each brand; the project brand under the project's name. */
12
+ mentioned: Record<string, number>;
13
+ };
14
+ export type GeoTopicTrend = {
15
+ day: string;
16
+ topic: string;
17
+ successful_samples: number;
18
+ mentioned_samples: number;
19
+ };
20
+ export type GeoGapPage = {
21
+ url: string;
22
+ domain: string;
23
+ category: GeoDomainType;
24
+ page_type: GeoPageType;
25
+ /** Answers citing the page that name a competitor and not the brand. */
26
+ answers: number;
27
+ prompts: number;
28
+ competitors: {
29
+ name: string;
30
+ answers: number;
31
+ }[];
32
+ };
33
+ export type GeoSuggestedBrand = {
34
+ name: string;
35
+ domain: string;
36
+ /** Answers whose prose names the brand. */
37
+ mentioned_samples: number;
38
+ /** Answers citing the brand's site. */
39
+ cited_samples: number;
40
+ };
41
+ export type GeoSearch = {
42
+ query: string;
43
+ answers: number;
44
+ engines: string[];
45
+ };
46
+ export type GeoInsights = {
47
+ headline: string | null;
48
+ matrix: GeoMatrixCell[];
49
+ topic_trends: GeoTopicTrend[];
50
+ gap_pages: GeoGapPage[];
51
+ suggested_brands: GeoSuggestedBrand[];
52
+ searches: GeoSearch[];
53
+ };
54
+ /** example.co.uk and docs.example.com both belong to the site a brand would own. */
55
+ export declare function geoSiteOf(domain: string): string;
56
+ /** One plain sentence per finding: who AI names, how often, and what it reads. */
57
+ export declare function geoHeadline(answers: GeoAnswer[], brand: string): string | null;
58
+ /**
59
+ * Third-party pages cited by answers that name a competitor and not the brand:
60
+ * the lists, comparisons, articles and threads a brand can get onto. Owned and
61
+ * competitor sites are excluded, and so are vendor homepages and product pages.
62
+ */
63
+ export declare function geoGapPages(answers: GeoAnswer[], brand: string, limit?: number): GeoGapPage[];
64
+ /** Answers naming each brand other than `brand`, most named first. */
65
+ export declare function geoRivalCounts(answers: GeoAnswer[], brand: string): {
66
+ name: string;
67
+ answers: number;
68
+ }[];
69
+ /** A page type as a reader says it ("best-of list"). */
70
+ export declare function geoPageTypePhrase(type: GeoPageType): string;
71
+ /**
72
+ * `topicOf` resolves an answer's topic (stored on the answer, else its prompt's).
73
+ * `answers` are the current definition's answers; controlled ones are selected here.
74
+ */
75
+ export declare function geoInsights(answers: GeoAnswer[], brand: string, topicOf: (answer: GeoAnswer) => string | undefined): GeoInsights;
@@ -0,0 +1,218 @@
1
+ import { isGeoControlledAnswer } from "./geo.js";
2
+ const NO_TOPIC = "No topic";
3
+ /** Third-party pages a brand can get onto; vendor homepages and product pages it cannot. */
4
+ const REACHABLE_VENDOR_PAGES = new Set(["listicle", "alternative", "comparison", "article", "how_to", "discussion", "profile"]);
5
+ const PAGE_TYPE_PHRASE = {
6
+ homepage: "homepages",
7
+ listicle: "best-of lists",
8
+ alternative: "alternatives pages",
9
+ comparison: "comparison pages",
10
+ article: "articles",
11
+ how_to: "how-to guides",
12
+ product: "product pages",
13
+ discussion: "forum threads",
14
+ profile: "review profiles",
15
+ category: "category pages",
16
+ };
17
+ /** The brand names present in an answer, the project brand under `brand`. */
18
+ function presentBrands(answer, brand) {
19
+ const own = answer.measurement?.brand.name;
20
+ return new Set(answer.mentions.filter((m) => m.present).map((m) => (m.brand === own ? brand : m.brand)));
21
+ }
22
+ /** example.co.uk and docs.example.com both belong to the site a brand would own. */
23
+ export function geoSiteOf(domain) {
24
+ const parts = domain.split(".");
25
+ const secondLevel = parts.length > 2 && /^(co|com|org|net|ac)$/.test(parts.at(-2)) && parts.at(-1).length === 2;
26
+ return parts.slice(secondLevel ? -3 : -2).join(".");
27
+ }
28
+ function tenths(count, total) {
29
+ return Math.round((count / total) * 10);
30
+ }
31
+ function listPhrase(items) {
32
+ return items.length <= 1 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
33
+ }
34
+ /** One plain sentence per finding: who AI names, how often, and what it reads. */
35
+ export function geoHeadline(answers, brand) {
36
+ const samples = answers.filter(isGeoControlledAnswer);
37
+ if (!samples.length)
38
+ return null;
39
+ const counts = new Map();
40
+ for (const answer of samples)
41
+ for (const name of presentBrands(answer, brand))
42
+ counts.set(name, (counts.get(name) ?? 0) + 1);
43
+ const own = counts.get(brand) ?? 0;
44
+ const sentences = [`AI names ${brand} in ${own} of ${samples.length} answers.`];
45
+ const leaders = [...counts].filter(([name]) => name !== brand).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
46
+ const top = leaders[0];
47
+ if (top && top[1] > own) {
48
+ const level = tenths(top[1], samples.length);
49
+ const peers = leaders.slice(0, 3).filter(([, count]) => tenths(count, samples.length) === level).map(([name]) => name);
50
+ const verb = `${listPhrase(peers)} ${peers.length > 1 ? "are" : "is"} named`;
51
+ const every = peers.every((name) => counts.get(name) === samples.length);
52
+ sentences.push(every ? `${verb} in every answer.` : level >= 10 ? `${verb} in nearly every answer.` : level >= 1 ? `${verb} in about ${level} of 10.` : `${verb} most often.`);
53
+ }
54
+ else if (own)
55
+ sentences.push(`No tracked competitor is named more often.`);
56
+ const pages = new Map();
57
+ for (const answer of samples)
58
+ for (const citation of answer.citations)
59
+ if (PAGE_TYPE_PHRASE[citation.page_type])
60
+ pages.set(citation.page_type, (pages.get(citation.page_type) ?? 0) + 1);
61
+ const read = [...pages].sort((a, b) => b[1] - a[1]).slice(0, 2).map(([type]) => PAGE_TYPE_PHRASE[type]);
62
+ if (read.length)
63
+ sentences.push(`The pages AI cites most are ${listPhrase(read)}.`);
64
+ return sentences.join(" ");
65
+ }
66
+ /**
67
+ * Third-party pages cited by answers that name a competitor and not the brand:
68
+ * the lists, comparisons, articles and threads a brand can get onto. Owned and
69
+ * competitor sites are excluded, and so are vendor homepages and product pages.
70
+ */
71
+ export function geoGapPages(answers, brand, limit = 25) {
72
+ const gaps = new Map();
73
+ for (const answer of answers.filter(isGeoControlledAnswer)) {
74
+ const named = presentBrands(answer, brand);
75
+ const rivals = [...named].filter((name) => name !== brand);
76
+ if (named.has(brand) || !rivals.length)
77
+ continue;
78
+ for (const citation of answer.citations) {
79
+ if (citation.category === "owned" || citation.category === "competitor")
80
+ continue;
81
+ if (citation.category === "corporate" && !REACHABLE_VENDOR_PAGES.has(citation.page_type))
82
+ continue;
83
+ const page = gaps.get(citation.url) ?? {
84
+ url: citation.url,
85
+ domain: citation.domain,
86
+ category: citation.category,
87
+ page_type: citation.page_type,
88
+ answers: 0,
89
+ prompts: 0,
90
+ competitors: [],
91
+ promptIds: new Set(),
92
+ rivals: new Map(),
93
+ };
94
+ page.answers++;
95
+ if (answer.prompt_id)
96
+ page.promptIds.add(answer.prompt_id);
97
+ for (const name of rivals)
98
+ page.rivals.set(name, (page.rivals.get(name) ?? 0) + 1);
99
+ gaps.set(citation.url, page);
100
+ }
101
+ }
102
+ return [...gaps.values()]
103
+ .map(({ promptIds, rivals, ...page }) => ({
104
+ ...page,
105
+ prompts: promptIds.size,
106
+ competitors: [...rivals].map(([name, count]) => ({ name, answers: count })).sort((a, b) => b.answers - a.answers || a.name.localeCompare(b.name)),
107
+ }))
108
+ .sort((a, b) => b.answers - a.answers || b.competitors.length - a.competitors.length || a.url.localeCompare(b.url))
109
+ .slice(0, limit);
110
+ }
111
+ /** Answers naming each brand other than `brand`, most named first. */
112
+ export function geoRivalCounts(answers, brand) {
113
+ const counts = new Map();
114
+ for (const answer of answers.filter(isGeoControlledAnswer))
115
+ for (const name of presentBrands(answer, brand))
116
+ if (name !== brand)
117
+ counts.set(name, (counts.get(name) ?? 0) + 1);
118
+ return [...counts].map(([name, count]) => ({ name, answers: count })).sort((a, b) => b.answers - a.answers || a.name.localeCompare(b.name));
119
+ }
120
+ /** A page type as a reader says it ("best-of list"). */
121
+ export function geoPageTypePhrase(type) {
122
+ return (PAGE_TYPE_PHRASE[type] ?? "pages").replace(/s$/, "");
123
+ }
124
+ /**
125
+ * `topicOf` resolves an answer's topic (stored on the answer, else its prompt's).
126
+ * `answers` are the current definition's answers; controlled ones are selected here.
127
+ */
128
+ export function geoInsights(answers, brand, topicOf) {
129
+ const samples = answers.filter(isGeoControlledAnswer);
130
+ const topic = (answer) => topicOf(answer)?.trim() || NO_TOPIC;
131
+ const cells = new Map();
132
+ const days = new Map();
133
+ const vendors = new Map();
134
+ const searches = new Map();
135
+ for (const answer of samples) {
136
+ const named = presentBrands(answer, brand);
137
+ const cellKey = JSON.stringify([topic(answer), answer.engine]);
138
+ const cell = cells.get(cellKey) ?? { topic: topic(answer), engine: answer.engine, successful_samples: 0, mentioned: {} };
139
+ cell.successful_samples++;
140
+ for (const name of named)
141
+ cell.mentioned[name] = (cell.mentioned[name] ?? 0) + 1;
142
+ cells.set(cellKey, cell);
143
+ const dayKey = JSON.stringify([answer.captured_at.slice(0, 10), topic(answer)]);
144
+ const day = days.get(dayKey) ?? { day: answer.captured_at.slice(0, 10), topic: topic(answer), successful_samples: 0, mentioned_samples: 0 };
145
+ day.successful_samples++;
146
+ if (named.has(brand))
147
+ day.mentioned_samples++;
148
+ days.set(dayKey, day);
149
+ // An untracked vendor: a commercial site the answer cites whose name its prose also uses.
150
+ for (const citation of answer.citations) {
151
+ if (citation.category !== "corporate")
152
+ continue;
153
+ const site = geoSiteOf(citation.domain);
154
+ const vendor = vendors.get(site) ?? { domain: site, cited: new Set(), spellings: new Map(), mentioned: new Set(), suffixed: new Set(), lowercase: 0 };
155
+ vendor.cited.add(answer.id);
156
+ vendors.set(site, vendor);
157
+ }
158
+ for (const raw of answer.fan_out ?? []) {
159
+ const query = raw.replace(/\s+/g, " ").trim();
160
+ if (!query)
161
+ continue;
162
+ const entry = searches.get(query.toLowerCase()) ?? { query, answers: 0, engines: new Set() };
163
+ entry.answers++;
164
+ entry.engines.add(answer.engine);
165
+ searches.set(query.toLowerCase(), entry);
166
+ }
167
+ }
168
+ // Names are proper nouns: count capitalized spellings in every answer, cited or not.
169
+ // A label prose also uses as a lowercase word ("cold", "enrich") counts only with
170
+ // its domain suffix ("Cold.app"), so a heading word is not a brand.
171
+ for (const vendor of vendors.values()) {
172
+ const label = vendor.domain.split(".")[0];
173
+ if (label.length < 4)
174
+ continue;
175
+ const suffix = vendor.domain.slice(label.length);
176
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}.])(${label.replace(/[-]/g, "[- ]?")})(${suffix.replace(/\./g, "\\.")})?(?![\\p{L}\\p{N}])`, "giu");
177
+ for (const answer of samples)
178
+ for (const match of answer.text.matchAll(pattern)) {
179
+ if (!/^\p{Lu}/u.test(match[0])) {
180
+ if (!match[2])
181
+ vendor.lowercase++;
182
+ continue;
183
+ }
184
+ vendor.mentioned.add(answer.id);
185
+ if (match[2])
186
+ vendor.suffixed.add(answer.id);
187
+ vendor.spellings.set(match[0], (vendor.spellings.get(match[0]) ?? 0) + 1);
188
+ }
189
+ if (vendor.lowercase >= 3) {
190
+ vendor.mentioned = vendor.suffixed;
191
+ for (const spelling of vendor.spellings.keys())
192
+ if (!spelling.includes("."))
193
+ vendor.spellings.delete(spelling);
194
+ }
195
+ }
196
+ const tracked = new Set(samples.flatMap((answer) => answer.mentions.map((mention) => mention.brand.toLowerCase())).concat(brand.toLowerCase()));
197
+ return {
198
+ headline: geoHeadline(samples, brand),
199
+ matrix: [...cells.values()].sort((a, b) => a.topic.localeCompare(b.topic) || a.engine.localeCompare(b.engine)),
200
+ topic_trends: [...days.values()].sort((a, b) => a.day.localeCompare(b.day) || a.topic.localeCompare(b.topic)),
201
+ gap_pages: geoGapPages(samples, brand),
202
+ suggested_brands: [...vendors.values()]
203
+ .filter((vendor) => vendor.mentioned.size >= 2)
204
+ .map((vendor) => ({
205
+ name: [...vendor.spellings].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0][0],
206
+ domain: vendor.domain,
207
+ mentioned_samples: vendor.mentioned.size,
208
+ cited_samples: vendor.cited.size,
209
+ }))
210
+ .filter((vendor) => !tracked.has(vendor.name.toLowerCase()))
211
+ .sort((a, b) => b.mentioned_samples - a.mentioned_samples || b.cited_samples - a.cited_samples || a.name.localeCompare(b.name))
212
+ .slice(0, 12),
213
+ searches: [...searches.values()]
214
+ .map((entry) => ({ query: entry.query, answers: entry.answers, engines: [...entry.engines].sort() }))
215
+ .sort((a, b) => b.answers - a.answers || a.query.localeCompare(b.query))
216
+ .slice(0, 20),
217
+ };
218
+ }
@@ -63,6 +63,20 @@ export declare function readDeliveryStatusNotificationBody(input: Pick<DsnInput,
63
63
  * incident out of a customer reply.
64
64
  */
65
65
  export declare function classifyDeliveryStatusNotification(input: DsnInput): DeliveryStatusNotification | null;
66
+ /**
67
+ * One bounced recipient as an ESP reports it (Amazon SES `bouncedRecipients[]`:
68
+ * its `status` and `diagnosticCode`), classified with the same rules as a DSN
69
+ * body: a reported enhanced status outranks prose, and only a "no such user"
70
+ * verdict is evidence that the address does not exist. A policy refusal, a full
71
+ * mailbox or a report without a usable status is not.
72
+ */
73
+ export declare function classifyBouncedRecipient(input: {
74
+ status?: string | null;
75
+ diagnosticCode?: string | null;
76
+ }): {
77
+ kind: DeliveryStatusNotificationKind;
78
+ enhancedCode: string | null;
79
+ };
66
80
  /**
67
81
  * A bounce generator is not necessarily the server that rejected delivery.
68
82
  * Gmail can relay a Mimecast/Sophos refusal. Require receiving-server evidence;
@@ -277,6 +277,19 @@ export function classifyDeliveryStatusNotification(input) {
277
277
  smtpCode,
278
278
  };
279
279
  }
280
+ /**
281
+ * One bounced recipient as an ESP reports it (Amazon SES `bouncedRecipients[]`:
282
+ * its `status` and `diagnosticCode`), classified with the same rules as a DSN
283
+ * body: a reported enhanced status outranks prose, and only a "no such user"
284
+ * verdict is evidence that the address does not exist. A policy refusal, a full
285
+ * mailbox or a report without a usable status is not.
286
+ */
287
+ export function classifyBouncedRecipient(input) {
288
+ const diagnostic = typeof input.diagnosticCode === "string" ? input.diagnosticCode.slice(0, 2_000) : "";
289
+ const reported = typeof input.status === "string" ? input.status.trim() : "";
290
+ const enhancedCode = /^[2-5]\.\d{1,3}\.\d{1,3}$/.test(reported) ? reported : readEnhancedStatusCode(diagnostic);
291
+ return { kind: readKind("", diagnostic, diagnostic.trim().length > 0, enhancedCode, null), enhancedCode };
292
+ }
280
293
  /**
281
294
  * A bounce generator is not necessarily the server that rejected delivery.
282
295
  * Gmail can relay a Mimecast/Sophos refusal. Require receiving-server evidence;
@@ -1,3 +1,3 @@
1
1
  export declare const OXYGEN_VERSION: string;
2
- export declare const OXYGEN_MINIMUM_CLI_VERSION = "1.1011.489";
2
+ export declare const OXYGEN_MINIMUM_CLI_VERSION = "1.1011.681";
3
3
  export declare const GEO_EXPORT_MINIMUM_CLI_VERSION = "1.1013.0";
@@ -1 +1 @@
1
- export declare const OXYGEN_BUILD_VERSION = "1.1028.9";
1
+ export declare const OXYGEN_BUILD_VERSION = "1.1030.9";
@@ -1,2 +1,2 @@
1
1
  // GENERATED by scripts/ci/version-stamp.mjs from VERSION + git history. Do not edit; do not commit.
2
- export const OXYGEN_BUILD_VERSION = "1.1028.9";
2
+ export const OXYGEN_BUILD_VERSION = "1.1030.9";
@@ -49,7 +49,7 @@ export const OXYGEN_VERSION = OXYGEN_BUILD_VERSION;
49
49
  // Since 2026-09-28 the release-preparation step advances this literal to the
50
50
  // highest CLI version published on npm for at least 30 days. It never lowers
51
51
  // the floor. The source change lands on dev before the next production release.
52
- export const OXYGEN_MINIMUM_CLI_VERSION = "1.1011.489";
52
+ export const OXYGEN_MINIMUM_CLI_VERSION = "1.1011.681";
53
53
  // The internal GEO export first gains required pagination in this dev version.
54
54
  // Earlier pilot clients would save a partial file without its continuation.
55
55
  export const GEO_EXPORT_MINIMUM_CLI_VERSION = "1.1013.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxygen-agent/cli",
3
- "version": "1.1028.9",
3
+ "version": "1.1030.9",
4
4
  "private": false,
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",