@agent-watch-ai/edge 0.3.1 → 0.5.0

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 (123) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +10 -6
  3. package/SECURITY.md +7 -4
  4. package/dist/cli/constants/cli.constants.d.ts +2 -0
  5. package/dist/cli/constants/cli.constants.js +3 -1
  6. package/dist/cli/doctor.js +13 -2
  7. package/dist/cli/setup.js +138 -29
  8. package/dist/cli/toggle.js +5 -1
  9. package/dist/cli/types/cli.types.d.ts +6 -0
  10. package/dist/cli/uninstall.js +1 -1
  11. package/dist/cli.js +14 -3
  12. package/dist/config/config-store.d.ts +1 -1
  13. package/dist/config/config-store.js +2 -2
  14. package/dist/config/constants/config.constants.d.ts +4 -1
  15. package/dist/config/constants/config.constants.js +7 -2
  16. package/dist/config/repo-config.js +1 -1
  17. package/dist/config/schemas/config.schema.d.ts +113 -767
  18. package/dist/config/schemas/config.schema.js +17 -8
  19. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  20. package/dist/credentials/constants/credentials.constants.js +9 -1
  21. package/dist/credentials/credential-status.js +8 -4
  22. package/dist/credentials/credentials.d.ts +16 -2
  23. package/dist/credentials/credentials.js +30 -5
  24. package/dist/credentials/device-api.d.ts +10 -1
  25. package/dist/credentials/device-api.js +12 -1
  26. package/dist/credentials/identity.d.ts +12 -1
  27. package/dist/credentials/identity.js +12 -1
  28. package/dist/credentials/migration.d.ts +1 -1
  29. package/dist/credentials/migration.js +1 -1
  30. package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
  31. package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
  32. package/dist/credentials/sign-in.d.ts +14 -1
  33. package/dist/credentials/sign-in.js +24 -5
  34. package/dist/credentials/types/credentials.types.d.ts +12 -1
  35. package/dist/enforcement/decision-client.js +2 -1
  36. package/dist/enforcement/enforcement.js +7 -5
  37. package/dist/enforcement/types/enforcement.types.d.ts +2 -2
  38. package/dist/git/code-state.d.ts +33 -0
  39. package/dist/git/code-state.js +44 -0
  40. package/dist/git/constants/git.constants.d.ts +6 -0
  41. package/dist/git/constants/git.constants.js +6 -0
  42. package/dist/git/index.d.ts +2 -1
  43. package/dist/git/index.js +1 -0
  44. package/dist/git/types/git.types.d.ts +6 -0
  45. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  46. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  47. package/dist/pipeline/hook-pipeline.js +56 -7
  48. package/dist/privacy/command-fingerprint.d.ts +42 -0
  49. package/dist/privacy/command-fingerprint.js +249 -0
  50. package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
  51. package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
  52. package/dist/privacy/index.d.ts +3 -1
  53. package/dist/privacy/index.js +2 -0
  54. package/dist/privacy/product-capture.js +20 -0
  55. package/dist/privacy/types/privacy.types.d.ts +7 -0
  56. package/dist/providers/antigravity/antigravity.adapter.js +3 -0
  57. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
  58. package/dist/providers/claude/claude.adapter.js +12 -1
  59. package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
  60. package/dist/providers/claude/constants/claude.constants.js +6 -0
  61. package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
  62. package/dist/providers/codex/codex.adapter.js +14 -0
  63. package/dist/providers/codex/codex.otel.d.ts +12 -1
  64. package/dist/providers/codex/codex.otel.js +61 -11
  65. package/dist/providers/codex/constants/codex.otel.constants.d.ts +5 -0
  66. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  67. package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
  68. package/dist/providers/constants/provider.constants.d.ts +8 -0
  69. package/dist/providers/constants/provider.constants.js +8 -0
  70. package/dist/providers/cursor/constants/cursor.constants.d.ts +2 -0
  71. package/dist/providers/cursor/constants/cursor.constants.js +2 -0
  72. package/dist/providers/cursor/cursor.adapter.js +84 -5
  73. package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
  74. package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
  75. package/dist/providers/gemini/constants/gemini.constants.js +2 -0
  76. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +16 -1
  77. package/dist/providers/gemini/constants/gemini.otel.constants.js +16 -1
  78. package/dist/providers/gemini/gemini.detect.d.ts +11 -0
  79. package/dist/providers/gemini/gemini.detect.js +14 -1
  80. package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
  81. package/dist/providers/gemini/gemini.hooks.js +5 -5
  82. package/dist/providers/gemini/gemini.otel.d.ts +14 -4
  83. package/dist/providers/gemini/gemini.otel.js +418 -107
  84. package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
  85. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  86. package/dist/providers/shared/bearer-rewrite.js +46 -0
  87. package/dist/providers/shared/constants/tooling.constants.d.ts +6 -0
  88. package/dist/providers/shared/constants/tooling.constants.js +6 -0
  89. package/dist/providers/shared/event-builder.d.ts +17 -2
  90. package/dist/providers/shared/event-builder.js +43 -3
  91. package/dist/providers/shared/install-record.d.ts +2 -0
  92. package/dist/providers/shared/install-record.js +3 -2
  93. package/dist/providers/shared/tooling.d.ts +35 -0
  94. package/dist/providers/shared/tooling.js +61 -1
  95. package/dist/providers/shared/types/adapter.types.d.ts +18 -0
  96. package/dist/providers/types/provider.types.d.ts +24 -0
  97. package/dist/storage/atomic-file.d.ts +14 -0
  98. package/dist/storage/atomic-file.js +19 -0
  99. package/dist/storage/constants/storage.constants.d.ts +2 -0
  100. package/dist/storage/constants/storage.constants.js +2 -0
  101. package/dist/storage/schemas/storage.schema.d.ts +11 -175
  102. package/dist/storage/schemas/storage.schema.js +7 -1
  103. package/dist/transport/schemas/queue.schema.d.ts +1 -16
  104. package/dist/transport/schemas/queue.schema.js +1 -1
  105. package/dist/turns/constants/turns.constants.d.ts +17 -0
  106. package/dist/turns/constants/turns.constants.js +17 -0
  107. package/dist/turns/index.d.ts +3 -2
  108. package/dist/turns/index.js +1 -0
  109. package/dist/turns/tool-events.d.ts +15 -0
  110. package/dist/turns/tool-events.js +59 -0
  111. package/dist/turns/turn-state.js +2 -2
  112. package/dist/turns/turn-summary.d.ts +1 -1
  113. package/dist/turns/turn-summary.js +1 -0
  114. package/dist/turns/turn-tracker.js +138 -7
  115. package/dist/turns/types/turn-state.types.d.ts +28 -1
  116. package/dist/turns/types/turn-summary.types.d.ts +30 -0
  117. package/dist/turns/types/turn-tracker.types.d.ts +10 -0
  118. package/dist/turns/work-checkout.d.ts +5 -3
  119. package/dist/turns/work-checkout.js +46 -12
  120. package/docs/AUDIT_PROMPT.md +11 -0
  121. package/docs/DATA_HANDLING.md +69 -14
  122. package/docs/ENTERPRISE_DEPLOYMENT.md +21 -5
  123. package/package.json +9 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,81 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `@agent-watch-ai/otel` (npm) and `agent-watch-otel` (PyPI) are released
6
+ together from one `otel-vX.Y.Z` tag by `otel-release.yml`, at one version and
7
+ only when both suites pass. `python-release.yml` no longer publishes alone.
8
+
9
+ ## 0.5.0
10
+
11
+ ### Behaviour change: turn summaries carry per-tool-call records
12
+
13
+ `turn.summary` gains `tool_events`: one content-free record per tool call, in
14
+ call order and capped at 200, from Claude Code, Codex, Cursor, Gemini CLI and
15
+ Antigravity. Each record has the tool, call id, status, exit code, start and
16
+ end times, and a fingerprint of the command or connector arguments, hashed in
17
+ memory. An allowlisted check that ran also carries HEAD and a digest of the
18
+ working tree. Nothing is sent with `capture.git` off. `docs/DATA_HANDLING.md`
19
+ lists every field. Needs a platform that accepts `tool_events` (AWT-674).
20
+
21
+ ### Behaviour change: Gemini CLI telemetry moves to `~/.gemini/.env`
22
+
23
+ Gemini CLI 0.63 and later ignore the `env` block in `settings.json`, so native
24
+ telemetry sent nothing. Setup, the hook bearer rewrite, `inspect`, the exporter
25
+ sweep and uninstall now use `~/.gemini/.env`, and remove a block an older
26
+ version left in `settings.json`. Re-run setup on machines with Gemini CLI.
27
+
28
+ ### Security: dependency updates
29
+
30
+ - `smol-toml`, the TOML parser the edge reads agent config files
31
+ with, is now `^1.9.1`, which clears GHSA-r4xh-jqrq-34v2 (quadratic-time
32
+ `parse()` on `<= 1.8.0`). No behaviour change.
33
+ - `zod` is now `^4.6.7` (from 3.x), which clears GHSA-mrhx-c7xc-m3w5
34
+ (memory exhaustion validating oversized constrained collections). It parses
35
+ the config, the delivery queue and every hook payload. No behaviour change:
36
+ nested config defaults still fill in from an empty section.
37
+
38
+ ## 0.4.0
39
+
40
+ - A Cursor MCP call keeps its server name: the before-hook carries it to the
41
+ completion, so `tools_used` keys it `mcp__<server>__<tool>`.
42
+ - A turn reports a checkout below `changed` (carried, referenced, inherited or
43
+ its folder) only if it edited no file or edited one inside that checkout, so
44
+ a turn that edits files elsewhere is no longer charged to that branch. Reads
45
+ never decide this.
46
+ - `tools_used` names each MCP call `mcp__<server>__<tool>` (never its
47
+ arguments). `capture.mcpNames: false` folds them all into `mcp` and keeps the
48
+ count; a repository file can turn it off, never on.
49
+ - An unattended machine (CI, a cloud agent) enrolls with an admin-issued,
50
+ single-use code instead of a browser sign-in:
51
+ `AGENTWATCH_ENROLLMENT_CODE=<code> agentwatch setup "<backend>?organization=<id>"`,
52
+ or pipe the code with `--enrollment-code -`. A code given on the command line
53
+ is refused. `status` and `doctor` say the device was enrolled with an
54
+ admin-issued code; a used or expired code fails with the gateway's reason and
55
+ writes nothing. No git email is needed, since the code names the developer,
56
+ and a re-run with the same code still exported keeps the device instead of
57
+ redeeming the spent code again.
58
+ - MDM rollout needs no key: `agentwatch setup <enrollment-url> --defer-sign-in`
59
+ saves the organization and installs the hooks with no credential (on a
60
+ machine with no device, an enrollment code is redeemed now instead). Until the
61
+ developer runs `agentwatch setup` and signs in as themselves, hooks send and
62
+ queue nothing, no native exporter is configured, and session start, `status`
63
+ and `doctor` say how to finish (doctor warns, it does not fail). A plain
64
+ `agentwatch setup` on such a machine resumes the browser sign-in for the saved
65
+ organization, and needs no git email when the gateway names the approver.
66
+ Running the policy again on an enrolled machine keeps its credential (a
67
+ legacy install key included) and refreshes the rest. A sign-in now also
68
+ stores `organizationId` in the config (global-only; cleared by other machine
69
+ setups and with the device on uninstall). The
70
+ Jamf and Intune templates use this flow and no longer deploy
71
+ `AGENTWATCH_TOKEN`, and uninstall points to the enrollment URL instead of the
72
+ install key.
73
+ - Codex `config.toml` and Gemini `settings.json` hold the device's one-hour
74
+ access token instead of the organization install key, and every hook
75
+ rewrites it there (atomically, 0600) when it rotates. A Codex session keeps
76
+ the token it started with, so after an hour its native export is refused;
77
+ its usage still arrives from the rollout file. See
78
+ `docs/NATIVE_OTLP_TOKENS.md`.
79
+
5
80
  ## 0.3.1
6
81
 
7
82
  - `agentwatch <command> --help` prints the help and exits 0 without running the
package/README.md CHANGED
@@ -28,8 +28,9 @@ Run through npx, setup installs this version globally (`npm install -g`) and fin
28
28
 
29
29
  ## Also here: `agent-watch-otel` (Python)
30
30
 
31
- [`python/agent-watch-otel/`](python/agent-watch-otel) is a separate, separately
32
- released package for **production** LLM spend rather than coding agents. One line
31
+ [`python/agent-watch-otel/`](python/agent-watch-otel) is a separate package,
32
+ released together with its Node twin `@agent-watch-ai/otel`, for **production**
33
+ LLM spend rather than coding agents. One line
33
34
  beside a Phoenix registration sends digests of your prompts — never the prompts —
34
35
  to Agent Watch, including the `service.name` and `service.version` Phoenix drops.
35
36
 
@@ -45,7 +46,7 @@ tracer_provider.add_span_processor(AgentWatchSpanProcessor(token="..."))
45
46
  |---|---|---|---|
46
47
  | **Claude Code** | `~/.claude/settings.json` | Logs, Traces, Metrics | Yes |
47
48
  | **OpenAI Codex** | `~/.codex/hooks.json` | Logs, Traces (`~/.codex/config.toml`) | Yes |
48
- | **Gemini CLI** | `~/.gemini/settings.json` | Logs, Traces, Metrics | Yes |
49
+ | **Gemini CLI** | `~/.gemini/settings.json` | Logs, Traces, Metrics (`~/.gemini/.env`) | Yes |
49
50
  | **Cursor** | `~/.cursor/hooks.json` | None | **No** |
50
51
  | **Google Antigravity** | `~/.gemini/config/hooks.json` | None | **No** |
51
52
 
@@ -56,7 +57,7 @@ branches, ticket keys — is reported for all five.
56
57
  Per-agent notes:
57
58
 
58
59
  * **OpenAI Codex** — new hooks must be trusted once: launch `codex`, type `/hooks`, approve the AgentWatch entries.
59
- * **Gemini CLI** — telemetry runs through `GEMINI_TELEMETRY_ENABLED` with `GEMINI_TELEMETRY_TARGET=local`, and the ingest token travels in `OTEL_EXPORTER_OTLP_HEADERS`; Gemini has no `otelHeadersHelper`.
60
+ * **Gemini CLI** — telemetry is written to `~/.gemini/.env` (Gemini 0.63+ does not apply the `settings.json` `env` block): `GEMINI_TELEMETRY_ENABLED` with `GEMINI_TELEMETRY_TARGET=local`, and the access token in `OTEL_EXPORTER_OTLP_HEADERS`; Gemini has no `otelHeadersHelper`. Gemini loads that file only in a trusted folder, and a project `.env` or `.gemini/.env` found first replaces it. The switch, target and endpoint are also set in the `settings.json` `telemetry` block, and `agentwatch status` warns when a project `.env` hides the token.
60
61
  * **Google Antigravity** — a turn is one *execution*: `PreInvocation`/`PostInvocation` bracket the model calls inside it and only `Stop` closes it. The prompt comes from `common.lastUserInput`; there is no user-prompt hook.
61
62
  * **Cursor** — the CLI emits shell hooks only; the full lifecycle exists in IDE sessions. Cloud agents need a committed `.cursor/hooks.json` and the package installed in the cloud environment. Accepted tab edits (`afterTabFileEdit`) are monitored; high-frequency `beforeTabFileRead` is ignored.
62
63
 
@@ -118,7 +119,8 @@ named in the opening prompt are extracted on the machine and sent as `prompt_jir
118
119
  "toolOutput": false,
119
120
  "sessionTitle": false,
120
121
  "git": true,
121
- "files": true
122
+ "files": true,
123
+ "mcpNames": true
122
124
  }
123
125
  }
124
126
  ```
@@ -134,6 +136,8 @@ named in the opening prompt are extracted on the machine and sent as `prompt_jir
134
136
  generated/display title, which can paraphrase the first prompt. Each is scrubbed, then cut at 200
135
137
  characters. Reading Codex and Cursor's SQLite indexes requires Node 22.12 or newer; older runtimes
136
138
  omit those optional fields. Gemini CLI and Antigravity expose neither, so the edge does not invent one.
139
+ * `mcpNames` (on by default) names each MCP call in `tools_used` as `mcp__<server>__<tool>`, no
140
+ arguments. Off, every MCP call counts under `mcp`. A repository file can turn it off, never on.
137
141
  * The agent's response text has no flag: it never leaves the machine.
138
142
 
139
143
  `git` and `files` are on because they carry metadata, not content: remote, branch, SHA, and the
@@ -263,7 +267,7 @@ To try it locally: `BLOCK=1 npm run example` refuses every check.
263
267
 
264
268
  | Record | How | Contents |
265
269
  |---|---|---|
266
- | `turn.summary` | Edge hooks → `POST <backend>/v1/events` | One completed turn: prompt/response length and hash, tool counts, file paths (repo-relative, and home-relative outside a checkout), Git branch, ticket keys from the branch name and the opening prompt. Prompt text and shell/connector inputs only when opted in. Never response text. |
270
+ | `turn.summary` | Edge hooks → `POST <backend>/v1/events` | One completed turn: prompt/response length and hash, tool counts, file paths (repo-relative, and home-relative outside a checkout), Git branch, ticket keys from the branch name and the opening prompt. With Git capture on, `tool_events`: per tool call its order, status, exit code, times, a sha256 fingerprint of the normalized command or connector arguments (never the text), and for a test/lint/build check over 60 s the commit and a working-tree digest. Prompt text and shell/connector inputs only when opted in. Never response text. |
267
271
  | `llm.call` | The agent's own OTLP → `POST <backend>/v1/otlp/v1/logs` | Token usage, cost and latency per model request. The edge does not proxy this. |
268
272
  | `repo.snapshot` | Edge hooks, after a closed turn | Changed branch/commit metadata, including commit subjects, when Git capture is on. |
269
273
 
package/SECURITY.md CHANGED
@@ -20,13 +20,16 @@ bugs of the highest priority:
20
20
  events, logs, queue files, or diagnostics output
21
21
  - credentials written into agent config files beyond the two sanctioned places: Claude Code
22
22
  gets a short-lived access token via `otelHeadersHelper` (never written to its settings), while
23
- Codex has no headers-helper mechanism, so its OTel exporter carries the Bearer token inside
24
- `~/.codex/config.toml` — which setup therefore keeps at mode 0600. Gemini also stores static
25
- OTLP bearer headers in `~/.gemini/settings.json` (0600); it has no headers helper.
23
+ Codex has no headers-helper mechanism, so its OTel exporter carries the device's one-hour
24
+ access token inside `~/.codex/config.toml` — which setup therefore keeps at mode 0600, and
25
+ every hook rewrites as the token rotates. Gemini stores the same access token in
26
+ `~/.gemini/.env` (0600); it has no headers helper. The device secret is never written
27
+ to either file, and the install key only while the machine has no device yet: the
28
+ first hook with a device token replaces it, and on Windows the next successful setup does (docs/NATIVE_OTLP_TOKENS.md).
26
29
  - a long-lived credential on disk in plaintext where an OS keychain exists. The edge exchanges
27
30
  the organization install key for a per-device credential on its first run after setup or
28
31
  upgrade, records the device beside the install key in `~/.agentwatch/config.json` (the key
29
- stays there, 0600, while Codex and Gemini still present it; AWT-357), and keeps the device
32
+ stays there, 0600, to enroll again when the secret expires), and keeps the device
30
33
  secret in the macOS Keychain, the Secret Service keyring (libsecret) or a Windows
31
34
  DPAPI-protected file. Only where none of those is usable (for example headless Linux) does
32
35
  it fall back to a 0600 file under `~/.agentwatch/credentials/`, and `status` and `doctor`
@@ -7,6 +7,8 @@
7
7
  */
8
8
  export declare const VALUE_FLAGS: ReadonlySet<string>;
9
9
  export declare const FLAG_PREFIX = "--";
10
+ /** `--enrollment-code -`: read the code from stdin. The only value the flag takes. */
11
+ export declare const ENROLLMENT_CODE_STDIN = "-";
10
12
  /** The directory npx unpacks packages into, under the npm cache. */
11
13
  export declare const NPX_CACHE_SEGMENT = "_npx";
12
14
  /** Set on the handed-off setup, so it never hands off again. */
@@ -5,8 +5,10 @@
5
5
  * itself into a boolean — which is how `--otel none` once ignored the selection
6
6
  * entirely.
7
7
  */
8
- export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'developer-email', 'developer-name', 'otel', 'root']);
8
+ export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'enrollment-code', 'developer-email', 'developer-name', 'otel', 'root']);
9
9
  export const FLAG_PREFIX = '--';
10
+ /** `--enrollment-code -`: read the code from stdin. The only value the flag takes. */
11
+ export const ENROLLMENT_CODE_STDIN = '-';
10
12
  /** The directory npx unpacks packages into, under the npm cache. */
11
13
  export const NPX_CACHE_SEGMENT = '_npx';
12
14
  /** Set on the handed-off setup, so it never hands off again. */
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { describeCredential } from '../credentials/credential-status.js';
7
- import { hasCredential } from '../credentials/identity.js';
7
+ import { awaitingSignIn, hasCredential } from '../credentials/identity.js';
8
8
  import { selectRoot } from '../config/root-config.js';
9
9
  import { enabledSignalNames, enforcementUrl, eventsUrl, otlpBaseUrl } from '../config/config.js';
10
10
  import { loadEffectiveConfig } from '../config/repo-config.js';
@@ -21,6 +21,7 @@ import { unattributedCount, unattributedQueue } from '../transport/queue-partiti
21
21
  import { AUTH_REJECTED_STATUSES, CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE } from '../transport/constants/transport.constants.js';
22
22
  import { discardResponseBody } from '../transport/response-body.js';
23
23
  import { edgeHeaders } from '../transport/headers.js';
24
+ import { DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
24
25
  import { buildAuthBlock, buildCliContext, buildHookCommand, buildQueue, resolveContextBearer } from './context.js';
25
26
  import { installedHookChecks } from './hook-check.js';
26
27
  import { BACKEND_CONNECTIVITY_CHECK, BACKEND_PROBE_TIMEOUT_MS, EMPTY_BATCH_REFUSED_STATUS, CLAUDE_MIN_VERSION_FOR_PROMPT_ID, CLAUDE_VERSION_TIMEOUT_MS, DEVELOPER_IDENTITY_CHECK, DEVELOPER_IDENTITY_REMEDIES, DEVELOPER_NAME_REMEDIES, GIT_VERSION_TIMEOUT_MS, MIN_NODE_MAJOR, NO_DEVELOPER_IDENTITY, NO_DEVELOPER_NAME, STALE_QUEUE_AGE_MS } from './constants/cli.constants.js';
@@ -287,8 +288,12 @@ async function developerIdentityCheck(env, context, options) {
287
288
  developerIdentity(context.identityConfig.developerEmail, env.cwd, { home: env.home, run: options.gitRun }),
288
289
  developerDisplayName(context.identityConfig.developerName, env.cwd, { home: env.home, run: options.gitRun })
289
290
  ]);
291
+ // A code names its developer on the platform: a CI runner needs no email of its own.
292
+ if (!identity && context.identityConfig.device?.source === DEVICE_SOURCE_BATCH_CODE)
293
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: 'the identity the enrollment code names' };
294
+ // Not yet a fault on an install waiting for its sign-in, which names the developer.
290
295
  if (!identity)
291
- return { name: DEVELOPER_IDENTITY_CHECK, level: 'fail', detail: `${NO_DEVELOPER_IDENTITY}; ${DEVELOPER_IDENTITY_REMEDIES}` };
296
+ return { name: DEVELOPER_IDENTITY_CHECK, level: awaitingSignIn(context.identityConfig) ? 'warn' : 'fail', detail: `${NO_DEVELOPER_IDENTITY}; ${DEVELOPER_IDENTITY_REMEDIES}` };
292
297
  // The name is reported beside the identity, never instead of it: the address
293
298
  // is what a turn is keyed on, and a reader has to be able to see the value
294
299
  // policy will match.
@@ -361,6 +366,9 @@ function noBackendDetail(context) {
361
366
  */
362
367
  async function probeBackend(url, context) {
363
368
  const name = BACKEND_CONNECTIVITY_CHECK;
369
+ // Nothing to prove, and an install that has not signed in sends nothing at all.
370
+ if (awaitingSignIn(context.identityConfig))
371
+ return { name, level: 'warn', detail: `${url} not probed: not signed in yet` };
364
372
  const bearer = await resolveContextBearer(context, BACKEND_PROBE_TIMEOUT_MS);
365
373
  // Probing with no bearer would earn a 401 that says nothing about the
366
374
  // credential this machine actually holds; the credential check names why.
@@ -506,6 +514,9 @@ async function otelCheck(provider, env, context) {
506
514
  };
507
515
  const status = await provider.nativeTelemetry.inspect(setupContext);
508
516
  const withheld = provider.nativeTelemetry.withheldSignals?.(context.config) ?? [];
517
+ // Setup leaves it out until the sign-in, which configures it.
518
+ if (!status.configured && awaitingSignIn(context.config))
519
+ return { name: `${provider.displayName} native OpenTelemetry`, level: 'warn', detail: 'configured when you sign in with `agentwatch setup`' };
509
520
  return {
510
521
  name: `${provider.displayName} native OpenTelemetry`,
511
522
  level: status.configured ? 'ok' : 'fail',
package/dist/cli/setup.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import { text } from 'node:stream/consumers';
4
5
  import { defaultConfig, enabledSignalNames, eventsUrl, parseOtelSignals, sharesOtlpCollector } from '../config/config.js';
5
- import { ensureInstallationId, storedRetiredCapture, updateConfig, withStoredDevices } from '../config/config-store.js';
6
- import { CONFIG_LOCK_WAIT_MS, CONTENT_CAPTURE_KEYS, ROOT_URL_FIELDS, URL_FIELDS } from '../config/constants/config.constants.js';
6
+ import { ensureInstallationId, loadConfig, storedRetiredCapture, updateConfig, withStoredDevices } from '../config/config-store.js';
7
+ import { CONFIG_LOCK_WAIT_MS, CONTENT_CAPTURE_KEYS, DEFAULT_ENDPOINT, ROOT_URL_FIELDS, URL_FIELDS } from '../config/constants/config.constants.js';
7
8
  import { deliverableOrigin, needsTrust } from '../config/schemas/config.schema.js';
8
9
  import { applyRootOverride, canonicalRoot } from '../config/root-config.js';
9
10
  import { transitionDestination } from '../config/destination.js';
10
11
  import { asRecord, compact } from '../core/object.js';
11
- import { CREDENTIALS_DIR_NAME } from '../credentials/constants/credentials.constants.js';
12
- import { forgetDeviceIfUnused, revokeDeviceIfUnused } from '../credentials/credentials.js';
13
- import { deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
12
+ import { CREDENTIALS_DIR_NAME, DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
13
+ import { forgetDeviceIfUnused, nativeExporterBearer, revokeDeviceIfUnused } from '../credentials/credentials.js';
14
+ import { awaitingSignIn, credentialId, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
14
15
  import { abandonDevice, migrateInstallKey } from '../credentials/migration.js';
15
- import { signInDevice } from '../credentials/sign-in.js';
16
+ import { enrollWithCode, signInDevice } from '../credentials/sign-in.js';
16
17
  import { identityPaths } from '../transport/queue-partition.js';
17
18
  import { clearUninstalled, configScopes, uninstallScope } from '../storage/uninstalled.js';
18
19
  import { storeLabel } from '../credentials/secret-store.js';
@@ -22,10 +23,10 @@ import { providers } from '../providers/registry.js';
22
23
  import { removeRefusedExporters } from '../providers/shared/exporter-allowlist.js';
23
24
  import { saveInstallState } from '../storage/install-state.js';
24
25
  import { readJsonFile } from '../storage/json-file.js';
25
- import { MACHINE_SCOPE, TOKEN_VAR } from '../storage/constants/storage.constants.js';
26
+ import { ENROLLMENT_CODE_VAR, MACHINE_SCOPE, TOKEN_VAR } from '../storage/constants/storage.constants.js';
26
27
  import { signInOpener } from './open-browser.js';
27
28
  import { buildCliContext, buildHookCommand, openIdentityQueue } from './context.js';
28
- import { DEVELOPER_IDENTITY_REMEDIES, NO_CONFIG_WRITTEN, NO_DEVELOPER_IDENTITY, SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
29
+ import { DEVELOPER_IDENTITY_REMEDIES, ENROLLMENT_CODE_STDIN, NO_CONFIG_WRITTEN, NO_DEVELOPER_IDENTITY, SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
29
30
  import { bold, customEndpointOverride, dim, printErrln, println, symbols } from './ui.js';
30
31
  /**
31
32
  * `agentwatch setup` — configure the backend, then register hooks and native
@@ -92,11 +93,31 @@ export async function runSetup(options) {
92
93
  const existingRoot = rootPath === undefined ? undefined : baseConfig.roots?.[rootPath];
93
94
  const inherited = rootPath === undefined ? baseConfig : { endpoint: existingRoot?.endpoint === undefined ? baseConfig.endpoint : existingRoot.endpoint };
94
95
  const heldDevice = rootPath === undefined ? baseConfig.device : existingRoot?.device;
95
- const enrolled = enroll(options, inherited, baseConfig.customEndpoints);
96
+ if (options.deferSignIn === true && (options.setupUrl === undefined || rootPath !== undefined)) {
97
+ println(`${symbols.fail} --defer-sign-in takes the organization enrollment URL and configures the machine, not a project root; nothing was written`);
98
+ return 1;
99
+ }
100
+ const enrolled = enroll({ ...options, setupUrl: options.setupUrl ?? pendingSignInUrl(options, baseConfig, rootPath) }, inherited, baseConfig.customEndpoints);
96
101
  if ('error' in enrolled) {
97
102
  println(`${symbols.fail} ${enrolled.error}`);
98
103
  return 1;
99
104
  }
105
+ const code = await readEnrollmentCode(options, enrolled.signIn !== undefined);
106
+ if ('error' in code) {
107
+ println(`${symbols.fail} ${code.error}`);
108
+ return 1;
109
+ }
110
+ // The same code still exported on a re-run (an MDM re-push) is spent: keep the device it enrolled.
111
+ const heldHere = heldDevice !== undefined && heldDevice.endpoint === enrolled.endpoint;
112
+ const spent = code.code !== undefined && heldHere && heldDevice.codeId === credentialId(code.code);
113
+ const redeem = spent ? undefined : code.code;
114
+ // A code enrolls a machine with no device for this backend now, so there is no sign-in
115
+ // left to defer. A device already held for it stays, as on any deferred re-run.
116
+ const deferred = options.deferSignIn === true && (code.code === undefined || heldHere);
117
+ if (options.deferSignIn === true && !deferred)
118
+ println(`${symbols.warn} an enrollment code is redeemed now; --defer-sign-in is ignored`);
119
+ if (deferred && redeem !== undefined)
120
+ println(`${symbols.warn} this machine already holds a device; the enrollment code was not redeemed (uninstall first to enroll with it)`);
100
121
  if (rootPath !== undefined && !enrolled.token && !enrolled.signIn && !heldDevice) {
101
122
  println(`${symbols.fail} a project root needs its own token: pass --token or $${TOKEN_VAR}, the machine token is not inherited`);
102
123
  return 1;
@@ -109,7 +130,8 @@ export async function runSetup(options) {
109
130
  }
110
131
  const installationId = baseConfig.installationId ?? crypto.randomUUID();
111
132
  const developerEmail = await resolveDeveloperEmail(options, baseConfig);
112
- if (!developerEmail) {
133
+ // A sign-in or a code names the developer itself (checked once it has), and a deferred install names nobody yet.
134
+ if (!developerEmail && !enrolled.signIn) {
113
135
  reportMissingIdentity();
114
136
  return 1;
115
137
  }
@@ -117,16 +139,28 @@ export async function runSetup(options) {
117
139
  // hand the platform a value to store, and the backend coalesces — it keeps the
118
140
  // name it already has only for as long as nobody sends a worse one.
119
141
  const developerName = await resolveDeveloperName(options, baseConfig);
142
+ if (spent)
143
+ println(`${symbols.ok} already enrolled with this enrollment code; it was not redeemed again`);
120
144
  // After every check that can refuse the run, so a developer never signs in
121
- // for a setup that was going to fail anyway.
122
- const signedIn = enrolled.signIn ? await signIn(options, context, { ...enrolled.signIn, endpoint: enrolled.endpoint, installationId }) : undefined;
145
+ // for a setup that was going to fail anyway. A spent code signs nobody in.
146
+ // Deferred: no sign-in here. A device its developer already enrolled is kept below.
147
+ const signedIn = enrolled.signIn && !deferred && !spent ? await signIn(options, context, { ...enrolled.signIn, endpoint: enrolled.endpoint, installationId, code: redeem }) : undefined;
123
148
  if (signedIn && 'error' in signedIn) {
124
149
  println(`${symbols.fail} ${signedIn.error}`);
125
150
  return 1;
126
151
  }
152
+ // A gateway older than AWT-555 names no approver: still nobody to attribute to.
153
+ // A code names its developer on the platform, and a deferred install names nobody yet.
154
+ if (!signedIn?.developerEmail && !developerEmail && !code.code && !deferred) {
155
+ if (signedIn)
156
+ await abandonSignIn(options, context, signedIn);
157
+ reportMissingIdentity();
158
+ return 1;
159
+ }
127
160
  // A root re-run without --token keeps the key its device was exchanged for:
128
- // the key stays beside the device until AWT-357. A sign-in has no key at all.
129
- const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined));
161
+ // the key stays beside the device to enroll again. A sign-in has no key at all.
162
+ // A deferred re-run keeps a legacy machine's key for the same backend: it keeps sending through the migration window.
163
+ const token = signedIn ? undefined : (enrolled.token ?? (heldDevice ? existingRoot?.token : undefined) ?? (deferred && (baseConfig.endpoint ?? DEFAULT_ENDPOINT) === enrolled.endpoint ? baseConfig.token : undefined));
130
164
  // The same key again (an MDM re-push, a re-run) keeps its device; a new key
131
165
  // starts a new enrollment, and the old device would otherwise stand beside
132
166
  // it as a second identity.
@@ -151,7 +185,9 @@ export async function runSetup(options) {
151
185
  println(`${symbols.warn} cleared ${field} (${stored?.[field]}) for ${rootPath ?? 'machine'}; backend is now ${identity.endpoint}; reconfigure this route if it is still required`);
152
186
  }
153
187
  const customEndpoints = nextTrustedOrigins(baseConfig.customEndpoints, previous, enrolled.endpoint, options.allowCustomEndpoint === true, withIdentity);
154
- const config = ensureInstallationId({ ...withIdentity, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
188
+ // Set by an enrollment URL and cleared by any other machine setup, so it never outlives the backend it belongs to.
189
+ const organization = rootPath === undefined ? { organizationId: enrolled.signIn?.organizationId } : {};
190
+ const config = ensureInstallationId({ ...withIdentity, ...organization, ...(signedIn ? { installationId } : {}), customEndpoints, otel, emit: { ...baseConfig.emit, llmCalls: true } });
155
191
  await reportContentDowngrade(context, config);
156
192
  // Under the config lock and onto the file as it is now: a hook may have
157
193
  // exchanged this key while setup was running.
@@ -176,16 +212,13 @@ export async function runSetup(options) {
176
212
  if (rootPath !== undefined && !sharesOtlpCollector(config, applyRootOverride(config, rootPath).config)) {
177
213
  println(`${symbols.warn} native OTLP cannot use this root's bearer with the machine-wide collector; only hook-path events use the root identity`);
178
214
  }
179
- println(`${symbols.ok} developer: ${developerLabel(developerEmail, signedIn)}`);
215
+ if (!deferred || developerEmail)
216
+ println(`${symbols.ok} developer: ${developerLabel(developerEmail, signedIn)}`);
180
217
  if (developerName)
181
218
  println(`${symbols.ok} name: ${developerName}`);
182
219
  println(`${symbols.ok} otel signals: ${enabledSignalNames(otel).join(', ') || 'none'}`);
183
220
  println(dim(` config: ${context.paths.configFile}`));
184
221
  println();
185
- // After the agents, so the Codex and Gemini files this run writes carry the
186
- // install key, which keeps working through the migration window (AWT-357
187
- // moves them to short-lived tokens).
188
- const failures = await installAgents(options, context, config, detected);
189
222
  // Setup is the one way back after an uninstall, for the entry it ran for
190
223
  // only: a root's setup leaves the machine uninstalled, and the reverse.
191
224
  const scope = uninstallScope(rootPath);
@@ -195,6 +228,11 @@ export async function runSetup(options) {
195
228
  if (signedIn && displaced)
196
229
  await revokeDeviceIfUnused({ env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn }, displaced);
197
230
  await exchangeInstallKey(context, afterIdentity, signedIn ? undefined : displaced, rootPath === undefined ? undefined : scope);
231
+ // After the exchange, so the Codex and Gemini files carry the machine's
232
+ // access token, or the install key while it has no device (AWT-357). From
233
+ // the file: the exchange filed the device there.
234
+ const bearer = await nativeExporterBearer({ env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn }, (await loadConfig(context.paths)).config);
235
+ const failures = await installAgents(options, context, config, detected, bearer);
198
236
  // A root with its own credential keeps queueing until its own setup, and
199
237
  // `status` only shows it from inside that root.
200
238
  if (rootPath === undefined) {
@@ -202,6 +240,8 @@ export async function runSetup(options) {
202
240
  println(`${symbols.warn} root ${root} is still uninstalled; run \`agentwatch setup --root ${root}\` to bring it back`);
203
241
  }
204
242
  }
243
+ if (awaitingSignIn(config))
244
+ println(`${symbols.warn} not signed in: the developer runs \`agentwatch setup\` as themselves to finish; nothing is sent until then`);
205
245
  println(failures === 0 ? `${symbols.ok} setup complete` : `${symbols.warn} setup finished with ${failures} skipped step(s) — see above`);
206
246
  println(dim(' restart any agent session already running: it keeps the hooks it started with'));
207
247
  if (detected.some(({ provider }) => provider.id === 'codex'))
@@ -226,30 +266,79 @@ async function abandonSignIn(options, context, signedIn) {
226
266
  /**
227
267
  * Who setup says the developer is. After a sign-in that is the approver. A
228
268
  * gateway older than AWT-555 does not name it, so the line shows the email this
229
- * machine stores and sends, and says the platform credits the approver.
269
+ * machine stores and sends, and says the platform credits the approver. A code
270
+ * names its developer on the platform, so it may enroll with no email here.
230
271
  *
231
- * @param developerEmail - The flag, config or git email.
272
+ * @param developerEmail - The flag, config or git email, if any.
232
273
  * @param signedIn - This run's sign-in, if any.
233
274
  * @returns The text after `developer:`.
234
275
  */
235
276
  function developerLabel(developerEmail, signedIn) {
277
+ const shown = signedIn?.developerEmail ?? developerEmail;
278
+ if (!shown)
279
+ return 'the identity the enrollment code names (no email on this machine)';
236
280
  if (!signedIn)
237
- return developerEmail;
238
- return signedIn.developerEmail ? `${signedIn.developerEmail} (signed in)` : `${developerEmail} (stored on this machine; the platform credits the account that approved the sign-in)`;
281
+ return shown;
282
+ if (signedIn.device.source === DEVICE_SOURCE_BATCH_CODE)
283
+ return `${shown} (stored on this machine; the platform credits the identity the enrollment code names)`;
284
+ return signedIn.developerEmail ? `${shown} (signed in)` : `${shown} (stored on this machine; the platform credits the account that approved the sign-in)`;
285
+ }
286
+ /**
287
+ * The admin-issued enrollment code for this run: from `$AGENTWATCH_ENROLLMENT_CODE`,
288
+ * or stdin with `--enrollment-code -`. Never from argv, where `ps` can read it
289
+ * for the life of the process (SPEC R4). Only an enrollment URL redeems one, so
290
+ * a variable left exported after enrolling does not stop a later setup.
291
+ *
292
+ * @param options - Setup options: the flag, the environment and the stdin seam.
293
+ * @param withUrl - This run was given an enrollment URL.
294
+ * @returns The code, none, or why the run is refused.
295
+ */
296
+ async function readEnrollmentCode(options, withUrl) {
297
+ const flag = options.enrollmentCode;
298
+ if (flag !== undefined && flag !== ENROLLMENT_CODE_STDIN) {
299
+ return { error: `an enrollment code goes in $${ENROLLMENT_CODE_VAR} or on stdin with --enrollment-code -, never on the command line, where other users can read it; nothing was written. If that was a code, ask your admin for a new one` };
300
+ }
301
+ if (flag !== undefined && !withUrl)
302
+ return { error: 'an enrollment code is redeemed with the enrollment URL: agentwatch setup <backend>?organization=<id>; nothing was written' };
303
+ if (!withUrl)
304
+ return {};
305
+ // `||`, as for the token: an exported-but-empty variable is one nobody set.
306
+ if (flag === undefined)
307
+ return { code: options.env.vars[ENROLLMENT_CODE_VAR]?.trim() || undefined };
308
+ const piped = (await (options.readStdin ?? readPipedStdin)()).trim();
309
+ return piped ? { code: piped } : { error: 'no enrollment code on stdin (pipe it in, a terminal is not read); nothing was written' };
239
310
  }
240
311
  /**
241
- * Enroll through the browser and say where the credential went.
312
+ * Stdin for `--enrollment-code -`, only when it is a pipe: a terminal would wait
313
+ * for an end of input nobody knows to type.
314
+ *
315
+ * @returns The piped text, or empty for a terminal or a failed read.
316
+ */
317
+ async function readPipedStdin() {
318
+ // A broken pipe reads as no code, refused like an empty one.
319
+ return process.stdin.isTTY ? '' : text(process.stdin).catch(() => '');
320
+ }
321
+ /**
322
+ * Enroll with the admin-issued code when there is one, else through the
323
+ * browser, and say where the credential went.
242
324
  *
243
325
  * @param options - Setup options, for the environment and test seams.
244
326
  * @param context - Resolved CLI context.
245
- * @param target - Backend, organization and the installation the credential binds to.
327
+ * @param target - Backend, organization, the installation the credential binds to, and the code.
246
328
  * @param target.endpoint - The backend to sign in with.
247
329
  * @param target.organizationId - The organization's public id.
248
330
  * @param target.installationId - The installation the credential is bound to.
331
+ * @param target.code - The admin-issued code; the browser sign-in runs without one.
249
332
  * @returns The device, or the message to show.
250
333
  */
251
334
  async function signIn(options, context, target) {
252
335
  const ctx = { env: options.env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS, fetchFn: options.fetchFn };
336
+ if (target.code) {
337
+ const redeemed = await enrollWithCode(ctx, { endpoint: target.endpoint, code: target.code, installationId: target.installationId, name: os.hostname() });
338
+ if (!('error' in redeemed))
339
+ println(`${symbols.ok} enrolled with an admin-issued code; device credential kept in ${storeLabel(redeemed.device.store)}`);
340
+ return redeemed;
341
+ }
253
342
  const open = signInOpener(options, Boolean(process.stdout.isTTY));
254
343
  const result = await signInDevice(ctx, { ...target, name: os.hostname(), print: println, open, sleep: options.sleep });
255
344
  if ('error' in result)
@@ -420,6 +509,23 @@ async function reportDetection(options) {
420
509
  println();
421
510
  return results.filter(({ detection }) => detection.detected);
422
511
  }
512
+ /**
513
+ * The enrollment URL a plain `agentwatch setup` resumes: the organization an
514
+ * MDM install was configured for, while it still holds no credential. Only
515
+ * when the run names no other backend or key, so those keep their meaning.
516
+ *
517
+ * @param options - Flags and environment.
518
+ * @param baseConfig - Config the run starts from.
519
+ * @param rootPath - The root this run is for, absent for the machine.
520
+ * @returns The URL to sign in with, or undefined.
521
+ */
522
+ function pendingSignInUrl(options, baseConfig, rootPath) {
523
+ if (rootPath !== undefined || options.endpoint || options.token || options.env.vars[TOKEN_VAR]?.trim())
524
+ return undefined;
525
+ if (!awaitingSignIn(baseConfig) || typeof baseConfig.endpoint !== 'string')
526
+ return undefined;
527
+ return `${baseConfig.endpoint}?organization=${baseConfig.organizationId}`;
528
+ }
423
529
  /**
424
530
  * Acquire the backend endpoint and token.
425
531
  *
@@ -588,9 +694,10 @@ async function reportStrandedBacklog(context, previousConfig, config, owner) {
588
694
  * @param context - Resolved CLI context.
589
695
  * @param config - The configuration just written.
590
696
  * @param detected - Agents to install into.
697
+ * @param bearer - What native exporters authenticate with; see `SetupContext.bearer`.
591
698
  * @returns How many steps were skipped or failed.
592
699
  */
593
- async function installAgents(options, context, config, detected) {
700
+ async function installAgents(options, context, config, detected, bearer) {
594
701
  let installState = context.installState;
595
702
  let failures = 0;
596
703
  for (const { provider } of detected) {
@@ -600,13 +707,15 @@ async function installAgents(options, context, config, detected) {
600
707
  paths: context.paths,
601
708
  config,
602
709
  hookCommand: (options.hookCommandFor ?? ((id) => buildHookCommand(options.env, id)))(provider.id),
603
- installState
710
+ installState,
711
+ ...(bearer ? { bearer } : {})
604
712
  };
605
713
  const hooks = await provider.installHooks(setupContext);
606
714
  installState = printOutcome(hooks, installState);
607
715
  if (!hooks.ok)
608
716
  failures++;
609
- if (provider.nativeTelemetry && (await provider.nativeTelemetry.supported(options.env))) {
717
+ // No exporter before a sign-in: it would send with no credential at all.
718
+ if (provider.nativeTelemetry && !awaitingSignIn(config) && (await provider.nativeTelemetry.supported(options.env))) {
610
719
  // First, so an exporter left pointing at a host this config refuses is
611
720
  // gone even when there is no allowed route to write in its place.
612
721
  const swept = await removeRefusedExporters({ ...setupContext, installState }, [provider]);
@@ -1,11 +1,13 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import { z } from 'zod';
3
+ import { nativeExporterBearer } from '../credentials/credentials.js';
3
4
  import { providers } from '../providers/registry.js';
4
5
  import { writeFileAtomic } from '../storage/atomic-file.js';
5
6
  import { SECRET_FILE_MODE } from '../storage/constants/storage.constants.js';
6
7
  import { disabledFile, isDisabled } from '../storage/disabled.js';
7
8
  import { saveInstallState } from '../storage/install-state.js';
8
9
  import { readJsonFile } from '../storage/json-file.js';
10
+ import { SETUP_EXCHANGE_TIMEOUT_MS } from './constants/cli.constants.js';
9
11
  import { buildCliContext, buildHookCommand } from './context.js';
10
12
  import { println } from './ui.js';
11
13
  const suspendedSchema = z.object({ providers: z.array(z.string()) });
@@ -64,13 +66,15 @@ export async function runToggle(env, enabled) {
64
66
  let installState = context.installState;
65
67
  let failures = 0;
66
68
  const restored = [];
69
+ // As setup writes it: the machine's access token, or its install key while it has no device.
70
+ const bearer = enabled ? await nativeExporterBearer({ env, paths: context.paths, timeoutMs: SETUP_EXCHANGE_TIMEOUT_MS }, context.config) : undefined;
67
71
  for (const provider of providers) {
68
72
  if (!targets.includes(provider.id) || !provider.nativeTelemetry)
69
73
  continue;
70
74
  // An uninstall performed while stopped must not be undone by `on`.
71
75
  if (enabled && !(await provider.detect(env)).hooksInstalled)
72
76
  continue;
73
- const setupContext = { ...context, installState, hookCommand: buildHookCommand(env, provider.id) };
77
+ const setupContext = { ...context, installState, hookCommand: buildHookCommand(env, provider.id), ...(bearer ? { bearer } : {}) };
74
78
  try {
75
79
  const outcome = enabled
76
80
  ? await provider.nativeTelemetry.configure(setupContext)
@@ -54,6 +54,10 @@ export interface SetupOptions {
54
54
  /** `--allow-custom-endpoint`: trust an `endpoint` outside the Agent Watch hosts. */
55
55
  readonly allowCustomEndpoint?: boolean;
56
56
  readonly token?: string;
57
+ /** `--enrollment-code` as given: `-` reads the code from stdin; any other value is refused. */
58
+ readonly enrollmentCode?: string;
59
+ /** Reads stdin for `--enrollment-code -`; tests inject the piped text. */
60
+ readonly readStdin?: () => Promise<string>;
57
61
  /** Developer identity for turn summaries; falls back to `git config user.email`. */
58
62
  readonly developerEmail?: string;
59
63
  readonly developerName?: string;
@@ -69,6 +73,8 @@ export interface SetupOptions {
69
73
  readonly gitRun?: GitRunner;
70
74
  /** `--no-browser`: print the sign-in link without opening it. */
71
75
  readonly noBrowser?: boolean;
76
+ /** `--defer-sign-in`: an MDM run saves the organization and stops; the developer signs in later with `agentwatch setup`. */
77
+ readonly deferSignIn?: boolean;
72
78
  /** Browser sign-in seams for tests: the gateway, the poll timer and the browser opener. */
73
79
  readonly openUrl?: (url: string) => void;
74
80
  readonly fetchFn?: typeof fetch;
@@ -111,7 +111,7 @@ function report(outcome, current) {
111
111
  */
112
112
  function revocationLine(revocation) {
113
113
  if (revocation.revoked && revocation.removed)
114
- return `${symbols.ok} device credential revoked on the platform and removed from this machine; setup with an install key enrolls it again`;
114
+ return `${symbols.ok} device credential revoked on the platform and removed from this machine; your organization's setup command (\`agentwatch setup <enrollment-url>\`) enrolls it again`;
115
115
  const leftover = revocation.leftover ? `; remove it by hand from ${revocation.leftover}` : '';
116
116
  if (revocation.revoked)
117
117
  return `${symbols.warn} device credential revoked on the platform but not removed from this machine (${revocation.reason})${leftover}`;