codex-copilot-dx 1.2.2 → 1.2.4

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.
@@ -12,7 +12,7 @@ export function m365HelperEnvironment(env = process.env) {
12
12
  return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
13
13
  }
14
14
 
15
- export function requestM365Token({ account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
15
+ function requestM365Helper({ action = "token", account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
16
16
  if (signal?.aborted) return Promise.reject(abortError(signal));
17
17
  return new Promise((resolve, reject) => {
18
18
  let child, timer, finished = false, bytes = 0;
@@ -46,6 +46,12 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
46
46
  finish(m365Error(/^m365_[a-z_]+$/.test(result.error?.code || "") ? result.error.code : "m365_auth_failed"));return;
47
47
  }
48
48
  try {
49
+ if (action === "accounts") {
50
+ if (!Array.isArray(result.accounts) || result.accounts.length > 128) throw Error();
51
+ for (const value of result.accounts) m365AccountKey(value);
52
+ if (result.windowsLogin !== null && (typeof result.windowsLogin !== "string" || result.windowsLogin.length > 320 || /[\r\n\0]/.test(result.windowsLogin))) throw Error();
53
+ finish(null, result);return;
54
+ }
49
55
  m365AccountKey(result.account);
50
56
  if (typeof result.token !== "string" || !result.token || /\s/.test(result.token)
51
57
  || !Number.isFinite(result.expiresAt) || result.expiresAt <= Date.now()) throw Error();
@@ -53,11 +59,14 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
53
59
  } catch { finish(m365Error("m365_auth_response_invalid"));return; }
54
60
  finish(null, result);
55
61
  });
56
- child.stdin.end(JSON.stringify({ action: "token", account: account || null }));
62
+ child.stdin.end(JSON.stringify({ action, account: account || null }));
57
63
  });
58
64
  }
59
65
 
60
- export function createM365Auth({ home, env = process.env, acquire = requestM365Token, now = Date.now } = {}) {
66
+ export const requestM365Token = options => requestM365Helper({ ...options, action: "token" });
67
+ export const requestM365Accounts = options => requestM365Helper({ ...options, action: "accounts" });
68
+
69
+ export function createM365Auth({ home, env = process.env, account, acquire = requestM365Token, now = Date.now } = {}) {
61
70
  let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0, checkedAt = null;
62
71
  const snapshot = () => ({ token_cached: Boolean(cached && cached.expiresAt > now()),
63
72
  token_expires_in_ms: cached ? Math.max(0, cached.expiresAt - now()) : null,
@@ -71,7 +80,7 @@ export function createM365Auth({ home, env = process.env, acquire = requestM365T
71
80
  if (!flight) {
72
81
  const controller = new AbortController(), current = generation;
73
82
  const entry = { controller, waiters: 0, settled: false, promise: null };
74
- entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || readM365Account({ home }), env, signal: controller.signal }))
83
+ entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || account || readM365Account({ home }), env, signal: controller.signal }))
75
84
  .then(result => {
76
85
  if (current !== generation || controller.signal.aborted) throw abortError(controller.signal);
77
86
  m365AccountKey(result.account);
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto";
2
+ import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
3
+ import { withFileLockSync } from "../lock.mjs";
4
+ import fs from "node:fs";
5
+
6
+ const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
7
+ { code: "m365_account_changed", statusCode: 409 });
8
+ const hash = value => createHash("sha256").update(value).digest("hex");
9
+
10
+ export function createM365ConversationGuard({ home } = {}) {
11
+ const { directory, conversations: file } = m365Paths({ home });
12
+ let cached;
13
+ return (account, body, headers = {}) => {
14
+ const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
15
+ let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
16
+ if (!session && typeof body.metadata?.user_id === "string") {
17
+ try { session = JSON.parse(body.metadata.user_id)?.session_id; } catch { session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1]; }
18
+ }
19
+ const first = items.find(item => item?.role === "user");
20
+ const key = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session)
21
+ ? hash(`session\0${session}`) : first ? hash(`first\0${JSON.stringify(first)}`) : typeof body.input === "string" ? hash(`first\0${body.input}`) : null;
22
+ const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
23
+ || items.some(item => item?.role === "assistant" || item?.role === "tool" || /(?:call|output|reasoning|compaction)/.test(item?.type || "")
24
+ || Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result"));
25
+ if (!key) { if (account.history_isolation && hasHistory) throw changed();return; }
26
+ const owner = m365AccountKey(account);
27
+ if (cached?.[key] === owner) return;
28
+ if (cached?.[key] && cached[key] !== owner) throw changed();
29
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
30
+ withFileLockSync(`${file}.lock`, () => {
31
+ const saved = readM365Json(file, { owners: {} });
32
+ if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
33
+ || Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
34
+ const owners = saved.owners;
35
+ if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory) throw changed();
36
+ if (owners[key]) { cached = owners;return; }
37
+ owners[key] = owner;
38
+ while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
39
+ writeM365Json(file, { owners });cached = owners;
40
+ });
41
+ };
42
+ }
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { createM365Auth, m365Error } from "./m365-auth.mjs";
3
- import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Json } from "../m365-settings.mjs";
3
+ import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Binding } from "../m365-settings.mjs";
4
4
  import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
5
5
  import { prepareResponsesPayload, summarizeReqBody } from "../image-optimization.mjs";
6
6
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
@@ -15,6 +15,7 @@ import { removeNativeImageTools } from "../responses-image-tools.mjs";
15
15
  import { resolveClaudeModel } from "../claude-models.mjs";
16
16
  import { modelReasoningEfforts } from "../provider-metadata.mjs";
17
17
  import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
+ import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
18
19
 
19
20
  export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
20
21
  const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
@@ -66,9 +67,11 @@ export function m365Models(catalog, family) {
66
67
  && model.supported_endpoints.some(endpoint => endpoint === "/responses" || endpoint === "/v1/responses"));
67
68
  }
68
69
 
69
- export function createM365Provider({ home, env = process.env, auth = createM365Auth({ home, env }), fetchImpl,
70
+ export function createM365Provider({ home, env = process.env, account: accountOverride, persist = true,
71
+ auth = createM365Auth({ home, env, account: accountOverride }), fetchImpl,
70
72
  createNetwork, now = Date.now, log = (kind, message) => console.log(status(kind, message)), onCatalog = () => {} } = {}) {
71
73
  const paths = m365Paths({ home });
74
+ const guardConversation = createM365ConversationGuard({ home });
72
75
  let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
73
76
  let network = null, networkFlight = null, cacheTtlAdjustments = 0;
74
77
  const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
@@ -95,7 +98,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
95
98
  registry.source = source;registry.cacheSavedAtMs = savedAt;registry.cacheState = now() - savedAt < SOFT_TTL_MS ? "fresh" : "stale";
96
99
  }
97
100
  try {
98
- account = readM365Account({ home });
101
+ account = accountOverride || readM365Account({ home });
99
102
  const saved = readM365Json(paths.catalog);
100
103
  if (account && saved?.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
101
104
  && now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
@@ -143,10 +146,11 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
143
146
  if (!response.ok) throw m365Error(`m365_catalog_http_${response.status}`);
144
147
  let value;try { value = m365Catalog(JSON.parse(raw)); } catch { throw m365Error("m365_catalog_invalid"); }
145
148
  if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
146
- account = credential.account;
147
- writeM365Json(paths.account, account);
148
- writeM365Json(paths.catalog, { account_key: m365AccountKey(account), saved_at: now(), models: value });
149
- applyCatalog(value, "live", now());state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
149
+ const savedAt = now();
150
+ const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
151
+ if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), saved_at: savedAt, models: value }, { home, expectedAccount: account });
152
+ account = nextAccount;
153
+ applyCatalog(value, "live", savedAt);state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
150
154
  try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
151
155
  return value;
152
156
  })().catch(error => {
@@ -180,6 +184,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
180
184
  cacheModelEndpoints() {},
181
185
  async responses(body, options = {}) {
182
186
  const model = selectedModel(body.model, "gpt");
187
+ if (account) guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers);
183
188
  const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
184
189
  currentInputStart: options.currentInputStart || 0, signal: options.signal,
185
190
  profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
@@ -197,6 +202,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
197
202
  async messages(body, options = {}) {
198
203
  if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
199
204
  const model = selectedModel(body.model, "claude");
205
+ if (account) guardConversation(account, body, options.headers);
200
206
  const efforts = modelReasoningEfforts(model);
201
207
  if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
202
208
  throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
@@ -236,7 +242,12 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
236
242
  return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
237
243
  },
238
244
  },
239
- snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login } : null,
245
+ commitSelection(expectedAccount) {
246
+ if (!catalog || state !== "ready" || !account) throw m365Error("m365_not_ready");
247
+ writeM365Binding(account, { account_key: m365AccountKey(account), saved_at: catalogAt, models: catalog }, { home, expectedAccount });
248
+ persist = true;
249
+ },
250
+ snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
240
251
  network: network?.snapshot() || null,
241
252
  cache_ttl_adjustments: cacheTtlAdjustments,
242
253
  models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
@@ -29,7 +29,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
29
29
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
30
30
  const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"], color_theme: ["action", "theme"],
31
31
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
32
- provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort"] }[input.action];
32
+ provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
33
33
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
34
34
  if (input.action === "preference") {
35
35
  writeServicePreference(input.key, input.value, options);
@@ -51,9 +51,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
51
51
  try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
52
52
  } else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
53
53
  else {
54
- if (!providerRuntime || !["on", "off", "switch", "auto-review"].includes(input.operation)) throw new Error("Invalid provider operation");
54
+ if (!providerRuntime || !["on", "off", "switch", "auto-review", "account"].includes(input.operation)) throw new Error("Invalid provider operation");
55
+ if (input.operation === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw new Error("Select an available company account");
55
56
  if (input.operation === "on" && env.CCDX_M365 === "0") throw new Error("Microsoft 365 is disabled by CCDX_M365=0");
56
- await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort });
57
+ await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort,
58
+ ...(input.operation === "account" ? { account_id: input.account_id } : {}) });
57
59
  }
58
60
  return snapshot();
59
61
  }