@codetelemetry/mcp 0.3.9 → 0.3.14

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.
Files changed (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +135 -9
  3. package/dist/src/client/agent.d.ts +201 -3
  4. package/dist/src/client/agent.js +154 -0
  5. package/dist/src/client/assistants.d.ts +4 -0
  6. package/dist/src/client/assistants.js +5 -0
  7. package/dist/src/client/bin.d.ts +2 -0
  8. package/dist/src/client/bin.js +3 -0
  9. package/dist/src/client/cli.d.ts +1 -0
  10. package/dist/src/client/cli.js +567 -0
  11. package/dist/src/client/clients.d.ts +34 -0
  12. package/dist/src/client/clients.js +74 -0
  13. package/dist/src/client/codexConfig.d.ts +1 -0
  14. package/dist/src/client/codexConfig.js +5 -0
  15. package/dist/src/client/config.d.ts +6 -0
  16. package/dist/src/client/config.js +6 -0
  17. package/dist/src/client/graderArtifact.d.ts +14 -0
  18. package/dist/src/client/graderArtifact.js +94 -0
  19. package/dist/src/client/graderSeed.d.ts +50 -0
  20. package/dist/src/client/graderSeed.js +289 -0
  21. package/dist/src/client/hostMetrics.d.ts +54 -0
  22. package/dist/src/client/hostMetrics.js +425 -0
  23. package/dist/src/client/import/browser.d.ts +30 -0
  24. package/dist/src/client/import/browser.js +157 -0
  25. package/dist/src/client/import/convert.d.ts +20 -0
  26. package/dist/src/client/import/convert.js +165 -0
  27. package/dist/src/client/import/core.d.ts +143 -0
  28. package/dist/src/client/import/core.js +441 -0
  29. package/dist/src/client/import/ledger.d.ts +52 -0
  30. package/dist/src/client/import/ledger.js +161 -0
  31. package/dist/src/client/import/model.d.ts +70 -0
  32. package/dist/src/client/import/model.js +42 -0
  33. package/dist/src/client/import/options.d.ts +24 -0
  34. package/dist/src/client/import/options.js +71 -0
  35. package/dist/src/client/import/otlpImport.d.ts +7 -0
  36. package/dist/src/client/import/otlpImport.js +81 -0
  37. package/dist/src/client/import/protocol.d.ts +35 -0
  38. package/dist/src/client/import/protocol.js +51 -0
  39. package/dist/src/client/import/run.d.ts +30 -0
  40. package/dist/src/client/import/run.js +127 -0
  41. package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
  42. package/dist/src/client/import/sources/claudeCodeText.js +214 -0
  43. package/dist/src/client/import/sources/codexText.d.ts +20 -0
  44. package/dist/src/client/import/sources/codexText.js +319 -0
  45. package/dist/src/client/import/sources/files.d.ts +24 -0
  46. package/dist/src/client/import/sources/files.js +129 -0
  47. package/dist/src/client/import/transport.d.ts +76 -0
  48. package/dist/src/client/import/transport.js +141 -0
  49. package/dist/src/client/index.d.ts +19 -0
  50. package/dist/src/client/index.js +19 -0
  51. package/dist/src/client/kiro/collector.d.ts +88 -0
  52. package/dist/src/client/kiro/collector.js +577 -0
  53. package/dist/src/client/kiro/command.d.ts +3 -0
  54. package/dist/src/client/kiro/command.js +109 -0
  55. package/dist/src/client/kiro/config.d.ts +39 -0
  56. package/dist/src/client/kiro/config.js +107 -0
  57. package/dist/src/client/kiro/records.d.ts +52 -0
  58. package/dist/src/client/kiro/records.js +206 -0
  59. package/dist/src/client/kiro/service.d.ts +21 -0
  60. package/dist/src/client/kiro/service.js +183 -0
  61. package/dist/src/client/kiro/state.d.ts +45 -0
  62. package/dist/src/client/kiro/state.js +205 -0
  63. package/dist/src/client/kiro/transport.d.ts +9 -0
  64. package/dist/src/client/kiro/transport.js +90 -0
  65. package/dist/src/client/onboard.d.ts +5 -1
  66. package/dist/src/client/onboard.js +28 -23
  67. package/dist/src/client/piConfig.d.ts +29 -0
  68. package/dist/src/client/piConfig.js +112 -0
  69. package/dist/src/client/plan.d.ts +1 -1
  70. package/dist/src/client/plan.js +2 -1
  71. package/dist/src/client/settings.d.ts +4 -0
  72. package/dist/src/client/settings.js +17 -0
  73. package/dist/src/client/yaml.d.ts +5 -0
  74. package/dist/src/client/yaml.js +72 -0
  75. package/dist/src/mcpServer.js +1 -1
  76. package/dist/src/tools.d.ts +9 -6
  77. package/dist/src/tools.js +428 -60
  78. package/dist/src/version.d.ts +1 -1
  79. package/dist/src/version.js +1 -1
  80. package/package.json +178 -9
  81. package/tool-manifest.json +708 -21
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Elliot Gardiner
3
+ Copyright (c) 2026 CodeTelemetry
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -31,7 +31,7 @@ deterministic (see [Releases & discovery](#releases--discovery)):
31
31
  ```json
32
32
  {
33
33
  "mcpServers": {
34
- "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.3.9", "codetelemetry-mcp"] }
34
+ "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.3.14", "codetelemetry-mcp"] }
35
35
  }
36
36
  }
37
37
  ```
@@ -42,6 +42,8 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
42
42
 
43
43
  | Tool | What it does |
44
44
  | --- | --- |
45
+ | `count_reply_phrases` | Count how often your own phrases appear in your Claude model replies, per day or week and per model (turns, turns with a match, per-phrase counts). Plain-text phrases with `{a|b}` / `[a|b]` groups, whole-word and case-insensitive; main-thread replies only; counts and session references, never reply text. |
46
+ | `import_history` | Import this machine's past Claude Code / Codex sessions (`~/.claude/projects`, `~/.codex/sessions`) through the normal ingest, tagged as imported. Dry run by default; skips sessions captured live or already imported; resumes interrupted imports; pages with `remaining`. Content defaults to `live` (what your live exporters send); `none` opts out. |
45
47
  | `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). |
46
48
  | `auth_status` | Poll the approval; on success captures the key into the session (masked-only to the model). |
47
49
  | `get_ingest_key` | Record a pasted key (fast path) or report the authenticated one — masked + hash only. |
@@ -61,6 +63,11 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
61
63
  | `estimate_task_size` | T-shirt size a proposed task (free-form text or a Linear-shaped issue) from the caller's own history. |
62
64
  | `estimate_plan` | T-shirt size a Claude Code / Codex **plan** (plain text or ordered steps) from the caller's own history. |
63
65
  | `estimate_linear_issue` | T-shirt size an **existing Linear issue** by URL or identifier, resolved through the workspace the user already connected. |
66
+ | `seed_grader_config` | Inspect local agent instructions, selected skills, and project task files; return source text and command-check candidates for the user's requested grading focus. Reads files without running commands or uploading them. |
67
+ | `publish_grader_config` | Publish the reviewed draft as a new policy version using its exact revision. Completes setup through MCP; historical scores remain unchanged. |
68
+ | `write_grader_config_artifact` | Write selected checks as Terraform JSON or a standalone Pulumi YAML program, choosing the format from repository context. Refuses overwrites; runs no commands. |
69
+ | `get_grader_config` | Read a page of the workspace's Grader draft, its revision, and published version. |
70
+ | `update_grader_config` | Add, update, or remove selected draft checks while preserving others. Records the user's requested instruction features and rejects stale revisions. Use publish_grader_config with the returned revision to apply it to future scoring. |
64
71
  | `get_github_pr_gate` | Read the workspace's GitHub PR gate as its settings page shows it: the policy, trusted repositories, the GitHub Actions workflow file to commit, the check to require, outstanding steps, and recent decisions. |
65
72
  | `configure_github_pr_gate` | Set up or change the GitHub PR gate: trust repositories (`owner/repo` or `owner/*`), set the policy, enable it. Once the gate is on, a change that loosens it is refused (`requires_dashboard`) and the user makes it on the settings page. No GitHub token is involved: the workflow authenticates with GitHub's own OIDC token. |
66
73
 
@@ -74,6 +81,99 @@ the user merges) → once it has run, the user requires
74
81
  `codetelemetry/validation` from GitHub Actions on the default branch (`howTo`
75
82
  gives the `gh api` ruleset command to run with their permission).
76
83
 
84
+ ## Seed and update the Grader
85
+
86
+ Ask, for example: **"Use AGENTS.md and our security-review skill to grade unit
87
+ tests, lint, and security-review skill invocation. Ignore the writing style rules."**
88
+
89
+ The agent calls `seed_grader_config` with the repository directory and your
90
+ `features` description. Discovery includes nested packages and repository skills
91
+ under `.agents/skills`, `.claude/skills`, and `.codex/skills`. Additional user
92
+ skills can be selected explicitly through `skillPaths`; your home directory is
93
+ never scanned automatically.
94
+
95
+ Command candidates come from npm/pnpm/yarn/bun scripts, Composer scripts,
96
+ Make/Just/Rake targets, pytest/Ruff/mypy configuration, tox/nox, Go, Cargo,
97
+ Maven/Gradle, .NET project files, Swift, Mix, and CMake test configuration.
98
+ Declared tasks and inferred conventions are labelled separately. Discovery is
99
+ bounded, skips dependency/generated/hidden directories, does not follow links,
100
+ and reports truncation or unreadable sources. Narrow the repository directory
101
+ when a large monorepo hits the limits. No task is executed.
102
+
103
+ The calling agent uses your description to select relevant checks and translate
104
+ instruction features into observable command or tool-use matchers. It should
105
+ explain prose requirements the deterministic Grader cannot establish. Invoking a
106
+ skill can be checked; compliance with all its written guidance cannot be inferred
107
+ from invocation alone. Review inferred commands and adapt local working-directory
108
+ matchers if your sessions run at another path. Pass `repositoryId` from session
109
+ metadata to scope checks to the recorded repository.
110
+
111
+ The agent then reads `get_grader_config` (follow `nextOffset` for remaining checks)
112
+ and sends selected `upsertChecks` and/or `removeCheckIds` to
113
+ `update_grader_config`, with `features` and the read's `revision` as
114
+ `expectedRevision`. Existing checks are preserved unless named. A concurrent
115
+ edit returns `conflict`; read again before retrying. An uncertain save must also
116
+ be read back before retrying. Only selected check definitions and your feature
117
+ description go to the server; source file text stays local to the MCP response.
118
+
119
+ Changes are initially saved as a draft. To activate them, call
120
+ `publish_grader_config` with the exact `expectedRevision` returned by
121
+ `update_grader_config` or a fresh `get_grader_config`. The complete workflow —
122
+ seed, select checks, save, review, publish — works through MCP without the UI.
123
+ Publish only when the user wants activation; saving a draft stays separate.
124
+ Publication creates a new policy version for future evaluations and leaves
125
+ historical scores unchanged. Concurrent edits or a repeated publish using the
126
+ same revision return `conflict`. After `publish_uncertain`, read
127
+ `get_grader_config` and compare `publishedVersion` and `revision` before retrying.
128
+ The [Grader page](https://codetelemetry.com/app/validation) remains an alternative. Remote configuration requires a backend implementing
129
+ `POST /api/agent/grader`, `POST /api/agent/grader/configure`, and
130
+ `POST /api/agent/grader/publish`; older deployments
131
+ return `not_supported` or `not_configured`. Local seeding works without a key.
132
+
133
+
134
+ Leave selected checks in the repository with `write_grader_config_artifact`:
135
+
136
+ ```json
137
+ {
138
+ "repositoryPath": "/path/to/project",
139
+ "features": "Require successful unit tests and lint from AGENTS.md",
140
+ "checks": ["<selected complete check objects from the seed or draft>"]
141
+ }
142
+ ```
143
+
144
+ The example's `checks` placeholder must be replaced with actual check objects.
145
+ Auto detection scans at most 4,000 entries, five directories deep, skipping links,
146
+ dependencies and state directories. `.tf` / `.tf.json` selects Terraform;
147
+ `Pulumi.yaml` / `Pulumi.yml` selects Pulumi. Mixed, missing or incomplete context
148
+ requires `format: "terraform"` or `format: "pulumi"`, or a narrower directory.
149
+
150
+ Terraform writes `codetelemetry-grader.tf.json`, for use with the local
151
+ `codetelemetry_grader_config` provider resource. Configure the provider using
152
+ [codetelemetry-providers](https://github.com/ElliotGardiner/codetelemetry-providers)
153
+ before planning; it is not a published registry integration.
154
+ Pulumi writes `codetelemetry-grader.pulumi.yaml` as JSON, a valid YAML subset.
155
+ Move it to a **separate directory** as `Pulumi.yaml`, build the provider binary
156
+ there at `./bin/terraform-provider-codetelemetry`, then run `pulumi install` and
157
+ `pulumi preview`. This standalone YAML program works alongside repositories using
158
+ any Pulumi language; it does not rewrite an existing Pulumi program.
159
+
160
+ Both resources own their listed check IDs, preserve unrelated checks, and use
161
+ revision checks on writes. An identical draft saved by the MCP can be adopted
162
+ without a write. Conflicting existing IDs require explicit import and review.
163
+ Destroy removes only managed draft checks. Use one state owner per workspace;
164
+ review plans and protect production resources as needed.
165
+
166
+ The requested focus is retained in Terraform locals or the Pulumi program
167
+ description. The IaC dashboard API preserves the draft's existing
168
+ `requestedFeatures`; use `update_grader_config` to change that remote intent.
169
+ Artifacts contain selected check definitions, not raw instructions or skills.
170
+ Template-like source strings remain literal. Files are created with restrictive
171
+ permissions and never overwrite an existing file, including symlinks. Edit an
172
+ existing artifact with normal file tools. The artifact tool does not execute IaC or publish a
173
+ policy; use `publish_grader_config` for activation. Apply with `CODETELEMETRY_ENDPOINT` and a **Cognito ID token** in
174
+ `CODETELEMETRY_TOKEN`, supplied through your secret manager; the MCP's ingest key
175
+ is not the IaC credential. Keep secrets out of check definitions and protect state.
176
+
77
177
  ## Organizations
78
178
 
79
179
  Without an `organizationId`, the key goes wherever the user picks while approving:
@@ -153,7 +253,7 @@ passes its own plan text/steps explicitly:
153
253
  { "title": "Config", "detail": "expose the limit + window as env vars" },
154
254
  "Add unit and integration tests for the limiter"
155
255
  ],
156
- "repo": "elo",
256
+ "repo": "acme-api",
157
257
  "provider": "claude",
158
258
  "model": "claude-opus-4-8"
159
259
  }
@@ -167,7 +267,7 @@ steps) and set `provider: "codex"`:
167
267
  {
168
268
  "title": "Backfill Linear estimates",
169
269
  "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",
170
- "repo": "elo",
270
+ "repo": "acme-api",
171
271
  "provider": "codex"
172
272
  }
173
273
  ```
@@ -194,7 +294,7 @@ names its own workspace, so nothing else is needed:
194
294
  // tool: estimate_linear_issue
195
295
  {
196
296
  "reference": "https://linear.app/acme/issue/ELL-44/add-an-mcp-tool-to-estimate-linear-issues",
197
- "repo": "elo"
297
+ "repo": "acme-api"
198
298
  }
199
299
  ```
200
300
 
@@ -207,7 +307,7 @@ workspace is connected, name the one to use:
207
307
  {
208
308
  "reference": "ELL-44",
209
309
  "workspace": "acme",
210
- "repo": "elo"
310
+ "repo": "acme-api"
211
311
  }
212
312
  ```
213
313
 
@@ -264,8 +364,8 @@ not help), and `sizing_failed` for anything unmapped.
264
364
  The plaintext `cot_…` key lives only inside the server process's session
265
365
  (`#private` field). Every tool result carries a **masked** preview (`cot_…b3F9`)
266
366
  and the key hash — never the plaintext. `callTool` additionally scrubs the
267
- serialized result as a backstop. This invariant is asserted in
268
- [`test/tools.test.ts`](test/tools.test.ts) across a full onboarding transcript.
367
+ serialized result as a backstop. This invariant is asserted throughout
368
+ [`test/tools.test.ts`](test/tools.test.ts).
269
369
 
270
370
  The public MCP schemas deliberately expose neither endpoint overrides nor
271
371
  arbitrary config paths. Test harnesses and trusted embedders can inject those
@@ -297,7 +397,7 @@ npm run smoke -- --tarball out.tgz --require-auth # exactly these by
297
397
  and read `server`:
298
398
 
299
399
  ```jsonc
300
- "server": { "name": "codetelemetry", "version": "0.3.9", "registryHash": "cb420922…", "toolCount": 21 }
400
+ "server": { "name": "codetelemetry", "version": "0.3.11", "registryHash": "cb420922…", "toolCount": 23 }
301
401
  ```
302
402
 
303
403
  **When a long-running client sees a new tool.** `tools/list` is requested once, at
@@ -338,6 +438,32 @@ npm run test:packaged # packs, launches the artifact, runs the release smoke
338
438
  npm run typecheck
339
439
  ```
340
440
 
341
- `npm test`, `test:protocol` and `test:e2e` load `test/support/isolateHome.ts`, which
441
+ `npm test` and `test:protocol` load `test/support/isolateHome.ts`, which
342
442
  points `HOME`, `USERPROFILE` and `CODEX_HOME` at a throwaway directory, so a test can
343
443
  never rewrite your own `~/.claude/settings.json` or Codex config.
444
+
445
+ ## Client implementation ownership
446
+
447
+ This public repository owns the local client implementation. `src/client` contains
448
+ configuration, privacy controls, HTTP adapters, history upload, and the bounded
449
+ Kiro collector. The MCP server and Connect CLI share that implementation. Server
450
+ authorization, analytics, dispatch policy and production operations are maintained
451
+ separately and are not included in either package.
452
+
453
+ Run the Connect CLI with `npx -p @codetelemetry/mcp codetelemetry-connect --help`.
454
+ Kiro uses `codetelemetry-connect login --client kiro` and requires Node 24.
455
+ `kiro status`, `kiro disable`, and `kiro uninstall` inspect or stop its owned service.
456
+ Kiro reads local V3 transcripts with prompt/tool content disabled by default;
457
+ `--enrich` explicitly opts into those fields. Linux/macOS support an owned user
458
+ service; Windows uses foreground `kiro collect`. Configuration lives separately
459
+ from Kiro itself. Checkpoints and owned runtime files survive service removal.
460
+
461
+ The Kiro collector sends bounded, sanitized source records. Event interpretation,
462
+ call/result association, usage aggregation and analytics run in the service.
463
+ The service must support `kiro-v3-source-v1` before this collector is released;
464
+ unsupported responses leave the pending upload and source offsets intact.
465
+ Checkpoint versions 1 and 2 upgrade to version 3; older collector binaries refuse
466
+ version 3. Existing canonical pending uploads retain their exact retry bytes.
467
+
468
+ Collector health version 2 reports local capture and delivery counters. It omits
469
+ call-association counts that are now computed by the service.
@@ -39,6 +39,7 @@ export type AgentReadPerformance = {
39
39
  };
40
40
  export type SessionPerformanceReport = {
41
41
  sessionId: string;
42
+ service?: string;
42
43
  present: boolean;
43
44
  sessionCount: number;
44
45
  eventCount: number;
@@ -90,6 +91,14 @@ export type SessionSearchHit = {
90
91
  title: string;
91
92
  titleIsId: boolean;
92
93
  sessionName?: string;
94
+ delegation?: {
95
+ parentSessionId: string;
96
+ parentSessionUrl?: string;
97
+ at: string;
98
+ source: "codex.agent_communication";
99
+ taskName?: string;
100
+ taskNameSource?: "parent_spawn_agent";
101
+ };
93
102
  repo: string;
94
103
  repoInferred?: boolean;
95
104
  user?: string;
@@ -97,17 +106,66 @@ export type SessionSearchHit = {
97
106
  models: string[];
98
107
  lastSeen: string | null;
99
108
  durationMs: number;
100
- totalTokens: number;
101
- costUsd: number;
109
+ totalTokens?: number;
110
+ costUsd?: number;
102
111
  prompts: number;
103
- invocations: number;
112
+ invocations?: number;
104
113
  tools: number;
114
+ linesAdded?: number;
115
+ linesRemoved?: number;
116
+ commits?: number;
117
+ pullRequests?: number;
118
+ costPerCommit?: number;
119
+ zeroOutput?: true;
120
+ outcomeSource?: "claude_code_metrics" | "tool_event_parse";
105
121
  activity?: "substantive" | "instrumentation_only" | "insufficient_evidence";
106
122
  match?: {
107
123
  fields: string[];
108
124
  };
125
+ measurements?: {
126
+ version: 1;
127
+ tokens: "measured" | "unmeasured" | "unavailable" | "conflict";
128
+ usd: "measured" | "unmeasured" | "unavailable" | "conflict";
129
+ modelCalls: "measured" | "unmeasured" | "unavailable" | "conflict";
130
+ apiLatency: "measured" | "unmeasured" | "unavailable" | "conflict";
131
+ toolDuration: "measured" | "unmeasured" | "unavailable" | "conflict";
132
+ providerCredits: "measured" | "unmeasured" | "unavailable" | "conflict";
133
+ reportedTurnElapsed: "measured" | "unmeasured" | "unavailable" | "conflict";
134
+ turnCompletion?: "measured" | "unmeasured" | "unavailable" | "conflict";
135
+ };
136
+ providerUsageWindow?: {
137
+ from: string;
138
+ through: string;
139
+ basis: "retained_provider_turns";
140
+ };
141
+ turnCompletion?: {
142
+ turns: number;
143
+ completed: number;
144
+ cancelled: number;
145
+ errors: number;
146
+ unknown: number;
147
+ successfulCompleted: number;
148
+ reportedStatusTurns: number;
149
+ };
150
+ providerTurnCoverage?: {
151
+ turnsWithoutUsage: number;
152
+ turnsWithoutCompletion: number;
153
+ };
154
+ providerUsage?: {
155
+ provider: "kiro";
156
+ unit: "credit";
157
+ amount: number;
158
+ turns: number;
159
+ reportedTurnElapsedMs?: number;
160
+ reportedTurnCount: number;
161
+ };
109
162
  };
110
163
  export type SessionSearchLegacyReport = {
164
+ telemetrySnapshot?: {
165
+ materializedAt: string;
166
+ dataThrough: string | null;
167
+ eventContent: "separate_snapshot";
168
+ };
111
169
  results: SessionSearchHit[];
112
170
  total: number;
113
171
  limit: number;
@@ -345,16 +403,121 @@ export type SimilarSessionErrorsResult = {
345
403
  error: string | null;
346
404
  message: string | null;
347
405
  };
406
+ export type HostState = "healthy" | "degraded" | "stale" | "offline";
407
+ export type HostThresholds = {
408
+ cpuSoft: number;
409
+ cpuHard: number;
410
+ memSoft: number;
411
+ memHard: number;
412
+ swapHard: number;
413
+ fsSoft: number;
414
+ fsHard: number;
415
+ staleAfterSec: number;
416
+ offlineAfterSec: number;
417
+ };
418
+ export type HostAgentdProcess = {
419
+ detected: boolean;
420
+ cpuUtil: number | null;
421
+ memUtil: number | null;
422
+ threads: number | null;
423
+ };
424
+ export type HostSignals = {
425
+ cpuUtil: number | null;
426
+ memUtil: number | null;
427
+ swapUtil: number | null;
428
+ fsUtil: number | null;
429
+ load1: number | null;
430
+ load5: number | null;
431
+ load15: number | null;
432
+ uptimeSec: number | null;
433
+ networkErrors: number | null;
434
+ agentd: HostAgentdProcess;
435
+ codingAgentsPresent: string[];
436
+ };
437
+ export type HostHeadroom = {
438
+ cpu: number | null;
439
+ memory: number | null;
440
+ swap: number | null;
441
+ filesystem: number | null;
442
+ limitingFactor: string | null;
443
+ };
444
+ export type HostAdmission = {
445
+ admit: boolean;
446
+ reason: string;
447
+ limitingFactor: string | null;
448
+ };
449
+ export type HostHealth = {
450
+ instance: string;
451
+ host: string | null;
452
+ os: string | null;
453
+ arch: string | null;
454
+ environment: string | null;
455
+ state: HostState;
456
+ synthetic?: boolean;
457
+ reasons: string[];
458
+ warnings: string[];
459
+ lastSeen: string | null;
460
+ ageSeconds: number | null;
461
+ signals: HostSignals;
462
+ signalObservedAt?: Record<string, {
463
+ at: string;
464
+ ageSeconds: number;
465
+ }>;
466
+ headroom: HostHeadroom;
467
+ admission: HostAdmission;
468
+ };
469
+ export type HostHealthReport = {
470
+ generatedAt: string;
471
+ asOf: string | null;
472
+ policyVersion: string;
473
+ lookbackMinutes: number;
474
+ windowMinutes: number;
475
+ signalMaxAgeSec: number;
476
+ thresholds: HostThresholds;
477
+ signalUnits?: Record<string, string>;
478
+ hosts: HostHealth[];
479
+ summary: {
480
+ total: number;
481
+ healthy: number;
482
+ degraded: number;
483
+ stale: number;
484
+ offline: number;
485
+ admittable: number;
486
+ synthetic?: number;
487
+ };
488
+ };
489
+ export type HostPipelineDiagnosis = {
490
+ stage: string;
491
+ detail: string;
492
+ hostFeedLastSeen: string | null;
493
+ hostFeedLastSeenAgeSec: number | null;
494
+ otherFeedsLastSeen: string | null;
495
+ otherFeedsLastSeenAgeSec: number | null;
496
+ horizonDays: number | null;
497
+ };
498
+ export type HostHealthResult = {
499
+ ok: boolean;
500
+ report: HostHealthReport | null;
501
+ status: string | null;
502
+ diagnosis: HostPipelineDiagnosis | null;
503
+ serverVersion: string | null;
504
+ reportUnusable: string | null;
505
+ httpStatus: number;
506
+ error: string | null;
507
+ message: string | null;
508
+ };
348
509
  export declare function getCostSignal(opts: {
349
510
  key: string;
350
511
  url: string;
351
512
  fetchImpl?: FetchLike;
352
513
  timeoutMs?: number;
353
514
  }): Promise<CostSignalResult>;
515
+ export declare function normalizeSessionPerformanceService(value: unknown): string | undefined | null;
354
516
  export declare function getSessionPerformance(opts: {
355
517
  key: string;
356
518
  url: string;
357
519
  sessionId: string;
520
+ service?: string;
358
521
  includeFresh?: boolean;
359
522
  cacheSamples?: number;
360
523
  fetchImpl?: FetchLike;
@@ -383,6 +546,20 @@ export declare function searchCodingSessions(opts: SessionSearchOptions<Record<s
383
546
  export declare function searchCodingSessions(opts: SessionSearchOptions<Record<string, unknown> & {
384
547
  precedent?: false;
385
548
  }>): Promise<SessionSearchResult>;
549
+ export type ReplyPhraseTrendsResult = {
550
+ ok: boolean;
551
+ trends: Record<string, unknown> | null;
552
+ httpStatus: number;
553
+ error: string | null;
554
+ message: string | null;
555
+ };
556
+ export declare function countReplyPhrases(opts: {
557
+ key: string;
558
+ url: string;
559
+ query: Record<string, unknown>;
560
+ fetchImpl?: FetchLike;
561
+ timeoutMs?: number;
562
+ }): Promise<ReplyPhraseTrendsResult>;
386
563
  export declare function estimateTaskSize(opts: {
387
564
  key: string;
388
565
  url: string;
@@ -402,6 +579,15 @@ export declare function estimateTaskSize(opts: {
402
579
  fetchImpl?: FetchLike;
403
580
  timeoutMs?: number;
404
581
  }): Promise<TaskEffortResult>;
582
+ export declare function getHostHealth(opts: {
583
+ key: string;
584
+ url: string;
585
+ lookbackMinutes?: number;
586
+ thresholds?: Partial<HostThresholds>;
587
+ diagnose?: boolean;
588
+ fetchImpl?: FetchLike;
589
+ timeoutMs?: number;
590
+ }): Promise<HostHealthResult>;
405
591
  export declare function estimateLinearIssue(opts: {
406
592
  key: string;
407
593
  url: string;
@@ -498,4 +684,16 @@ export declare function planNextSession(opts: {
498
684
  error: string | null;
499
685
  message: string | null;
500
686
  }>;
687
+ export declare function graderConfigRequest(opts: {
688
+ key: string;
689
+ url: string;
690
+ body: Record<string, unknown>;
691
+ fetchImpl?: FetchLike;
692
+ }): Promise<{
693
+ ok: boolean;
694
+ config: any;
695
+ httpStatus: number;
696
+ error: any;
697
+ message: any;
698
+ }>;
501
699
  export {};
@@ -1,4 +1,22 @@
1
1
  import { assertKey } from "./keys.js";
2
+ function parseDiagnosis(raw) {
3
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
4
+ return null;
5
+ const d = raw;
6
+ if (typeof d.stage !== "string" || !d.stage)
7
+ return null;
8
+ const str = (v) => (typeof v === "string" && v ? v : null);
9
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
10
+ return {
11
+ stage: d.stage,
12
+ detail: str(d.detail) ?? "",
13
+ hostFeedLastSeen: str(d.hostFeedLastSeen),
14
+ hostFeedLastSeenAgeSec: num(d.hostFeedLastSeenAgeSec),
15
+ otherFeedsLastSeen: str(d.otherFeedsLastSeen),
16
+ otherFeedsLastSeenAgeSec: num(d.otherFeedsLastSeenAgeSec),
17
+ horizonDays: num(d.horizonDays),
18
+ };
19
+ }
2
20
  async function postAgent(opts) {
3
21
  const key = assertKey(opts.key);
4
22
  const fetchImpl = opts.fetchImpl ?? fetch;
@@ -79,12 +97,24 @@ export async function getCostSignal(opts) {
79
97
  clearTimeout(timer);
80
98
  }
81
99
  }
100
+ export function normalizeSessionPerformanceService(value) {
101
+ if (value === undefined)
102
+ return undefined;
103
+ if (typeof value !== "string" || /[\u0000-\u001f]/.test(value))
104
+ return null;
105
+ const service = value.trim();
106
+ return service && Buffer.byteLength(service, "utf8") <= 128 ? service : null;
107
+ }
82
108
  export async function getSessionPerformance(opts) {
109
+ const service = normalizeSessionPerformanceService(opts.service);
110
+ if (service === null)
111
+ return { ok: false, report: null, httpStatus: 0, error: "bad_input", message: "service must contain 1-128 UTF-8 bytes without C0 controls" };
83
112
  const result = await postAgent({
84
113
  ...opts,
85
114
  timeoutMs: opts.timeoutMs ?? 120_000,
86
115
  body: {
87
116
  sessionId: opts.sessionId,
117
+ ...(service === undefined ? {} : { service }),
88
118
  ...(opts.includeFresh === undefined ? {} : { includeFresh: opts.includeFresh }),
89
119
  ...(opts.cacheSamples === undefined ? {} : { cacheSamples: opts.cacheSamples }),
90
120
  },
@@ -152,6 +182,19 @@ export async function searchCodingSessions(opts) {
152
182
  message: result.message,
153
183
  };
154
184
  }
185
+ export async function countReplyPhrases(opts) {
186
+ const result = await postAgent({
187
+ key: opts.key, url: opts.url, fetchImpl: opts.fetchImpl, timeoutMs: opts.timeoutMs ?? 20_000, body: opts.query,
188
+ });
189
+ if (result.bodyError) {
190
+ return { ok: false, trends: null, httpStatus: result.httpStatus, error: result.bodyError, message: `Reply-phrase response headers arrived but its body did not (${result.bodyError}).` };
191
+ }
192
+ const trends = result.value?.trends;
193
+ if (result.ok && (!trends || typeof trends !== "object" || Array.isArray(trends))) {
194
+ return { ok: false, trends: null, httpStatus: result.httpStatus, error: "read_unusable", message: "Reply-phrase response did not contain usable counts." };
195
+ }
196
+ return { ok: result.ok, trends: result.ok ? trends ?? null : null, httpStatus: result.httpStatus, error: result.error, message: result.message };
197
+ }
155
198
  export async function estimateTaskSize(opts) {
156
199
  const result = await postAgent({
157
200
  ...opts,
@@ -176,6 +219,76 @@ export async function estimateTaskSize(opts) {
176
219
  message: result.message,
177
220
  };
178
221
  }
222
+ export async function getHostHealth(opts) {
223
+ assertKey(opts.key);
224
+ let result;
225
+ try {
226
+ result = await postAgent({
227
+ ...opts,
228
+ timeoutMs: opts.timeoutMs ?? 25_000,
229
+ body: {
230
+ ...(opts.lookbackMinutes === undefined ? {} : { lookbackMinutes: opts.lookbackMinutes }),
231
+ ...(opts.thresholds === undefined ? {} : { thresholds: opts.thresholds }),
232
+ ...(opts.diagnose === undefined ? {} : { diagnose: opts.diagnose }),
233
+ },
234
+ });
235
+ }
236
+ catch (err) {
237
+ return {
238
+ ok: false,
239
+ report: null,
240
+ status: null,
241
+ diagnosis: null,
242
+ serverVersion: null,
243
+ reportUnusable: null,
244
+ httpStatus: 0,
245
+ error: "read_unavailable",
246
+ message: `Host-health read could not reach the control plane: ${err.message}`,
247
+ };
248
+ }
249
+ if (result.bodyError) {
250
+ return {
251
+ ok: false,
252
+ report: null,
253
+ status: null,
254
+ diagnosis: null,
255
+ serverVersion: null,
256
+ reportUnusable: null,
257
+ httpStatus: result.httpStatus,
258
+ error: result.bodyError,
259
+ message: `Host-health response headers arrived but its body did not (${result.bodyError}).`,
260
+ };
261
+ }
262
+ const decoded = result.ok ? result.value : null;
263
+ const reportUnusable = (() => {
264
+ if (!result.ok)
265
+ return null;
266
+ if (decoded === null || typeof decoded !== "object") {
267
+ return "the response body could not be read as JSON";
268
+ }
269
+ if (!("report" in decoded))
270
+ return "the response carried no report member";
271
+ if (decoded.report === null)
272
+ return null;
273
+ if (typeof decoded.report !== "object" || Array.isArray(decoded.report)) {
274
+ return "the response report is not an object";
275
+ }
276
+ return null;
277
+ })();
278
+ return {
279
+ ok: result.ok,
280
+ report: result.ok && reportUnusable === null ? result.value?.report ?? null : null,
281
+ status: result.ok && typeof result.value?.status === "string" ? result.value.status : null,
282
+ diagnosis: parseDiagnosis(result.value?.diagnosis),
283
+ serverVersion: typeof result.value?.serverVersion === "string" && result.value.serverVersion.trim()
284
+ ? result.value.serverVersion.trim()
285
+ : null,
286
+ reportUnusable,
287
+ httpStatus: result.httpStatus,
288
+ error: result.error,
289
+ message: result.message,
290
+ };
291
+ }
179
292
  export async function estimateLinearIssue(opts) {
180
293
  const result = await postAgent({
181
294
  ...opts,
@@ -279,3 +392,44 @@ export async function planNextSession(opts) {
279
392
  });
280
393
  return { ok: result.ok, value: result.value ?? null, httpStatus: result.httpStatus, error: result.error, message: result.message };
281
394
  }
395
+ export async function graderConfigRequest(opts) {
396
+ const key = assertKey(opts.key);
397
+ const response = await (opts.fetchImpl ?? fetch)(opts.url, {
398
+ method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
399
+ body: JSON.stringify(opts.body), signal: AbortSignal.timeout(10_000),
400
+ });
401
+ const reader = response.body?.getReader();
402
+ const chunks = [];
403
+ let bytes = 0;
404
+ if (reader)
405
+ try {
406
+ while (true) {
407
+ const chunk = await reader.read();
408
+ if (chunk.done)
409
+ break;
410
+ bytes += chunk.value.byteLength;
411
+ if (bytes > 64 * 1024)
412
+ throw new Error("Grader response exceeds 64 KiB");
413
+ chunks.push(chunk.value);
414
+ }
415
+ }
416
+ finally {
417
+ await reader.cancel().catch(() => { });
418
+ reader.releaseLock();
419
+ }
420
+ let decoded;
421
+ try {
422
+ decoded = JSON.parse(Buffer.concat(chunks).toString("utf8"));
423
+ }
424
+ catch {
425
+ decoded = null;
426
+ }
427
+ const config = decoded?.config;
428
+ return {
429
+ ok: response.ok && decoded?.ok === true && !!config && typeof config === "object" && !Array.isArray(config),
430
+ config,
431
+ httpStatus: response.status,
432
+ error: typeof decoded?.error === "string" ? decoded.error : null,
433
+ message: typeof decoded?.message === "string" ? decoded.message : null,
434
+ };
435
+ }
@@ -0,0 +1,4 @@
1
+ export declare const ONBOARD_CLIENTS: readonly ["claude", "codex", "pi", "kiro"];
2
+ export type OnboardClient = (typeof ONBOARD_CLIENTS)[number];
3
+ export declare function isOnboardClient(value: unknown): value is OnboardClient;
4
+ export declare const SESSION_FILTER_ASSISTANTS: readonly ["claude", "codex", "kiro"];