codex-copilot-dx 1.4.0 → 1.4.2

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.
@@ -671,3 +671,30 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
671
671
  .image-model-choice { display: flex; align-items: center; gap: 8px; overflow-wrap: anywhere; }
672
672
  .image-model-choice input { flex: 0 0 auto; }
673
673
  .image-metrics { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
674
+
675
+ .tool-style { display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);white-space:nowrap; }
676
+ .tool-style select { max-width:160px; }
677
+ .tool-stage { display:grid;grid-template-columns:minmax(180px,250px) minmax(0,1fr);align-items:center;gap:24px;min-height:230px; }
678
+ .tool-visual,.tool-content { min-width:0; }
679
+ .tool-orbit { width:100%;height:190px;position:relative; }
680
+ .tool-orbit canvas { display:block;width:100%;height:100%; }
681
+ .tool-stage[data-style="grid"] .tool-orbit { max-height:140px; }
682
+ .tool-stage[data-style="off"] { grid-template-columns:1fr;min-height:110px; }
683
+ .tool-stage[data-style="off"] .tool-orbit { display:none; }
684
+ .tool-stage[data-style="off"] .tool-narration { text-align:left; }
685
+ .tool-narration { margin:0;min-height:24px;text-align:center;color:var(--text);font-size:12px;line-height:1.7; }
686
+ .tool-context { color:var(--muted);font-size:11px;line-height:1.6;margin:0 0 16px; }
687
+ .tool-entry { display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;min-height:48px;padding-block:8px;border-bottom:1px solid var(--border); }
688
+ .tool-entry:last-child { border-bottom:0; }
689
+ .tool-name { font-size:12px; }
690
+ .tool-entry > span:last-child { color:var(--muted);font-size:11px;white-space:nowrap; }
691
+ .tool-mark { display:inline-block;width:7px;height:7px;border:1px solid var(--accent);border-radius:50%; }
692
+ .tool-entry[data-state="preparing"] .tool-mark { background:var(--accent); }
693
+ .tool-entry[data-state="returned"] .tool-mark { width:9px;height:5px;border-top:0;border-right:0;border-radius:0;transform:rotate(-45deg); }
694
+ .tool-technical { margin:12px 0 0;color:var(--muted);font-size:11px; }
695
+ .tool-technical p { overflow-wrap:anywhere;line-height:1.7;margin:6px 0; }
696
+ #tool-cursor { display:inline-block;animation:tool-cursor 1s steps(1) infinite; }
697
+ #tool-activity[data-paused="true"] #tool-cursor { animation:none; }
698
+ @keyframes tool-cursor { 50% { opacity:0; } }
699
+ @media(max-width:620px) { .tool-stage { grid-template-columns:1fr;gap:8px; }.tool-visual { width:100%;max-width:330px;margin:auto; }.tool-content { padding-bottom:8px; }.tool-context { margin-bottom:4px; } }
700
+ @media(prefers-reduced-motion:reduce) { #tool-cursor { animation:none; } }
@@ -271,7 +271,7 @@ for (const [key, ids] of [["auth", ["account-authorization", "client-features",
271
271
  const updateView = globalThis.ccdxDashboardUpdates.create(viewHelpers);
272
272
  function statusState(state) {
273
273
  if (!liveActivity.current && (state.error || !state.value)) globalThis.ccdxDashboardActivity?.unavailable();
274
- if (!liveActivity.current && (state.error || !state.value) && statusResourceKey() === "status") globalThis.ccdxDashboardFlow?.unavailable();
274
+ if (!liveActivity.current && (state.error || !state.value) && statusResourceKey() === "status") { globalThis.ccdxDashboardFlow?.unavailable();globalThis.ccdxToolActivity?.unavailable(); }
275
275
  text("connection", state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable");
276
276
  element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
277
277
  globalThis.ccdxIcons?.set(element("connection"), state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable",
@@ -457,7 +457,7 @@ const liveActivity = globalThis.ccdxLive.create({
457
457
  element("connection").className = "badge good";
458
458
  globalThis.ccdxIcons?.set(element("connection"), "service_reachable", "connected");
459
459
  } else {
460
- globalThis.ccdxDashboardActivity?.unavailable();globalThis.ccdxDashboardFlow?.unavailable();
460
+ globalThis.ccdxDashboardActivity?.unavailable();globalThis.ccdxDashboardFlow?.unavailable();globalThis.ccdxToolActivity?.unavailable();
461
461
  if (value !== "paused") {
462
462
  element("connection").className = "badge neutral";
463
463
  globalThis.ccdxIcons?.set(element("connection"), "reading", "unknown");
package/src/dashboard.mjs CHANGED
@@ -17,6 +17,7 @@ const ASSETS = new Map([
17
17
  ["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
18
18
  ["/activity.js", ["./dashboard/activity.js", "text/javascript; charset=utf-8"]],
19
19
  ["/flow.js", ["./dashboard/flow.js", "text/javascript; charset=utf-8"]],
20
+ ["/tool-activity.js", ["./dashboard/tool-activity.js", "text/javascript; charset=utf-8"]],
20
21
  ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
21
22
  ["/context.js", ["./dashboard/context.js", "text/javascript; charset=utf-8"]],
22
23
  ["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
@@ -3,6 +3,7 @@ import { sourceModels } from "./client-model-plan.mjs";
3
3
  import { isImageModel, imageModelCatalog } from "./image-models.mjs";
4
4
  import os from "node:os";
5
5
  import { publicModelCatalog } from "./provider-metadata.mjs";
6
+ import { uniqueModelEntries } from "./model-catalog.mjs";
6
7
  import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
7
8
  import { githubTokenFingerprint } from "./github-identity.mjs";
8
9
  import { validateGithubToken } from "./auth.mjs";
@@ -33,7 +34,8 @@ function endpointLabels(model) {
33
34
  }
34
35
 
35
36
  export function selectableCopilotModels(payload) {
36
- const data = Array.isArray(payload) ? payload : payload?.data;
37
+ const raw = Array.isArray(payload) ? payload : payload?.data;
38
+ const data = Array.isArray(raw) ? uniqueModelEntries(raw) : raw;
37
39
  if (!Array.isArray(data)) throw new Error("Copilot models response contained no model list");
38
40
 
39
41
  const models = [];
@@ -63,10 +65,10 @@ export function selectableCopilotModels(payload) {
63
65
  }
64
66
 
65
67
  export function publicCopilotModelCatalog(payload) {
66
- const data=Array.isArray(payload)?payload:payload.data;
68
+ const data=uniqueModelEntries(Array.isArray(payload)?payload:payload.data);
67
69
  const codex=new Set(sourceModels({id:"github",registry:{models:{data}}},"codex")
68
70
  .filter(model=>model.model_picker_enabled!==false&&(!model.policy?.state||model.policy.state==="enabled")).map(model=>model.id));
69
- const antigravity=new Set(antigravityCopilotModels(payload).map(model=>model.model));
71
+ const antigravity=new Set(antigravityCopilotModels({data}).map(model=>model.model));
70
72
  return publicModelCatalog(data,{
71
73
  selectable:model=>codex.has(model.id)||antigravity.has(model.id)||imageModelCatalog([model]).length>0,
72
74
  clients:model=>[...(codex.has(model.id)||isImageModel(model)?["codex"]:[]),...(antigravity.has(model.id)?["antigravity"]:[])],
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { readBoundedFileSync, MAX_MODEL_CACHE_FILE_BYTES } from "./bounded-file.mjs";
5
+ import { normalizeModelList } from "./model-catalog.mjs";
5
6
 
6
7
  export const MODEL_CACHE_SOFT_TTL_MS = 2 * 60 * 60 * 1000;
7
8
  export const MODEL_CACHE_HARD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -50,7 +51,7 @@ export function loadModelCacheEntry({
50
51
  const ageMs = Math.max(0, now() - savedAt);
51
52
  if (ageMs > resolvedHardTtlMs) return null;
52
53
  return {
53
- models: parsed.models,
54
+ models: normalizeModelList(parsed.models),
54
55
  savedAtMs: savedAt,
55
56
  ageMs,
56
57
  state: ageMs > resolvedSoftTtlMs ? "stale" : "fresh",
@@ -74,7 +75,7 @@ export function saveModelCache(models, {
74
75
  if (typeof isCurrent === "function" && !isCurrent()) return false;
75
76
  const filePath = modelCachePath(home);
76
77
  const tempPath = `${filePath}.${process.pid}.tmp`;
77
- const payload = { saved_at: new Date(now()).toISOString(), models };
78
+ const payload = { saved_at: new Date(now()).toISOString(), models: normalizeModelList(models) };
78
79
  const fingerprint = String(credentialFingerprint || "").trim();
79
80
  if (fingerprint) payload.credential_fingerprint = fingerprint;
80
81
  fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
@@ -0,0 +1,37 @@
1
+ const record = value => value !== null && typeof value === "object" && !Array.isArray(value);
2
+
3
+ function fillMissing(first, later) {
4
+ const updates = [];
5
+ for (const [key, value] of Object.entries(later)) {
6
+ const previous = Object.hasOwn(first, key) ? first[key] : undefined;
7
+ const next = previous == null || previous === "" ? value
8
+ : record(previous) && record(value) ? fillMissing(previous, value) : previous;
9
+ if (next !== previous) updates.push([key, next]);
10
+ }
11
+ return updates.length ? { ...first, ...Object.fromEntries(updates) } : first;
12
+ }
13
+
14
+ // Call only on a single source/account catalog. Explicit values, including
15
+ // false and empty capability arrays, win; duplicates only supply missing data.
16
+ export function uniqueModelEntries(models) {
17
+ const positions = new Map();let result = null;
18
+ for (let index = 0; index < models.length; index++) {
19
+ const model = models[index], id = model?.id;
20
+ if (typeof id === "string" && id && positions.has(id)) {
21
+ result ||= models.slice(0, index);
22
+ const position = positions.get(id);
23
+ result[position] = fillMissing(result[position], model);
24
+ } else {
25
+ if (typeof id === "string" && id) positions.set(id, result ? result.length : index);
26
+ if (result) result.push(model);
27
+ }
28
+ }
29
+ return result || models;
30
+ }
31
+
32
+ export function normalizeModelList(value) {
33
+ const data = Array.isArray(value) ? value : value?.data;
34
+ if (!Array.isArray(data)) return value;
35
+ const normalized = uniqueModelEntries(data);
36
+ return normalized === data ? value : Array.isArray(value) ? normalized : { ...value, data: normalized };
37
+ }
@@ -9,6 +9,7 @@ import {
9
9
  } from "./models.mjs";
10
10
  import { initializeModelRegistry } from "./startup.mjs";
11
11
  import { status } from "./status.mjs";
12
+ import { normalizeModelList } from "./model-catalog.mjs";
12
13
 
13
14
  const DEFAULT_TIMEOUT_MS = 5000;
14
15
 
@@ -29,7 +30,7 @@ function parsedCatalog(result) {
29
30
  if (!isValidModelList(models)) {
30
31
  throw new Error("Copilot models response contained no valid models");
31
32
  }
32
- return models;
33
+ return normalizeModelList(models);
33
34
  }
34
35
 
35
36
  function createModelRegistry() {
@@ -1,6 +1,7 @@
1
1
  import { isImageModel } from "./image-models.mjs";
2
2
  import { autoReviewReasoningEfforts } from "./models.mjs";
3
3
  import { modelDisplayName } from "./model-display.mjs";
4
+ import { uniqueModelEntries } from "./model-catalog.mjs";
4
5
  // Public metadata only. Credentials and provider transport never enter this layer.
5
6
  export const isProviderId = value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value)
6
7
  && !["constructor", "prototype"].includes(value);
@@ -11,7 +12,7 @@ export function modelReasoningEfforts(model) {
11
12
  }
12
13
 
13
14
  export function publicModelCatalog(models, { clients = () => [], selectable = () => false, maker = model => model.publisher || model.vendor || model.owned_by || "Unknown" } = {}) {
14
- return models.slice(0, 1000).filter(model => typeof model?.id === "string").map(model => ({
15
+ return uniqueModelEntries(models.slice(0, 1000)).filter(model => typeof model?.id === "string").map(model => ({
15
16
  id: model.id, ...(isImageModel(model) ? { kind: "image" } : {}), display_name: modelDisplayName(model), vendor: maker(model), ...(model.owned_by ? { owned_by: model.owned_by } : {}),
16
17
  endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
17
18
  ["messages", ["/v1/messages"]], ["images", ["/images/generations", "/v1/images/generations"]], ["image_edits", ["/images/edits", "/v1/images/edits"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { createRoutePlan } from "../route-plan.mjs";
3
3
  import { accessError } from "../access-settings.mjs";
4
4
  import { publicModelCatalog } from "../provider-metadata.mjs";
5
+ import { uniqueModelEntries } from "../model-catalog.mjs";
5
6
  import { claudeModelEntries } from "../claude-models.mjs";
6
7
  import { prepareResponsesPayload } from "../image-optimization.mjs";
7
8
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
@@ -190,7 +191,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
190
191
  clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
191
192
  capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.protocol_capabilities.responses?.values.reasoning_efforts || [])] })) }; },
192
193
  async discover({ signal } = {}) {
193
- const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
194
+ const models = [], cursors = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
194
195
  for (let page = 0; page < 25; page++) {
195
196
  const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
196
197
  if (!response.ok) {
@@ -201,14 +202,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
201
202
  const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
202
203
  let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
203
204
  if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
204
- for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//") || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
205
+ for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//")) throw accessError("ccdx_api_catalog_invalid", 502); }
205
206
  // A catalog listing is not evidence that every model supports every API.
206
- models.push(...value.data.map(model => ({ id: model.id, display: apiModelDisplay(model), metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
207
- ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] })));
208
- if (value.has_more !== true) return models;
207
+ models.push(...value.data);
208
+ if (value.has_more !== true) return uniqueModelEntries(models).map(model => ({ id: model.id, display: apiModelDisplay(model), metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
209
+ ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] }));
209
210
  // Follow only the native cursor on the configured origin, never an
210
211
  // upstream next-page URL that could disclose this source's credential.
211
- if (!value.data.length || value.last_id !== value.data.at(-1).id || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
212
+ if (!value.data.length || value.last_id !== value.data.at(-1).id || cursors.has(value.last_id) || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
213
+ cursors.add(value.last_id);
212
214
  const next = new URL(modelsUrl);next.searchParams.set("after_id", value.last_id);url = next.href;
213
215
  }
214
216
  throw accessError("ccdx_api_catalog_limit", 502);
@@ -18,6 +18,7 @@ import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
18
  import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
19
19
  import { catalogFailure, m365CatalogDiagnostic, m365CatalogRead } from "./m365-catalog-diagnostic.mjs";
20
20
  import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
21
+ import { uniqueModelEntries } from "../model-catalog.mjs";
21
22
 
22
23
  import { M365_API_BASE, M365_API_ORIGIN } from "./m365-endpoint.mjs";
23
24
  export { M365_API_BASE } from "./m365-endpoint.mjs";
@@ -53,13 +54,13 @@ export function m365ConversationId(body, headers = {}, profile = "m365") {
53
54
 
54
55
  export function m365Catalog(payload) {
55
56
  if (!payload || !Array.isArray(payload.data) || payload.data.length > 1000) throw m365Error("m365_catalog_invalid");
56
- const seen = new Set();
57
57
  for (const model of payload.data) {
58
58
  if (!model || typeof model.id !== "string" || !/^[A-Za-z0-9][\w.-]{0,127}$/.test(model.id)
59
- || seen.has(model.id) || !Array.isArray(model.supported_endpoints)) throw m365Error("m365_catalog_invalid");
60
- seen.add(model.id);
59
+ || model.supported_endpoints != null && !Array.isArray(model.supported_endpoints)) throw m365Error("m365_catalog_invalid");
61
60
  }
62
- return { data: payload.data };
61
+ const data = uniqueModelEntries(payload.data);
62
+ if (data.some(model => !Array.isArray(model.supported_endpoints))) throw m365Error("m365_catalog_invalid");
63
+ return { data };
63
64
  }
64
65
 
65
66
  export function m365Models(catalog, family) {
@@ -1,3 +1,4 @@
1
+ import { markToolActivity } from "./stream-performance.mjs";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { chatCompletions } from "./copilot.mjs";
3
4
  import { webStreamLines } from "./stream.mjs";
@@ -88,26 +89,38 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
88
89
  const messages = [];
89
90
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
90
91
 
91
- const messageContent = (content) => {
92
- if (typeof content === "string") return content;
92
+ const cacheFields = value => {
93
+ if (cacheSupport?.prompt_cache_breakpoint === true) {
94
+ if (value?.prompt_cache_breakpoint != null) return { prompt_cache_breakpoint: cloneJson(value.prompt_cache_breakpoint) };
95
+ if (value?.cache_control != null) return { prompt_cache_breakpoint: { mode: "explicit" } };
96
+ }
97
+ return cacheSupport?.cache_control === true && value?.cache_control != null ? { cache_control: cloneJson(value.cache_control) } : null;
98
+ };
99
+ const messageContent = (content, owner) => {
100
+ const ownerCache = cacheFields(owner);
101
+ if (typeof content === "string") return ownerCache ? [{ type: "text", text: content, ...ownerCache }] : content;
93
102
  if (content === null) return null;
94
103
  if (!Array.isArray(content)) throw chatCompatibilityError("message content", typeof content);
95
- if (content.length === 1 && ["input_text", "output_text", "text"].includes(content[0]?.type) && typeof content[0].text === "string") return content[0].text;
104
+ if (!ownerCache && content.length === 1 && ["input_text", "output_text", "text"].includes(content[0]?.type) && typeof content[0].text === "string" && !cacheFields(content[0])) return content[0].text;
96
105
  const parts = [];
97
106
  for (const part of content) {
98
107
  if (!part || typeof part !== "object") throw chatCompatibilityError("message content", part?.type);
99
108
  if (["input_text", "output_text", "text"].includes(part.type)) {
100
109
  if (typeof part.text !== "string") throw chatCompatibilityError("message content", part.type);
101
- parts.push({ type: "text", text: part.text });
110
+ parts.push({ type: "text", text: part.text, ...cacheFields(part) });
102
111
  } else if (["input_image", "image_url", "image"].includes(part.type)) {
103
112
  const imagePart = chatImagePart(part);
104
- if (imagePart) parts.push(imagePart);
113
+ if (imagePart) parts.push({ ...imagePart, ...cacheFields(part) });
105
114
  else throw chatCompatibilityError("message content", part.type);
106
115
  } else {
107
116
  throw chatCompatibilityError("message content", part.type);
108
117
  }
109
118
  }
110
- if (parts.length === 1 && parts[0].type === "text") return parts[0].text;
119
+ if (ownerCache) {
120
+ if (!parts.length) parts.push({ type: "text", text: "" });
121
+ const last = parts.length - 1;parts[last] = { ...ownerCache, ...parts[last] };
122
+ }
123
+ if (parts.length === 1 && parts[0].type === "text" && !Object.hasOwn(parts[0], "cache_control") && !Object.hasOwn(parts[0], "prompt_cache_breakpoint")) return parts[0].text;
111
124
  return parts;
112
125
  };
113
126
 
@@ -120,9 +133,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
120
133
  && ["user", "assistant", "system", "developer"].includes(item?.role)
121
134
  && Object.prototype.hasOwnProperty.call(item, "content");
122
135
  if (item?.type === "message" || isEasyMessage) {
123
- messages.push({ role: item.role, content: messageContent(item.content) });
136
+ messages.push({ role: item.role, content: messageContent(item.content, item) });
124
137
  } else if (item?.type === "agent_message") {
125
- if (typeof item.author !== "string" || typeof item.recipient !== "string" || !Array.isArray(item.content)) {
138
+ if (typeof item.author !== "string" || typeof item.recipient !== "string" || !Array.isArray(item.content) || item.encrypted_content != null) {
126
139
  throw chatCompatibilityError("input item", "agent_message");
127
140
  }
128
141
  const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
@@ -192,6 +205,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
192
205
  if (cacheSupport.prompt_cache_retention === true && ["in_memory", "24h"].includes(body.prompt_cache_retention)) {
193
206
  chatReq.prompt_cache_retention = body.prompt_cache_retention;
194
207
  }
208
+ if (cacheSupport.prompt_cache_options === true && body.prompt_cache_options && typeof body.prompt_cache_options === "object" && !Array.isArray(body.prompt_cache_options)) {
209
+ chatReq.prompt_cache_options = cloneJson(body.prompt_cache_options);
210
+ }
195
211
  }
196
212
  const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
197
213
  if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
@@ -383,6 +399,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
383
399
  emitEvent = async (...args) => {
384
400
  const written = await configuredEmitEvent(...args);
385
401
  if (written === false) throw downstreamClosed;
402
+ if (args[1]?.item || args[1]?.response?.output) markToolActivity(args[1]);
386
403
  return written;
387
404
  };
388
405
  let performanceOutputSeen = false;
@@ -1,3 +1,4 @@
1
+ import { markToolActivity } from "./stream-performance.mjs";
1
2
  import { defaultGithubProvider } from "./providers/github.mjs";
2
3
  import { observeContextSession } from "./context-metrics.mjs";
3
4
  import {
@@ -484,6 +485,7 @@ export function createResponsesHandler(options) {
484
485
  return;
485
486
  }
486
487
  const response = chatToResponses(JSON.parse(data), model, { toolChoice, ...(carbonBridge ? { toolAdapter: carbonBridge } : {}) });
488
+ markToolActivity(response);
487
489
  markResponseTerminal(response.status, {
488
490
  model: response.model || model, origin: "chat_completion", reason: response.incomplete_details?.reason,
489
491
  });
@@ -1,3 +1,4 @@
1
+ import { markToolActivity } from "./stream-performance.mjs";
1
2
  import { responses as copilotResponses } from "./copilot.mjs";
2
3
  import {
3
4
  logRequestFailure,
@@ -124,6 +125,7 @@ function inspectResponseSseEvent(state, eventName, data) {
124
125
  );
125
126
  }
126
127
  const eventType = event.type || (event.error ? "error" : eventName);
128
+ if (event.item || event.response?.output) markToolActivity(event);
127
129
  const previousSequence = state.lastSequence;
128
130
  state.lastSequence = event.sequence_number ?? previousSequence + 1;
129
131
  if (event.response && typeof event.response === "object" && !Array.isArray(event.response)) {
@@ -673,6 +675,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
673
675
  data,
674
676
  );
675
677
  response = reqContext.protectCompactionResult?.(response) || response;
678
+ markToolActivity(response);
676
679
  rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
677
680
  if (!resp[COMPACTION_USAGE_RECORDED]) recordResponsesUsage({
678
681
  surface: reqContext.surface,
@@ -722,6 +725,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
722
725
  continue;
723
726
  }
724
727
  }
728
+ markToolActivity(response);
725
729
  rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
726
730
  if (!reqContext.compactionUsageRecorded) recordResponsesUsage({
727
731
  surface: reqContext.surface,
@@ -128,6 +128,9 @@ function stripEncryptedReasoningValue(value, state) {
128
128
  }
129
129
 
130
130
  function stripEncryptedReasoningInputValue(item, state) {
131
+ // A sealed agent message may contain the entire delegated task. Removing
132
+ // opaque parts would turn a rejected task into an unrelated plaintext ask.
133
+ if (item?.type === "agent_message") return item;
131
134
  if (!isResponsesToolOutputItem(item)) {
132
135
  const out = stripEncryptedReasoningValue(item, state);
133
136
  if (item?.type === "message"
@@ -5,6 +5,7 @@ import { applicationLabel } from "./request-application.mjs";
5
5
  import { createContextMetrics } from "./context-metrics.mjs";
6
6
  import { createChangeSignal } from "./activity-events.mjs";
7
7
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
+ import { createToolActivity, isToolActivityOutput } from "./tool-activity.mjs";
8
9
 
9
10
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
10
11
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -217,6 +218,7 @@ function routeSnapshot(route) {
217
218
 
218
219
  export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString(), routeNames = PERFORMANCE_ROUTES } = {}) {
219
220
  const changes = createChangeSignal();
221
+ const toolActivity = createToolActivity({ now, changed: changes.changed });
220
222
  const routes = Object.fromEntries(routeNames.map((name) => [name, createRoutePerformance()]));
221
223
  const recentRequests = [];
222
224
  const contexts = createContextMetrics();
@@ -260,6 +262,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
260
262
  let terminalAt = null;
261
263
  const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null, output_tokens: null, max_output_tokens_requested: null, max_output_tokens_sent: null };
262
264
  let stopReason = null;
265
+ let toolObserver = null;
266
+ const tools = () => toolObserver ||= toolActivity.request(() => ({ application: client, session,
267
+ provider: provider || currentRequestContext()?.provider, model: model === "other" ? currentRequestContext()?.requestedModel || model : model }));
263
268
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
264
269
  if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
265
270
  request_id: safeRequestId, session_id: session ? session.slice(0, 16) : null, application: client, purpose: purposeLabel, route: routeName, provider, model, phase,
@@ -299,6 +304,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
299
304
  },
300
305
  upstreamStarted(streaming = true) {
301
306
  if (finished) return;
307
+ if (attempts && toolObserver) { toolObserver.finish("unknown");toolObserver = null; }
302
308
  const time = now();
303
309
  attempts += 1;
304
310
  if (attemptTimings.length === 3) attemptTimings.splice(1, 1);
@@ -322,6 +328,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
322
328
  },
323
329
  upstreamActivity() {
324
330
  if (finished) return;
331
+ toolObserver?.activity();
325
332
  lastActivityAt = now();
326
333
  if (phase !== "upstream_stream") { phase = "upstream_stream";changes.changed(); }
327
334
  },
@@ -344,6 +351,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
344
351
  setProvider: assignProvider,
345
352
  setPurpose(value) { if (!finished) { purposeLabel = requestPurpose(value);changes.changed(); } },
346
353
  observeSession(key) { if (!finished && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) session = key; },
354
+ observeToolInput(body, protocol) { if (!finished && purposeLabel === "conversation" && toolActivity.size) tools().input(body, protocol); },
355
+ observeToolOutput(value, protocol) { if (!finished && purposeLabel === "conversation" && isToolActivityOutput(value, protocol)) tools().output(value, protocol); },
347
356
  attemptCount() { return attempts; },
348
357
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
349
358
  observeContext(values) {
@@ -390,6 +399,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
390
399
  changes.changed();
391
400
  failed ||= finishFailed;
392
401
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
402
+ toolObserver?.finish(aborted ? "cancelled" : statusCode >= 400 ? "failed" : outcome);
393
403
  const emptyStreamCompletion = outcome === "completed" && upstreamStartedAt !== null
394
404
  && firstOutputAt === null && outputTokens === 0;
395
405
  if (emptyStreamCompletion) route.empty_stream_completions += 1;
@@ -464,6 +474,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
464
474
  contextSnapshot: () => contexts.snapshot(),
465
475
  activitySnapshot() {
466
476
  return {
477
+ tool_activity: toolActivity.snapshot(),
467
478
  by_route: Object.fromEntries(routeNames.map(name => [name, {
468
479
  terminal_outcomes: { totals: { ...routes[name].terminalTotals } },
469
480
  by_provider: Object.fromEntries([...routes[name].providers].map(([id, value]) => [id, {
@@ -477,6 +488,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
477
488
  },
478
489
  snapshot() {
479
490
  return {
491
+ tool_activity: toolActivity.snapshot(),
480
492
  by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
481
493
  active_requests: [...activeRequests.values()].map(snapshot => snapshot()),
482
494
  active_total: activeTotal,
@@ -557,3 +569,7 @@ export function markResponseErrorOrigin(origin) {
557
569
  export function markResponseTerminal(outcome, options) {
558
570
  tracker()?.terminal?.(outcome, options);
559
571
  }
572
+
573
+ export function markToolActivity(value, protocol = "responses") {
574
+ tracker()?.observeToolOutput?.(value, protocol);
575
+ }
@@ -0,0 +1,135 @@
1
+ import { hash } from "node:crypto";
2
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
+
4
+ export const TOOL_ACTIVITY_LIMITS = Object.freeze({ retained: 128, visible: 32, per_request: 32, stale_ms: 90_000, terminal_ms: 15_000, unknown_ms: 300_000 });
5
+ const pending = state => state === "preparing" || state === "waiting";
6
+ const nameOf = value => typeof value === "string" && /^[\w./:@-]{1,80}$/.test(value) && redactDiagnosticText(value) === value ? value : null;
7
+ const idOf = value => typeof value === "string" && value.length > 0 && value.length <= 256 ? value : null;
8
+ const toolTypes = new Set(["function_call", "custom_tool_call", "web_search_call", "file_search_call", "computer_call", "tool_search_call", "mcp_call", "shell_call", "image_generation_call", "program", "multi_agent_call"]);
9
+ const hostedTools = new Set(["web_search_call", "file_search_call", "mcp_call", "image_generation_call"]);
10
+ const messageResult = value => typeof value?.type === "string" && value.type.endsWith("_tool_result") && idOf(value.tool_use_id);
11
+ const items = value => Array.isArray(value) ? value.slice(0, 64) : [];
12
+ export function isToolActivityOutput(value, protocol = "responses") {
13
+ if (!value || typeof value !== "object") return false;
14
+ if (protocol === "messages") return ["tool_use", "server_tool_use", "mcp_tool_use"].includes((value.content_block || value).type) || Boolean(messageResult(value.content_block || value))
15
+ || items(value.content).some(item => ["tool_use", "server_tool_use", "mcp_tool_use"].includes(item?.type) || messageResult(item));
16
+ if (protocol === "gemini") return Boolean(value.functionCall) || items((value.response || value).candidates).some(candidate => items(candidate?.content?.parts).some(part => part?.functionCall));
17
+ return toolTypes.has((value.item || value).type) || items(value.response?.output || value.output).some(item => toolTypes.has(item?.type));
18
+ }
19
+
20
+ // Metadata only: arguments, input/output text and raw conversation/call IDs never leave the request.
21
+ export function createToolActivity({ now = Date.now, changed = () => {} } = {}) {
22
+ const entries = new Map();let sequence = 0;
23
+ function sweep() {
24
+ const time = now();
25
+ for (const [key, entry] of entries) {
26
+ if (pending(entry.state) && time - entry.updated >= TOOL_ACTIVITY_LIMITS.stale_ms) { entry.state = "unknown";entry.updated = time; }
27
+ if (!pending(entry.state) && time - entry.updated >= (entry.state === "unknown" ? TOOL_ACTIVITY_LIMITS.unknown_ms : TOOL_ACTIVITY_LIMITS.terminal_ms)) entries.delete(key);
28
+ }
29
+ }
30
+ const change = (entry, state) => {
31
+ if (!entry || entry.state === state || !pending(entry.state) && entry.state !== "unknown") return;
32
+ entry.state = state;entry.updated = now();changed();
33
+ };
34
+ return {
35
+ get size() { return entries.size; },
36
+ request(metadata) {
37
+ const aliases = new Map(), owned = new Set(), local = ++sequence;
38
+ let lastNotice = now();
39
+ const scope = () => { const m = metadata();return m.session ? `${m.application}\0${m.session}` : `request:${local}`; };
40
+ const keyFor = id => hash("sha256", `${scope()}\0${id}`, "hex");
41
+ function record(id, name, alias, resultId) {
42
+ id = idOf(id);const known = aliases.get(id) || aliases.get(alias);
43
+ if (known) { const next = nameOf(name);if (next && known.name !== next) { known.name = next;changed(); }if (id) aliases.set(id, known);if (idOf(resultId)) known.result_key = keyFor(resultId);return known; }
44
+ if (owned.size >= TOOL_ACTIVITY_LIMITS.per_request) return null;
45
+ sweep();const key = keyFor(id || `anonymous:${local}:${owned.size}`), m = metadata();
46
+ if (entries.has(key) && pending(entries.get(key).state)) return entries.get(key);
47
+ const entry = { id: `tool-${++sequence}`, application: m.application, provider: m.provider || "unknown", model: m.model,
48
+ name: nameOf(name), state: "preparing", updated: now(), key, scope: scope(), ...(idOf(resultId) ? { result_key: keyFor(resultId) } : {}) };
49
+ entries.set(key, entry);owned.add(entry);if (id) aliases.set(id, entry);if (alias !== undefined) aliases.set(alias, entry);
50
+ while (entries.size > TOOL_ACTIVITY_LIMITS.retained) entries.delete(entries.keys().next().value);
51
+ changed();return entry;
52
+ }
53
+ function output(value, protocol = "responses") {
54
+ if (!value || typeof value !== "object") return;
55
+ if (protocol === "messages") {
56
+ const block = value.type === "content_block_start" ? value.content_block : value;
57
+ if (["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type)) record(block.id, block.name, value.index);
58
+ else if (messageResult(block)) change(aliases.get(block.tool_use_id), block.is_error === true ? "failed" : "returned");
59
+ else if (Array.isArray(value.content)) for (const item of value.content.slice(0, 64)) output(item, protocol);
60
+ return;
61
+ }
62
+ if (protocol === "gemini") {
63
+ if (value.functionCall) {
64
+ const id = idOf(value.functionCall.id), name = nameOf(value.functionCall.name);
65
+ if (!id && !name) return;
66
+ const alias = id ? undefined : `gemini:${name}:${value.index ?? 0}`;
67
+ const prior = alias === undefined ? null : aliases.get(alias);
68
+ if (prior) prior.ambiguous = true;
69
+ record(id, name, alias);
70
+ }
71
+ else for (const candidate of items((value.response || value).candidates)) for (const [index, part] of items(candidate?.content?.parts).entries()) {
72
+ if (part?.functionCall) output({ functionCall: part.functionCall, index }, protocol);
73
+ }
74
+ return;
75
+ }
76
+ const item = value.item || value;
77
+ if (toolTypes.has(item.type)) {
78
+ const entry = record(item.call_id || item.id, item.name || item.type, value.output_index ?? item.id, item.call_id);
79
+ if (["completed", "failed", "cancelled"].includes(item.status) && hostedTools.has(item.type)) {
80
+ change(entry, item.status === "completed" ? "returned" : item.status);
81
+ }
82
+ } else if (value.response?.output || value.output) {
83
+ for (const item of items(value.response?.output || value.output)) output(item, protocol);
84
+ }
85
+ }
86
+ return {
87
+ output,
88
+ activity() {
89
+ const time = now();let active = false;
90
+ for (const entry of owned) if (entry.state === "preparing") { entry.updated = time;active = true; }
91
+ if (active && time - lastNotice >= 1000) { lastNotice = time;changed(); }
92
+ },
93
+ input(body, protocol) {
94
+ if (!entries.size || !metadata().session || !body || typeof body !== "object") return;
95
+ const results = [];
96
+ const inspect = part => {
97
+ if (["function_call_output", "custom_tool_call_output", "computer_call_output", "shell_call_output"].includes(part?.type)) results.push({ id: part.call_id });
98
+ else if (part?.type === "tool_result") results.push({ id: part.tool_use_id, error: part.is_error === true });
99
+ else if (part?.role === "tool") results.push({ id: part.tool_call_id });
100
+ else if (part?.functionResponse) results.push({ id: part.functionResponse.id, name: nameOf(part.functionResponse.name) });
101
+ };
102
+ if (Array.isArray(body.input)) for (const item of body.input.slice(-64)) inspect(item);
103
+ else if (Array.isArray(body.messages)) for (const message of body.messages.slice(-8)) {
104
+ inspect(message);if (Array.isArray(message?.content)) for (const part of message.content.slice(-64)) inspect(part);
105
+ }
106
+ else if (protocol === "gemini" && Array.isArray(body.contents)) for (const message of body.contents.slice(-8)) {
107
+ for (const part of items(message?.parts)) inspect(part);
108
+ }
109
+ for (const result of results) {
110
+ const resultKey = idOf(result.id) ? keyFor(result.id) : null;
111
+ let entry = resultKey ? entries.get(resultKey) || [...entries.values()].find(item => item.result_key === resultKey) : null;
112
+ if (!entry && result.name) {
113
+ const matches = [...entries.values()].filter(item => pending(item.state) && item.scope === scope() && item.name === result.name);
114
+ if (matches.length === 1) entry = matches[0];
115
+ }
116
+ change(entry, result.error ? "failed" : "returned");
117
+ }
118
+ },
119
+ finish(outcome) {
120
+ for (const entry of owned) {
121
+ entry.scope = scope();
122
+ change(entry, outcome === "completed" ? metadata().session && !entry.ambiguous ? "waiting" : "unknown" : ["failed", "cancelled"].includes(outcome) ? outcome : "unknown");
123
+ }
124
+ },
125
+ };
126
+ },
127
+ snapshot() {
128
+ sweep();const time = now(), all = [...entries.values()].reverse();
129
+ all.sort((a, b) => Number(pending(b.state)) - Number(pending(a.state)));
130
+ return { items: all.slice(0, TOOL_ACTIVITY_LIMITS.visible).map(({ key, scope, result_key, ambiguous, updated, ...entry }) => ({ ...entry,
131
+ expires_in_ms: Math.max(0, (pending(entry.state) ? TOOL_ACTIVITY_LIMITS.stale_ms : entry.state === "unknown" ? TOOL_ACTIVITY_LIMITS.unknown_ms : TOOL_ACTIVITY_LIMITS.terminal_ms) - (time - updated)) })),
132
+ omitted: Math.max(0, all.length - TOOL_ACTIVITY_LIMITS.visible), limits: TOOL_ACTIVITY_LIMITS };
133
+ },
134
+ };
135
+ }