@codetelemetry/mcp 0.3.0 → 0.3.7

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
@@ -11,10 +11,18 @@ artifact. The CodeTelemetry web application, storage, and infrastructure are not
11
11
  part of this package. See [PUBLICATION.md](PUBLICATION.md) for the enforced
12
12
  publication boundary.
13
13
 
14
+ The zero-config Connect CLI is published independently so onboarding does not
15
+ depend on the MCP sizing release:
16
+
17
+ ```bash
18
+ npx -y @codetelemetry/connect login
19
+ # Add --codex when configuring OpenAI Codex.
20
+ ```
21
+
14
22
  ## Install (Claude Code)
15
23
 
16
24
  ```bash
17
- claude mcp add codetelemetry -- npx -y @codetelemetry/mcp
25
+ claude mcp add codetelemetry -- npx -y --package=@codetelemetry/mcp codetelemetry-mcp
18
26
  ```
19
27
 
20
28
  or in `.mcp.json` — pinning the version you expect, so what a client launches is
@@ -23,7 +31,7 @@ deterministic (see [Releases & discovery](#releases--discovery)):
23
31
  ```json
24
32
  {
25
33
  "mcpServers": {
26
- "codetelemetry": { "command": "npx", "args": ["-y", "@codetelemetry/mcp@0.3.0"] }
34
+ "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.3.7", "codetelemetry-mcp"] }
27
35
  }
28
36
  }
29
37
  ```
@@ -42,8 +50,12 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
42
50
  | `verify_telemetry` | Poll the connectivity check until the probe lands. |
43
51
  | `onboard` | One-shot: key → config → test → verify, returns a checklist. |
44
52
  | `status` | Read-only diagnostics (no secrets). |
45
- | `get_cost_signal` | Read recent observed model cost and CodeTelemetry fee for the caller's own telemetry. |
46
- | `search_sessions` | Search the same bounded session index as the UI by prompt/title text, assistant, repo, model, duration, and sort order; returns metadata and match fields, never prompt text. |
53
+ | `get_cost_signal` | Read recent tokens and observed model cost for the caller's own telemetry, with what CodeTelemetry meters for those tokens shown separately. |
54
+ | `search_sessions` | Search the same bounded session index as the UI by prompt/title text, assistant, repo, model, duration, and sort order; returns metadata and match fields, never prompt text. Results are ordered by `lastSeen` (most recently active, not started or finished); `activity: "substantive"` keeps only sessions with observed agent work and counts what it left out. |
55
+ | `read_session_events` | Read one of your sessions' recorded events in order (prompts, assistant text, commands, tool inputs and outputs, exit codes), after privacy filtering and independent of any interpretation. Pages with a cursor, jumps by position or time, filters by kind, recorded outcome, tool or text, shows the context around an event, and expands one event's full retained text. |
56
+ | `interpret_session` | Read CodeTelemetry's own bounded, materialized interpretation of a session: optional hints to verify against the recorded events. Evidence cards are opt-in, privacy-filtered and pointer-resolved; the tool never replays raw telemetry. |
57
+ | `compare_sessions` | Compare 2–10 distinct materialized personal sessions. Returns descriptive repeated patterns, evidence pointers, denominators, observed outcome counterexamples, one-offs and confidence limits; it never replays raw telemetry or claims causation. |
58
+ | `plan_next_session` | Produce a bounded, read-only next-session recommendation from authorized materialized precedents. Historical advice is cited, generic fallback is labelled, and it never executes work or mutates plans/issues. |
47
59
  | `get_session_performance` | Measure a session timeline's fresh/cache latency, rows, bytes, and query phases without returning content. |
48
60
  | `find_similar_session_errors` | Find other personal-scope sessions with matching normalized failure signatures and report query performance. |
49
61
  | `estimate_task_size` | T-shirt size a proposed task (free-form text or a Linear-shaped issue) from the caller's own history. |
@@ -200,7 +212,7 @@ npm run smoke -- --tarball out.tgz --require-auth # exactly these by
200
212
  and read `server`:
201
213
 
202
214
  ```jsonc
203
- "server": { "name": "codetelemetry", "version": "0.3.0", "registryHash": "f2b6568d…", "toolCount": 15 }
215
+ "server": { "name": "codetelemetry", "version": "0.3.7", "registryHash": "cc2fcdcc…", "toolCount": 18 }
204
216
  ```
205
217
 
206
218
  **When a long-running client sees a new tool.** `tools/list` is requested once, at
@@ -86,6 +86,7 @@ export type SessionPerformanceResult = {
86
86
  };
87
87
  export type SessionSearchHit = {
88
88
  sessionId: string;
89
+ sessionUrl?: string;
89
90
  title: string;
90
91
  titleIsId: boolean;
91
92
  sessionName?: string;
@@ -101,11 +102,12 @@ export type SessionSearchHit = {
101
102
  prompts: number;
102
103
  invocations: number;
103
104
  tools: number;
105
+ activity?: "substantive" | "instrumentation_only" | "insufficient_evidence";
104
106
  match?: {
105
107
  fields: string[];
106
108
  };
107
109
  };
108
- export type SessionSearchReport = {
110
+ export type SessionSearchLegacyReport = {
109
111
  results: SessionSearchHit[];
110
112
  total: number;
111
113
  limit: number;
@@ -113,6 +115,11 @@ export type SessionSearchReport = {
113
115
  hasMore: boolean;
114
116
  nextOffset: number | null;
115
117
  query: Record<string, unknown>;
118
+ activityCounts?: {
119
+ substantive: number;
120
+ instrumentationOnly: number;
121
+ insufficientEvidence: number;
122
+ };
116
123
  repos: string[];
117
124
  promptSearchAvailable: boolean;
118
125
  promptSearchTruncated?: boolean;
@@ -120,9 +127,35 @@ export type SessionSearchReport = {
120
127
  contentRedacted: true;
121
128
  truncated?: boolean;
122
129
  };
123
- export type SessionSearchResult = {
130
+ export type SessionPrecedentReport = {
131
+ precedents: {
132
+ mode: "semantic" | "lexical";
133
+ degraded: boolean;
134
+ reason?: "embedding_unavailable" | "embedding_failed";
135
+ total: number;
136
+ limit: number;
137
+ offset: number;
138
+ hasMore: boolean;
139
+ candidates: number;
140
+ lookbackDays: number;
141
+ hits: Array<{
142
+ sessionId: string;
143
+ service: string;
144
+ sessionUrl?: string;
145
+ sourceGeneration: string;
146
+ outcome: "success" | "partial" | "failed" | "unknown";
147
+ complexity: "low" | "medium" | "high" | "unknown";
148
+ semanticScore: number;
149
+ lexicalScore: number;
150
+ reasons: string[];
151
+ interpretationReadiness: "ready" | "partial";
152
+ }>;
153
+ };
154
+ };
155
+ export type SessionSearchReport = SessionSearchLegacyReport | SessionPrecedentReport;
156
+ export type SessionSearchResult<TReport extends SessionSearchReport = SessionSearchLegacyReport> = {
124
157
  ok: boolean;
125
- report: SessionSearchReport | null;
158
+ report: TReport | null;
126
159
  httpStatus: number;
127
160
  error: string | null;
128
161
  message: string | null;
@@ -337,13 +370,19 @@ export declare function findSimilarSessionErrors(opts: {
337
370
  timeoutMs?: number;
338
371
  }): Promise<SimilarSessionErrorsResult>;
339
372
  export declare const SESSION_SEARCH_REQUEST_TIMEOUT_MS = 65000;
340
- export declare function searchCodingSessions(opts: {
373
+ type SessionSearchOptions<TQuery extends Record<string, unknown>> = {
341
374
  key: string;
342
375
  url: string;
343
- query: Record<string, unknown>;
376
+ query: TQuery;
344
377
  fetchImpl?: FetchLike;
345
378
  timeoutMs?: number;
346
- }): Promise<SessionSearchResult>;
379
+ };
380
+ export declare function searchCodingSessions(opts: SessionSearchOptions<Record<string, unknown> & {
381
+ precedent: true;
382
+ }>): Promise<SessionSearchResult<SessionPrecedentReport>>;
383
+ export declare function searchCodingSessions(opts: SessionSearchOptions<Record<string, unknown> & {
384
+ precedent?: false;
385
+ }>): Promise<SessionSearchResult>;
347
386
  export declare function estimateTaskSize(opts: {
348
387
  key: string;
349
388
  url: string;
@@ -377,3 +416,66 @@ export declare function estimateLinearIssue(opts: {
377
416
  fetchImpl?: FetchLike;
378
417
  timeoutMs?: number;
379
418
  }): Promise<LinearIssueEstimateResult>;
419
+ export declare function interpretSession(opts: {
420
+ key: string;
421
+ url: string;
422
+ sessionId: string;
423
+ service?: string;
424
+ evidenceIds?: string[];
425
+ snapshot?: string;
426
+ fetchImpl?: FetchLike;
427
+ timeoutMs?: number;
428
+ }): Promise<{
429
+ ok: boolean;
430
+ value: Record<string, unknown> | null;
431
+ httpStatus: number;
432
+ error: string | null;
433
+ message: string | null;
434
+ }>;
435
+ export declare function readSessionEvents(opts: {
436
+ key: string;
437
+ url: string;
438
+ input: Record<string, unknown>;
439
+ fetchImpl?: FetchLike;
440
+ timeoutMs?: number;
441
+ }): Promise<{
442
+ ok: boolean;
443
+ value: Record<string, unknown> | null;
444
+ httpStatus: number;
445
+ error: string | null;
446
+ message: string | null;
447
+ }>;
448
+ export declare function compareSessions(opts: {
449
+ key: string;
450
+ url: string;
451
+ sessions: Array<{
452
+ sessionId: string;
453
+ service?: string;
454
+ }>;
455
+ fetchImpl?: FetchLike;
456
+ timeoutMs?: number;
457
+ }): Promise<{
458
+ ok: boolean;
459
+ value: Record<string, unknown> | null;
460
+ httpStatus: number;
461
+ error: string | null;
462
+ message: string | null;
463
+ }>;
464
+ export declare function planNextSession(opts: {
465
+ key: string;
466
+ url: string;
467
+ taskText?: string;
468
+ draftPlan?: string;
469
+ repo?: string;
470
+ model?: string;
471
+ environment?: string;
472
+ fetchImpl?: FetchLike;
473
+ timeoutMs?: number;
474
+ }): Promise<{
475
+ ok: boolean;
476
+ value: Record<string, unknown> | null;
477
+ httpStatus: number;
478
+ error: string | null;
479
+ message: string | null;
480
+ }>;
481
+ export {};
@@ -202,3 +202,60 @@ export async function estimateLinearIssue(opts) {
202
202
  message: result.message,
203
203
  };
204
204
  }
205
+ export async function interpretSession(opts) {
206
+ const result = await postAgent({
207
+ ...opts,
208
+ timeoutMs: opts.timeoutMs ?? 15_000,
209
+ body: {
210
+ sessionId: opts.sessionId,
211
+ ...(opts.service === undefined ? {} : { service: opts.service }),
212
+ ...(opts.evidenceIds === undefined ? {} : { evidenceIds: opts.evidenceIds }),
213
+ ...(opts.snapshot === undefined ? {} : { snapshot: opts.snapshot }),
214
+ },
215
+ });
216
+ return {
217
+ ok: result.ok,
218
+ value: result.value ?? null,
219
+ httpStatus: result.httpStatus,
220
+ error: result.error,
221
+ message: result.message,
222
+ };
223
+ }
224
+ export async function readSessionEvents(opts) {
225
+ const result = await postAgent({ ...opts, timeoutMs: opts.timeoutMs ?? 15_000, body: opts.input });
226
+ return {
227
+ ok: result.ok,
228
+ value: result.value ?? null,
229
+ httpStatus: result.httpStatus,
230
+ error: result.error,
231
+ message: result.message,
232
+ };
233
+ }
234
+ export async function compareSessions(opts) {
235
+ const result = await postAgent({
236
+ ...opts,
237
+ timeoutMs: opts.timeoutMs ?? 10_000,
238
+ body: { sessions: opts.sessions },
239
+ });
240
+ return {
241
+ ok: result.ok,
242
+ value: result.value ?? null,
243
+ httpStatus: result.httpStatus,
244
+ error: result.error,
245
+ message: result.message,
246
+ };
247
+ }
248
+ export async function planNextSession(opts) {
249
+ const result = await postAgent({
250
+ ...opts,
251
+ timeoutMs: opts.timeoutMs ?? 10_000,
252
+ body: {
253
+ ...(opts.taskText === undefined ? {} : { taskText: opts.taskText }),
254
+ ...(opts.draftPlan === undefined ? {} : { draftPlan: opts.draftPlan }),
255
+ ...(opts.repo === undefined ? {} : { repo: opts.repo }),
256
+ ...(opts.model === undefined ? {} : { model: opts.model }),
257
+ ...(opts.environment === undefined ? {} : { environment: opts.environment }),
258
+ },
259
+ });
260
+ return { ok: result.ok, value: result.value ?? null, httpStatus: result.httpStatus, error: result.error, message: result.message };
261
+ }
@@ -2,8 +2,13 @@ export type Endpoints = {
2
2
  apiBase: string;
3
3
  ingestEndpoint: string;
4
4
  deviceCodeUrl: string;
5
+ deviceScopedCodeUrl: string;
6
+ deviceOrganizationCodeUrl: string;
5
7
  deviceApproveUrl: string;
8
+ deviceScopedApproveUrl: string;
9
+ deviceOrganizationApproveUrl: string;
6
10
  deviceTokenUrl: string;
11
+ deviceScopedTokenUrl: string;
7
12
  connectivityUrl: string;
8
13
  verificationUri: string;
9
14
  agentCostUrl: string;
@@ -12,6 +17,10 @@ export type Endpoints = {
12
17
  agentSessionSearchUrl: string;
13
18
  agentTaskSizeUrl: string;
14
19
  agentLinearIssueSizeUrl: string;
20
+ agentInterpretSessionUrl: string;
21
+ agentReadSessionEventsUrl: string;
22
+ agentCompareSessionsUrl: string;
23
+ agentPlanNextSessionUrl: string;
15
24
  };
16
25
  export declare function resolveEndpoints(overrides?: Partial<{
17
26
  apiBase: string;
@@ -9,8 +9,13 @@ export function resolveEndpoints(overrides = {}) {
9
9
  apiBase,
10
10
  ingestEndpoint,
11
11
  deviceCodeUrl: `${apiBase}/api/device/code`,
12
+ deviceScopedCodeUrl: `${apiBase}/api/device/code/scope-v1`,
13
+ deviceOrganizationCodeUrl: `${apiBase}/api/device/code/organization-v1`,
12
14
  deviceApproveUrl: `${apiBase}/api/device/approve`,
15
+ deviceScopedApproveUrl: `${apiBase}/api/device/approve/scope-v1`,
16
+ deviceOrganizationApproveUrl: `${apiBase}/api/device/approve/organization-v1`,
13
17
  deviceTokenUrl: `${apiBase}/api/device/token`,
18
+ deviceScopedTokenUrl: `${apiBase}/api/device/token/scope-v1`,
14
19
  connectivityUrl: `${apiBase}/api/connectivity/check`,
15
20
  verificationUri: `${apiBase}/activate`,
16
21
  agentCostUrl: `${apiBase}/api/agent/cost`,
@@ -19,6 +24,10 @@ export function resolveEndpoints(overrides = {}) {
19
24
  agentSessionSearchUrl: `${apiBase}/api/agent/session-search`,
20
25
  agentTaskSizeUrl: `${apiBase}/api/agent/task-size`,
21
26
  agentLinearIssueSizeUrl: `${apiBase}/api/agent/linear-issue-size`,
27
+ agentInterpretSessionUrl: `${apiBase}/api/agent/interpret-session`,
28
+ agentReadSessionEventsUrl: `${apiBase}/api/agent/read-session-events`,
29
+ agentCompareSessionsUrl: `${apiBase}/api/agent/compare-sessions`,
30
+ agentPlanNextSessionUrl: `${apiBase}/api/agent/plan-next-session`,
22
31
  };
23
32
  }
24
33
  export function resolveSettingsPath(opts = {}) {
@@ -1,7 +1,22 @@
1
1
  import type { FetchLike } from "./otlp.ts";
2
+ export type ConnectivityState = "scope_verified" | "connected" | "ingestion_delay" | "wrong_scope" | "budget_exhausted" | "invalid_key" | "dashboard_read_failure" | "unknown_failure";
3
+ export type KeyScope = {
4
+ tenantId: string;
5
+ teamId: string | null;
6
+ billingAccountId: string;
7
+ };
8
+ export type ExpectedKeyScope = Partial<KeyScope>;
2
9
  export type CheckResult = {
3
10
  seen: boolean;
4
11
  httpStatus: number;
12
+ state: ConnectivityState;
13
+ scope?: KeyScope;
14
+ budget?: {
15
+ creditBalanceUsd: number;
16
+ seats: number;
17
+ remainingIncludedTokens: number;
18
+ } | null;
19
+ mismatches?: (keyof KeyScope)[];
5
20
  };
6
21
  export declare function checkOnce(opts: {
7
22
  key: string;
@@ -9,8 +24,16 @@ export declare function checkOnce(opts: {
9
24
  probeId: string;
10
25
  fetchImpl?: FetchLike;
11
26
  timeoutMs?: number;
27
+ expected?: ExpectedKeyScope;
28
+ }): Promise<CheckResult>;
29
+ export declare function verifyScope(opts: {
30
+ key: string;
31
+ connectivityUrl: string;
32
+ fetchImpl?: FetchLike;
33
+ timeoutMs?: number;
34
+ expected: ExpectedKeyScope;
12
35
  }): Promise<CheckResult>;
13
- export type ConfirmResult = {
36
+ export type ConfirmResult = CheckResult & {
14
37
  landed: boolean;
15
38
  elapsedMs: number;
16
39
  polls: number;
@@ -24,4 +47,5 @@ export declare function confirmLanded(opts: {
24
47
  timeoutMs?: number;
25
48
  onTick?: (poll: number) => void;
26
49
  now?: () => number;
50
+ expected?: ExpectedKeyScope;
27
51
  }): Promise<ConfirmResult>;
@@ -8,17 +8,71 @@ export async function checkOnce(opts) {
8
8
  const res = await fetchImpl(opts.connectivityUrl, {
9
9
  method: "POST",
10
10
  headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
11
- body: JSON.stringify({ probeId: opts.probeId }),
11
+ body: JSON.stringify({ probeId: opts.probeId, ...(opts.expected ? { expected: opts.expected } : {}) }),
12
12
  signal: ac.signal,
13
13
  });
14
- let seen = false;
14
+ let payload = {};
15
15
  try {
16
- const json = (await res.json());
17
- seen = !!json?.seen;
16
+ payload = ((await res.json()) ?? {});
18
17
  }
19
18
  catch {
20
19
  }
21
- return { seen, httpStatus: res.status };
20
+ const seen = payload.seen === true;
21
+ const state = typeof payload.state === "string"
22
+ ? payload.state
23
+ : seen
24
+ ? "connected"
25
+ : res.status === 401
26
+ ? "invalid_key"
27
+ : res.status >= 500
28
+ ? "dashboard_read_failure"
29
+ : "ingestion_delay";
30
+ return {
31
+ seen,
32
+ httpStatus: res.status,
33
+ state,
34
+ ...(payload.scope ? { scope: payload.scope } : {}),
35
+ ...(payload.budget !== undefined ? { budget: payload.budget } : {}),
36
+ ...(payload.mismatches ? { mismatches: payload.mismatches } : {}),
37
+ };
38
+ }
39
+ finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+ export async function verifyScope(opts) {
44
+ const key = assertKey(opts.key);
45
+ const fetchImpl = opts.fetchImpl ?? fetch;
46
+ const ac = new AbortController();
47
+ const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 8_000);
48
+ try {
49
+ const res = await fetchImpl(opts.connectivityUrl, {
50
+ method: "POST",
51
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
52
+ body: JSON.stringify({ scopeOnly: true, expected: opts.expected }),
53
+ signal: ac.signal,
54
+ });
55
+ let payload = {};
56
+ try {
57
+ payload = ((await res.json()) ?? {});
58
+ }
59
+ catch {
60
+ }
61
+ const state = typeof payload.state === "string"
62
+ ? payload.state
63
+ : res.status === 401
64
+ ? "invalid_key"
65
+ : res.status >= 500
66
+ ? "dashboard_read_failure"
67
+ : "unknown_failure";
68
+ return {
69
+ seen: false,
70
+ httpStatus: res.status,
71
+ state,
72
+ ...(payload.scope ? { scope: payload.scope } : {}),
73
+ ...(payload.budget !== undefined ? { budget: payload.budget } : {}),
74
+ ...(payload.mismatches ? { mismatches: payload.mismatches } : {}),
75
+ };
22
76
  }
23
77
  finally {
24
78
  clearTimeout(timer);
@@ -31,24 +85,34 @@ export async function confirmLanded(opts) {
31
85
  const now = opts.now ?? (() => Date.now());
32
86
  const start = now();
33
87
  let polls = 0;
88
+ let last = null;
34
89
  while (true) {
35
90
  const remaining = timeout - (now() - start);
36
- if (remaining <= 0)
37
- return { landed: false, elapsedMs: now() - start, polls };
91
+ if (remaining <= 0) {
92
+ const fallback = { seen: false, httpStatus: 0, state: "ingestion_delay" };
93
+ return { ...(last ?? fallback), landed: false, elapsedMs: now() - start, polls };
94
+ }
38
95
  polls += 1;
39
96
  opts.onTick?.(polls);
40
- const { seen } = await checkOnce({
97
+ const checked = await checkOnce({
41
98
  key: opts.key,
42
99
  connectivityUrl: opts.connectivityUrl,
43
100
  probeId: opts.probeId,
44
101
  fetchImpl: opts.fetchImpl,
102
+ expected: opts.expected,
45
103
  timeoutMs: Math.min(8_000, remaining),
46
104
  });
105
+ last = checked;
47
106
  const elapsedMs = now() - start;
48
- if (seen)
49
- return { landed: true, elapsedMs, polls };
107
+ if (checked.seen)
108
+ return { ...checked, landed: true, elapsedMs, polls };
109
+ if (checked.state !== "ingestion_delay"
110
+ && checked.state !== "budget_exhausted"
111
+ && checked.state !== "dashboard_read_failure") {
112
+ return { ...checked, landed: false, elapsedMs, polls };
113
+ }
50
114
  if (elapsedMs + interval >= timeout)
51
- return { landed: false, elapsedMs, polls };
115
+ return { ...checked, landed: false, elapsedMs, polls };
52
116
  await sleep(interval);
53
117
  }
54
118
  }
@@ -1,32 +1,39 @@
1
1
  import type { FetchLike } from "./otlp.ts";
2
2
  import type { Endpoints } from "./config.ts";
3
+ import type { ExpectedKeyScope, KeyScope } from "./connectivity.ts";
3
4
  export type DeviceCodeResponse = {
4
5
  deviceCode: string;
5
6
  userCode: string;
6
7
  verificationUri: string;
7
8
  expiresIn: number;
8
9
  interval: number;
10
+ scopeFenced: boolean;
9
11
  };
10
- export declare function requestDeviceCode(endpoints: Endpoints, fetchImpl?: FetchLike, timeoutMs?: number): Promise<DeviceCodeResponse>;
12
+ export declare function requestDeviceCode(endpoints: Endpoints, fetchImpl?: FetchLike, timeoutMs?: number, expected?: ExpectedKeyScope): Promise<DeviceCodeResponse>;
11
13
  export type DeviceKey = {
12
14
  apiKey: string;
13
15
  ingestEndpoint: string;
16
+ scope?: KeyScope;
14
17
  };
15
18
  export type PollOnce = {
16
19
  status: "authorized";
17
20
  apiKey: string;
18
21
  ingestEndpoint: string;
22
+ scope?: KeyScope;
19
23
  } | {
20
24
  status: "pending";
21
25
  } | {
22
26
  status: "error";
23
27
  error: string;
24
28
  };
25
- export declare function pollOnce(endpoints: Endpoints, deviceCode: string, fetchImpl?: FetchLike, timeoutMs?: number): Promise<PollOnce>;
29
+ export declare function pollOnce(endpoints: Endpoints, deviceCode: string, fetchImpl?: FetchLike, timeoutMs?: number, opts?: {
30
+ scopeFenced?: boolean;
31
+ }): Promise<PollOnce>;
26
32
  export declare function pollForKey(endpoints: Endpoints, deviceCode: string, opts?: {
27
33
  intervalMs?: number;
28
34
  timeoutMs?: number;
29
35
  fetchImpl?: FetchLike;
30
36
  now?: () => number;
31
37
  sleepImpl?: (ms: number) => Promise<void>;
38
+ scopeFenced?: boolean;
32
39
  }): Promise<DeviceKey>;
@@ -1,14 +1,16 @@
1
1
  const TERMINAL_ERRORS = new Set(["expired_token", "invalid_grant", "access_denied"]);
2
- export async function requestDeviceCode(endpoints, fetchImpl = fetch, timeoutMs = 10_000) {
2
+ export async function requestDeviceCode(endpoints, fetchImpl = fetch, timeoutMs = 10_000, expected) {
3
+ const scopeFenced = !!expected && Object.keys(expected).length > 0;
4
+ const codeUrl = scopeFenced ? endpoints.deviceScopedCodeUrl : endpoints.deviceCodeUrl;
3
5
  const ac = new AbortController();
4
6
  const timer = setTimeout(() => ac.abort(), Math.max(1, timeoutMs));
5
7
  try {
6
8
  let res;
7
9
  try {
8
- res = await fetchImpl(endpoints.deviceCodeUrl, {
10
+ res = await fetchImpl(codeUrl, {
9
11
  method: "POST",
10
12
  headers: { "content-type": "application/json" },
11
- body: JSON.stringify({ client: "codetelemetry-connect" }),
13
+ body: JSON.stringify({ client: "codetelemetry-connect", ...(expected ? { expected } : {}) }),
12
14
  signal: ac.signal,
13
15
  });
14
16
  }
@@ -34,19 +36,32 @@ export async function requestDeviceCode(endpoints, fetchImpl = fetch, timeoutMs
34
36
  verificationUri: String(j.verification_uri ?? endpoints.verificationUri),
35
37
  expiresIn: Number(j.expires_in ?? 600),
36
38
  interval: Number(j.interval ?? 2),
39
+ scopeFenced,
37
40
  };
38
41
  }
39
42
  finally {
40
43
  clearTimeout(timer);
41
44
  }
42
45
  }
43
- async function tokenRequest(endpoints, deviceCode, fetchImpl, timeoutMs) {
46
+ function keyScope(value) {
47
+ if (!value || typeof value !== "object" || Array.isArray(value))
48
+ return undefined;
49
+ const raw = value;
50
+ if (typeof raw.tenantId !== "string" || !raw.tenantId || raw.tenantId.length > 256)
51
+ return undefined;
52
+ if (raw.teamId !== null && (typeof raw.teamId !== "string" || !raw.teamId || raw.teamId.length > 256))
53
+ return undefined;
54
+ if (typeof raw.billingAccountId !== "string" || !raw.billingAccountId || raw.billingAccountId.length > 256)
55
+ return undefined;
56
+ return { tenantId: raw.tenantId, teamId: raw.teamId, billingAccountId: raw.billingAccountId };
57
+ }
58
+ async function tokenRequest(endpoints, deviceCode, fetchImpl, timeoutMs, scopeFenced) {
44
59
  const ac = new AbortController();
45
60
  const timer = setTimeout(() => ac.abort(), Math.max(1, timeoutMs));
46
61
  try {
47
62
  let response;
48
63
  try {
49
- response = await fetchImpl(endpoints.deviceTokenUrl, {
64
+ response = await fetchImpl(scopeFenced ? endpoints.deviceScopedTokenUrl : endpoints.deviceTokenUrl, {
50
65
  method: "POST",
51
66
  headers: { "content-type": "application/json" },
52
67
  body: JSON.stringify({ device_code: deviceCode }),
@@ -65,13 +80,19 @@ async function tokenRequest(endpoints, deviceCode, fetchImpl, timeoutMs) {
65
80
  clearTimeout(timer);
66
81
  }
67
82
  }
68
- export async function pollOnce(endpoints, deviceCode, fetchImpl = fetch, timeoutMs = 8_000) {
69
- const result = await tokenRequest(endpoints, deviceCode, fetchImpl, timeoutMs);
83
+ export async function pollOnce(endpoints, deviceCode, fetchImpl = fetch, timeoutMs = 8_000, opts = {}) {
84
+ const result = await tokenRequest(endpoints, deviceCode, fetchImpl, timeoutMs, opts.scopeFenced === true);
70
85
  if (result === null)
71
86
  return { status: "pending" };
72
87
  const { response: res, body: j } = result;
73
88
  if (res.ok && j.api_key) {
74
- return { status: "authorized", apiKey: String(j.api_key), ingestEndpoint: String(j.ingest_endpoint) };
89
+ const scope = keyScope(j.scope);
90
+ return {
91
+ status: "authorized",
92
+ apiKey: String(j.api_key),
93
+ ingestEndpoint: String(j.ingest_endpoint),
94
+ ...(scope ? { scope } : {}),
95
+ };
75
96
  }
76
97
  const error = String(j.error ?? "authorization_pending");
77
98
  return TERMINAL_ERRORS.has(error) ? { status: "error", error } : { status: "pending" };
@@ -89,13 +110,18 @@ export async function pollForKey(endpoints, deviceCode, opts = {}) {
89
110
  if (remaining <= 0) {
90
111
  throw new Error("device authorization timed out — approval not completed in time");
91
112
  }
92
- const result = await tokenRequest(endpoints, deviceCode, fetchImpl, remaining);
113
+ const result = await tokenRequest(endpoints, deviceCode, fetchImpl, remaining, opts.scopeFenced === true);
93
114
  if (result === null) {
94
115
  throw new Error("device authorization timed out — approval not completed in time");
95
116
  }
96
117
  const { response: res, body: j } = result;
97
118
  if (res.ok && j.api_key) {
98
- return { apiKey: String(j.api_key), ingestEndpoint: String(j.ingest_endpoint) };
119
+ const scope = keyScope(j.scope);
120
+ return {
121
+ apiKey: String(j.api_key),
122
+ ingestEndpoint: String(j.ingest_endpoint),
123
+ ...(scope ? { scope } : {}),
124
+ };
99
125
  }
100
126
  const error = String(j.error ?? (res.status >= 500 ? "server_error" : "authorization_pending"));
101
127
  if (TERMINAL_ERRORS.has(error)) {
@@ -1,7 +1,7 @@
1
1
  import { type SettingsScope } from "./config.ts";
2
2
  import { type WriteResult } from "./settings.ts";
3
3
  import { type SendTestResult, type FetchLike } from "./otlp.ts";
4
- import { type ConfirmResult } from "./connectivity.ts";
4
+ import { type ConfirmResult, type ExpectedKeyScope, type KeyScope } from "./connectivity.ts";
5
5
  export type OnboardStep = {
6
6
  name: string;
7
7
  ok: boolean;
@@ -24,6 +24,7 @@ export type OnboardOptions = {
24
24
  getKey?: () => Promise<{
25
25
  apiKey: string;
26
26
  ingestEndpoint?: string;
27
+ scope?: KeyScope;
27
28
  }>;
28
29
  client?: OnboardClient;
29
30
  endpoints?: Partial<{
@@ -41,6 +42,7 @@ export type OnboardOptions = {
41
42
  verify?: boolean;
42
43
  verifyTimeoutMs?: number;
43
44
  verifyIntervalMs?: number;
45
+ expectedScope?: ExpectedKeyScope;
44
46
  fetchImpl?: FetchLike;
45
47
  logger?: (msg: string) => void;
46
48
  };