@codetelemetry/mcp 0.3.0 → 0.3.8

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.8", "codetelemetry-mcp"] }
27
35
  }
28
36
  }
29
37
  ```
@@ -34,34 +42,66 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
34
42
 
35
43
  | Tool | What it does |
36
44
  | --- | --- |
37
- | `authenticate` | Start device-code auth; returns a URL + short code for the human to approve. |
45
+ | `authenticate` | Start device-code auth; returns a URL + short code for the human to approve. Optional `organizationId` connects one of the user's organizations; optional `workspaceUrl` picks a CodeTelemetry server (codetelemetry.com hosts only). |
38
46
  | `auth_status` | Poll the approval; on success captures the key into the session (masked-only to the model). |
39
47
  | `get_ingest_key` | Record a pasted key (fast path) or report the authenticated one — masked + hash only. |
40
- | `write_local_config` | Merge the OTEL config + key into a recognized Claude Code or Codex config path (preserves + backs up). |
48
+ | `write_local_config` | Merge the OTEL config + key into Claude Code's or Codex's config (the default, or an explicit `path` to a `settings.json`/`settings.local.json` in a `.claude` directory or a `config.toml` in a `.codex` directory); preserves + backs up. |
41
49
  | `send_test_event` | Fire one OTLP probe log with a unique id. |
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. |
62
+ | `estimate_plan` | T-shirt size a Claude Code / Codex **plan** (plain text or ordered steps) from the caller's own history. |
50
63
  | `estimate_linear_issue` | T-shirt size an **existing Linear issue** by URL or identifier, resolved through the workspace the user already connected. |
51
64
 
52
65
  Typical agent flow: `authenticate` → (human approves) → `auth_status` →
53
66
  `onboard`. Or, if the user pastes a key: `onboard { key }`.
54
67
 
68
+ ## Organizations
69
+
70
+ Without an `organizationId`, the key goes wherever the user picks while approving:
71
+ their personal workspace or one of their organizations. To connect an
72
+ organization on purpose, pass its id, shown in parentheses next to each
73
+ organization on the approval page:
74
+
75
+ ```jsonc
76
+ // tool: authenticate
77
+ { "organizationId": "<organization id>" }
78
+ ```
79
+
80
+ The approval link then pre-selects that organization, the sign-in runs on the
81
+ scope-fenced route, and `auth_status` keeps the key only when CodeTelemetry
82
+ attests that it belongs to that organization. Otherwise it answers `wrong_scope`
83
+ (or `scope_unverified` when the organization could not be confirmed) and discards
84
+ the key. `onboard` and `verify_telemetry` repeat the check against
85
+ the connectivity endpoint. `workspaceUrl` is unrelated: it picks the CodeTelemetry
86
+ server, not an organization.
87
+
55
88
  ## Data and local changes
56
89
 
57
90
  The default setup writes only the OpenTelemetry exporter endpoint and ingest
58
- credential to the selected client's recognized config file. The MCP tool cannot
59
- choose an arbitrary URL or filesystem path: authentication uses
60
- `https://codetelemetry.com` and telemetry uses CodeTelemetry's production ingest
61
- endpoint, while configuration is limited to Claude Code's user/current-project
62
- `settings.json` or Codex's active `config.toml`. Existing config is preserved,
63
- backed up before a change, and the resulting file is made owner-readable only
64
- where the platform supports it.
91
+ credential to the selected client's config file: Claude Code's user or
92
+ current-project `settings.json`, or Codex's active `config.toml`. An explicit
93
+ `path` may name another config file of the same client, and nothing else: a
94
+ `settings.json` or `settings.local.json` inside a `.claude` directory (or
95
+ `$CLAUDE_CONFIG_DIR`), or a `config.toml` inside a `.codex` directory (or
96
+ `$CODEX_HOME`). A leading `~` is the home directory; links, network paths and
97
+ anything but a regular file are refused, and a path the host pins outranks the
98
+ model's. Authentication uses `https://codetelemetry.com` unless `authenticate` is
99
+ given a `workspaceUrl`, which must be an https URL on codetelemetry.com or one of
100
+ its subdomains and cannot override a server the MCP configuration pins. Moving to
101
+ another server drops any key from the old one, and telemetry goes to the ingest
102
+ endpoint the new server issues with its key. Existing config is preserved, backed
103
+ up before a change, and the resulting file is made owner-readable only where the
104
+ platform supports it.
65
105
 
66
106
  Two higher-sensitivity features are off by default and require separate boolean
67
107
  opt-ins:
@@ -81,6 +121,54 @@ on prompt/body telemetry, and `enrich` does not install repository hooks. A late
81
121
  run with `repositoryObservation` omitted or false removes only CodeTelemetry's
82
122
  managed hook entries and helper/state files; unrelated user hooks are preserved.
83
123
 
124
+ ## Estimating a plan
125
+
126
+ `estimate_plan` predicts the **coding-assistant token effort** of a plan from the
127
+ user's own similar past sessions — not elapsed time or human engineering hours.
128
+ The client must submit the plan content **explicitly** (the server never reads the
129
+ agent's hidden state), and the whole plan is sized as **one** unit: submitted step
130
+ boundaries are preserved in `source` for provenance but are never summed as
131
+ independent estimates. It is read-only — it never edits the plan, creates issues,
132
+ or starts work. Weak or contradictory history yields a **low-confidence** result
133
+ carrying a small calibration task rather than a falsely precise number.
134
+
135
+ **Claude Code** — after Claude drafts a plan, ask it to size that plan. Claude
136
+ passes its own plan text/steps explicitly:
137
+
138
+ ```jsonc
139
+ // tool: estimate_plan
140
+ {
141
+ "title": "Add a rate limiter to the ingest API",
142
+ "steps": [
143
+ { "title": "Token bucket", "detail": "per-tenant bucket in the ingest middleware" },
144
+ { "title": "Config", "detail": "expose the limit + window as env vars" },
145
+ "Add unit and integration tests for the limiter"
146
+ ],
147
+ "repo": "elo",
148
+ "provider": "claude",
149
+ "model": "claude-opus-4-8"
150
+ }
151
+ ```
152
+
153
+ **Codex** — the same tool from a Codex session. Pass the plan as plain text (or
154
+ steps) and set `provider: "codex"`:
155
+
156
+ ```jsonc
157
+ // tool: estimate_plan
158
+ {
159
+ "title": "Backfill Linear estimates",
160
+ "planText": "1. Read settled sessions for the window\n2. Size each by actual token usage\n3. Write the estimate + provenance back to Linear behind a confirm gate",
161
+ "repo": "elo",
162
+ "provider": "codex"
163
+ }
164
+ ```
165
+
166
+ The result carries the shared sizing schema (`estimate`: size, predicted token
167
+ range, confidence with reasons, comparable-work evidence, optional calibration
168
+ task), plus normalized `source` metadata (title, format, preserved step
169
+ boundaries, repo/project/provider/model) and a `note` restating that the number is
170
+ token effort, not time.
171
+
84
172
  ## Estimating a Linear issue
85
173
 
86
174
  `estimate_linear_issue` sizes an issue that **already exists** in Linear, so you
@@ -200,7 +288,7 @@ npm run smoke -- --tarball out.tgz --require-auth # exactly these by
200
288
  and read `server`:
201
289
 
202
290
  ```jsonc
203
- "server": { "name": "codetelemetry", "version": "0.3.0", "registryHash": "f2b6568d…", "toolCount": 15 }
291
+ "server": { "name": "codetelemetry", "version": "0.3.8", "registryHash": "36d8f5e3…", "toolCount": 19 }
204
292
  ```
205
293
 
206
294
  **When a long-running client sees a new tool.** `tools/list` is requested once, at
@@ -240,3 +328,7 @@ npm run test:protocol # drives the tools through a real MCP client/server pair
240
328
  npm run test:packaged # packs, launches the artifact, runs the release smoke
241
329
  npm run typecheck
242
330
  ```
331
+
332
+ `npm test`, `test:protocol` and `test:e2e` load `test/support/isolateHome.ts`, which
333
+ points `HOME`, `USERPROFILE` and `CODEX_HOME` at a throwaway directory, so a test can
334
+ never rewrite your own `~/.claude/settings.json` or Codex config.
@@ -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>;