Преглед изворни кода

feat(embedding): send X-AI-Caller attribution header on ai.mm.mk gateway calls

Inject the advisory X-AI-Caller header (Oivo ai.mm.mk observability rollout,
Thread 1) in OpenAIEmbeddingsProvider.buildHeaders() — the single chokepoint
for /health + /v1/embeddings. comp=qmd; mc/sid from OIVO_* env, NULL-safe and
sanitized. Header is advisory metadata only, never an auth input.

Session-Id: 06714332
Claude пре 4 недеља
родитељ
комит
39d45270a7
2 измењених фајлова са 82 додато и 0 уклоњено
  1. 41 0
      dist/embedding/openai.js
  2. 41 0
      src/embedding/openai.ts

+ 41 - 0
dist/embedding/openai.js

@@ -18,6 +18,7 @@
  *   - Per-call timeout via AbortSignal (default QMD_EMBED_TIMEOUT_MS=30000)
  *   - Healthcheck via `GET /health` if available, else a probe embed call
  */
+import os from "node:os";
 // ─────────────────────────── Configuration ───────────────────────────────────
 /**
  * Default batch size — most OpenAI-compatible embedding endpoints accept up to
@@ -55,6 +56,43 @@ export const CIRCUIT_MIN_SAMPLES = 4;
 function defaultSleep(ms) {
     return new Promise((resolve) => setTimeout(resolve, ms));
 }
+/**
+ * Build the advisory `X-AI-Caller` attribution header value (Oivo ai.mm.mk
+ * "Observability-Driven Fleet Self-Improvement" rollout, Thread 1). Format
+ * mirrors Oivo's `cli/src/shared/aiCallerHeader.ts` EXACTLY:
+ *   site=<file:line | tool file>; mc=<machine>; sid=<session-8char>;
+ *   comp=<component>; via=<logical-label>
+ *
+ * Advisory metadata ONLY — never an auth/authorization input. `mc`/`sid` come
+ * from the Oivo fleet env when qmd runs as a delegated embedder; both degrade
+ * to `-`/short-hostname safely when qmd runs standalone. Values are sanitized
+ * (`;` + control chars stripped, capped at 120) so a pathological env value can
+ * never break the header grammar.
+ */
+function aiCallerHeaderValue(via) {
+    const clean = (raw, fallback) => {
+        if (raw == null)
+            return fallback;
+        let out = "";
+        for (const ch of String(raw)) {
+            const code = ch.charCodeAt(0);
+            out += code < 32 || code === 127 || ch === ";" ? " " : ch;
+        }
+        const collapsed = out.replace(/\s+/g, " ").trim();
+        return (collapsed || fallback).slice(0, 120);
+    };
+    let mc = (process.env.OIVO_MACHINE_NAME ?? "").trim();
+    if (!mc) {
+        try {
+            mc = os.hostname().split(".")[0] || "unknown";
+        }
+        catch {
+            mc = "unknown";
+        }
+    }
+    const sid = (process.env.OIVO_SESSION_ID || process.env.CLAUDE_CODE_SESSION_ID || "-").slice(0, 8);
+    return `site=src/embedding/openai.ts; mc=${clean(mc, "unknown")}; sid=${clean(sid, "-")}; comp=qmd; via=${clean(via, "-")}`;
+}
 /**
  * Build the merged AbortSignal for a single HTTP attempt: combines an
  * external `userSignal` (from caller / withLLMSession) with a per-attempt
@@ -480,6 +518,9 @@ export class OpenAIEmbeddingsProvider {
         const headers = {
             "Content-Type": "application/json",
             "Accept": "application/json",
+            // Advisory caller attribution for the ai.mm.mk gateway (NULL-safe, never
+            // auth). Single chokepoint for both /health and /v1/embeddings.
+            "X-AI-Caller": aiCallerHeaderValue("embeddings"),
         };
         if (this.apiKey) {
             headers["Authorization"] = `Bearer ${this.apiKey}`;

+ 41 - 0
src/embedding/openai.ts

@@ -19,6 +19,8 @@
  *   - Healthcheck via `GET /health` if available, else a probe embed call
  */
 
+import os from "node:os";
+
 import type {
   EmbeddingProvider,
   ProviderEmbedOptions,
@@ -128,6 +130,42 @@ function defaultSleep(ms: number): Promise<void> {
   return new Promise((resolve) => setTimeout(resolve, ms));
 }
 
+/**
+ * Build the advisory `X-AI-Caller` attribution header value (Oivo ai.mm.mk
+ * "Observability-Driven Fleet Self-Improvement" rollout, Thread 1). Format
+ * mirrors Oivo's `cli/src/shared/aiCallerHeader.ts` EXACTLY:
+ *   site=<file:line | tool file>; mc=<machine>; sid=<session-8char>;
+ *   comp=<component>; via=<logical-label>
+ *
+ * Advisory metadata ONLY — never an auth/authorization input. `mc`/`sid` come
+ * from the Oivo fleet env when qmd runs as a delegated embedder; both degrade
+ * to `-`/short-hostname safely when qmd runs standalone. Values are sanitized
+ * (`;` + control chars stripped, capped at 120) so a pathological env value can
+ * never break the header grammar.
+ */
+function aiCallerHeaderValue(via: string): string {
+  const clean = (raw: string | undefined, fallback: string): string => {
+    if (raw == null) return fallback;
+    let out = "";
+    for (const ch of String(raw)) {
+      const code = ch.charCodeAt(0);
+      out += code < 32 || code === 127 || ch === ";" ? " " : ch;
+    }
+    const collapsed = out.replace(/\s+/g, " ").trim();
+    return (collapsed || fallback).slice(0, 120);
+  };
+  let mc = (process.env.OIVO_MACHINE_NAME ?? "").trim();
+  if (!mc) {
+    try {
+      mc = os.hostname().split(".")[0] || "unknown";
+    } catch {
+      mc = "unknown";
+    }
+  }
+  const sid = (process.env.OIVO_SESSION_ID || process.env.CLAUDE_CODE_SESSION_ID || "-").slice(0, 8);
+  return `site=src/embedding/openai.ts; mc=${clean(mc, "unknown")}; sid=${clean(sid, "-")}; comp=qmd; via=${clean(via, "-")}`;
+}
+
 /**
  * Build the merged AbortSignal for a single HTTP attempt: combines an
  * external `userSignal` (from caller / withLLMSession) with a per-attempt
@@ -607,6 +645,9 @@ export class OpenAIEmbeddingsProvider implements EmbeddingProvider {
     const headers: Record<string, string> = {
       "Content-Type": "application/json",
       "Accept": "application/json",
+      // Advisory caller attribution for the ai.mm.mk gateway (NULL-safe, never
+      // auth). Single chokepoint for both /health and /v1/embeddings.
+      "X-AI-Caller": aiCallerHeaderValue("embeddings"),
     };
     if (this.apiKey) {
       headers["Authorization"] = `Bearer ${this.apiKey}`;