@agent-watch-ai/edge 0.3.1 → 0.4.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 (67) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +7 -3
  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 +1 -1
  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/schemas/config.schema.d.ts +110 -0
  17. package/dist/config/schemas/config.schema.js +12 -3
  18. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  19. package/dist/credentials/constants/credentials.constants.js +9 -1
  20. package/dist/credentials/credential-status.js +8 -4
  21. package/dist/credentials/credentials.d.ts +16 -2
  22. package/dist/credentials/credentials.js +28 -3
  23. package/dist/credentials/device-api.d.ts +10 -1
  24. package/dist/credentials/device-api.js +12 -1
  25. package/dist/credentials/identity.d.ts +12 -1
  26. package/dist/credentials/identity.js +12 -1
  27. package/dist/credentials/migration.d.ts +1 -1
  28. package/dist/credentials/migration.js +1 -1
  29. package/dist/credentials/sign-in.d.ts +14 -1
  30. package/dist/credentials/sign-in.js +24 -5
  31. package/dist/credentials/types/credentials.types.d.ts +12 -1
  32. package/dist/enforcement/decision-client.js +2 -1
  33. package/dist/enforcement/enforcement.js +7 -5
  34. package/dist/enforcement/types/enforcement.types.d.ts +2 -2
  35. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  36. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  37. package/dist/pipeline/hook-pipeline.js +56 -7
  38. package/dist/privacy/product-capture.js +2 -0
  39. package/dist/providers/codex/codex.otel.d.ts +12 -1
  40. package/dist/providers/codex/codex.otel.js +61 -11
  41. package/dist/providers/codex/constants/codex.otel.constants.d.ts +5 -0
  42. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  43. package/dist/providers/constants/provider.constants.d.ts +8 -0
  44. package/dist/providers/constants/provider.constants.js +8 -0
  45. package/dist/providers/cursor/constants/cursor.constants.d.ts +2 -0
  46. package/dist/providers/cursor/constants/cursor.constants.js +2 -0
  47. package/dist/providers/cursor/cursor.adapter.js +79 -3
  48. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +6 -0
  49. package/dist/providers/gemini/constants/gemini.otel.constants.js +6 -0
  50. package/dist/providers/gemini/gemini.otel.d.ts +11 -1
  51. package/dist/providers/gemini/gemini.otel.js +52 -12
  52. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  53. package/dist/providers/shared/bearer-rewrite.js +46 -0
  54. package/dist/providers/shared/constants/tooling.constants.d.ts +6 -0
  55. package/dist/providers/shared/constants/tooling.constants.js +6 -0
  56. package/dist/providers/shared/tooling.d.ts +28 -0
  57. package/dist/providers/shared/tooling.js +52 -1
  58. package/dist/providers/types/provider.types.d.ts +24 -0
  59. package/dist/storage/atomic-file.d.ts +14 -0
  60. package/dist/storage/atomic-file.js +19 -0
  61. package/dist/storage/constants/storage.constants.d.ts +2 -0
  62. package/dist/storage/constants/storage.constants.js +2 -0
  63. package/dist/turns/work-checkout.d.ts +5 -3
  64. package/dist/turns/work-checkout.js +46 -12
  65. package/docs/DATA_HANDLING.md +11 -4
  66. package/docs/ENTERPRISE_DEPLOYMENT.md +19 -4
  67. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import type { DeviceApiResult, EnrollInput, IssuedDeviceCredential, PollSessionInput, RefreshedAccessToken, RefreshInput, RevokeInput, StartedEnrollmentSession, StartSessionInput } from './types/credentials.types.js';
1
+ import type { DeviceApiResult, EnrollInput, IssuedDeviceCredential, PollSessionInput, RedeemCodeInput, RefreshedAccessToken, RefreshInput, RevokeInput, StartedEnrollmentSession, StartSessionInput } from './types/credentials.types.js';
2
2
  /**
3
3
  * Trade the install key for a device credential of this machine's own.
4
4
  *
@@ -10,6 +10,15 @@ import type { DeviceApiResult, EnrollInput, IssuedDeviceCredential, PollSessionI
10
10
  * @returns The credential, or why not.
11
11
  */
12
12
  export declare function enrollDevice(input: EnrollInput): Promise<DeviceApiResult<IssuedDeviceCredential>>;
13
+ /**
14
+ * Trade an admin-issued, single-use code for a device credential (AWT-275 N3).
15
+ * Public on the gateway: the code in the body is the credential, and it names
16
+ * the organization and the identity, so neither is sent.
17
+ *
18
+ * @param input - Gateway base URL, code, installation, machine label, timeout.
19
+ * @returns The credential, or why not (`enrollment_code_invalid` for any code it cannot redeem).
20
+ */
21
+ export declare function redeemEnrollmentCode(input: RedeemCodeInput): Promise<DeviceApiResult<IssuedDeviceCredential>>;
13
22
  /**
14
23
  * Open a browser sign-in session. Public on the gateway: the organization's id
15
24
  * is all it takes, and no install key travels on this path.
@@ -2,7 +2,7 @@ import { joinUrl } from '../config/config.js';
2
2
  import { asRecord } from '../core/object.js';
3
3
  import { AUTHORIZATION_HEADER, CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE, USER_AGENT, USER_AGENT_HEADER } from '../transport/constants/transport.constants.js';
4
4
  import { discardResponseBody, readCappedJson } from '../transport/response-body.js';
5
- import { ENROLL_PATH, ENROLLMENT_SESSION_PATH, ENROLLMENT_SESSION_TOKEN_PATH, KNOWN_REFUSALS, REVOKE_PATH, TOKEN_PATH } from './constants/credentials.constants.js';
5
+ import { ENROLL_CODE_PATH, ENROLL_PATH, ENROLLMENT_SESSION_PATH, ENROLLMENT_SESSION_TOKEN_PATH, KNOWN_REFUSALS, REVOKE_PATH, TOKEN_PATH } from './constants/credentials.constants.js';
6
6
  import { issuedDeviceCredentialSchema, pollErrorSchema, refreshedAccessTokenSchema, startedEnrollmentSessionSchema } from './schemas/device-api.schema.js';
7
7
  /**
8
8
  * Trade the install key for a device credential of this machine's own.
@@ -17,6 +17,17 @@ import { issuedDeviceCredentialSchema, pollErrorSchema, refreshedAccessTokenSche
17
17
  export async function enrollDevice(input) {
18
18
  return post(input, ENROLL_PATH, { developerId: input.developerId, name: input.name }, issuedDeviceCredentialSchema, input.installKey);
19
19
  }
20
+ /**
21
+ * Trade an admin-issued, single-use code for a device credential (AWT-275 N3).
22
+ * Public on the gateway: the code in the body is the credential, and it names
23
+ * the organization and the identity, so neither is sent.
24
+ *
25
+ * @param input - Gateway base URL, code, installation, machine label, timeout.
26
+ * @returns The credential, or why not (`enrollment_code_invalid` for any code it cannot redeem).
27
+ */
28
+ export async function redeemEnrollmentCode(input) {
29
+ return post(input, ENROLL_CODE_PATH, { code: input.code, installationId: input.installationId, name: input.name }, issuedDeviceCredentialSchema);
30
+ }
20
31
  /**
21
32
  * Open a browser sign-in session. Public on the gateway: the organization's id
22
33
  * is all it takes, and no install key travels on this path.
@@ -17,6 +17,17 @@ export declare function identityOf(config: CredentialFields): string | undefined
17
17
  * @returns True for an install key or a device credential.
18
18
  */
19
19
  export declare function hasCredential(config: CredentialFields): boolean;
20
+ /**
21
+ * Whether this is an MDM install still waiting for its developer's sign-in:
22
+ * configured for an organization, holding no credential. It sends and queues
23
+ * nothing, and never adopts an identity of its own (SPEC section 5).
24
+ *
25
+ * @param config - The credential fields of an effective config, with its organization.
26
+ * @returns True until the developer runs `agentwatch setup`.
27
+ */
28
+ export declare function awaitingSignIn(config: CredentialFields & {
29
+ readonly organizationId?: string;
30
+ }): boolean;
20
31
  /**
21
32
  * The device id an install key's credential is filed under.
22
33
  *
@@ -39,7 +50,7 @@ export declare function identityFingerprint(identity: string): string;
39
50
  * The device credential that stands for this config's identity, if any.
40
51
  *
41
52
  * The install key stays beside its device in the config through the migration
42
- * window, because Codex and Gemini still present it (AWT-357). A device whose
53
+ * window, to enroll again when the secret expires. A device whose
43
54
  * id is not that key's is a leftover from an earlier key and stands for
44
55
  * nothing.
45
56
  *
@@ -25,6 +25,17 @@ export function identityOf(config) {
25
25
  export function hasCredential(config) {
26
26
  return identityOf(config) !== undefined;
27
27
  }
28
+ /**
29
+ * Whether this is an MDM install still waiting for its developer's sign-in:
30
+ * configured for an organization, holding no credential. It sends and queues
31
+ * nothing, and never adopts an identity of its own (SPEC section 5).
32
+ *
33
+ * @param config - The credential fields of an effective config, with its organization.
34
+ * @returns True until the developer runs `agentwatch setup`.
35
+ */
36
+ export function awaitingSignIn(config) {
37
+ return config.organizationId !== undefined && !hasCredential(config);
38
+ }
28
39
  /**
29
40
  * The device id an install key's credential is filed under.
30
41
  *
@@ -53,7 +64,7 @@ export function identityFingerprint(identity) {
53
64
  * The device credential that stands for this config's identity, if any.
54
65
  *
55
66
  * The install key stays beside its device in the config through the migration
56
- * window, because Codex and Gemini still present it (AWT-357). A device whose
67
+ * window, to enroll again when the secret expires. A device whose
57
68
  * id is not that key's is a leftover from an earlier key and stands for
58
69
  * nothing.
59
70
  *
@@ -9,7 +9,7 @@ import type { CredentialContext, DeviceCredentialRef } from './types/credentials
9
9
  * `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
10
10
  * cached before the config names the device, so a crash in between costs one
11
11
  * more exchange, never the credential. The install key stays in the config
12
- * beside the device: Codex and Gemini still present it (AWT-357). A failure
12
+ * beside the device, to enroll again when the secret expires. A failure
13
13
  * keeps the key in use, and the next try waits an hour.
14
14
  *
15
15
  * A device the gateway refused counts as no device: an expired secret is
@@ -22,7 +22,7 @@ import { saveSecret, secretStoreFor } from './secret-store.js';
22
22
  * `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
23
23
  * cached before the config names the device, so a crash in between costs one
24
24
  * more exchange, never the credential. The install key stays in the config
25
- * beside the device: Codex and Gemini still present it (AWT-357). A failure
25
+ * beside the device, to enroll again when the secret expires. A failure
26
26
  * keeps the key in use, and the next try waits an hour.
27
27
  *
28
28
  * A device the gateway refused counts as no device: an expired secret is
@@ -1,4 +1,4 @@
1
- import type { CredentialContext, SignedIn, SignInInput } from './types/credentials.types.js';
1
+ import type { CredentialContext, RedeemCodeInput, SignedIn, SignInInput } from './types/credentials.types.js';
2
2
  /**
3
3
  * Enroll this machine through the browser: show the verification code, wait
4
4
  * for the developer to approve it, and keep the device credential it earns.
@@ -16,3 +16,16 @@ import type { CredentialContext, SignedIn, SignInInput } from './types/credentia
16
16
  export declare function signInDevice(ctx: CredentialContext, input: SignInInput): Promise<SignedIn | {
17
17
  readonly error: string;
18
18
  }>;
19
+ /**
20
+ * Enroll this machine with an admin-issued code, for one that has no browser
21
+ * (SPEC R4). No install key and no prompt: the code names the organization and
22
+ * the identity, and is spent by this one redeem. The credential is kept exactly
23
+ * as a sign-in's is.
24
+ *
25
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
26
+ * @param input - Gateway, code, installation and label.
27
+ * @returns The device to name in the config and its secret, or the reason there is none.
28
+ */
29
+ export declare function enrollWithCode(ctx: CredentialContext, input: Omit<RedeemCodeInput, 'timeoutMs' | 'fetchFn'>): Promise<SignedIn | {
30
+ readonly error: string;
31
+ }>;
@@ -1,7 +1,7 @@
1
1
  import { sleep } from '../core/async.js';
2
2
  import { identityPaths } from '../transport/queue-partition.js';
3
- import { POLL_DENIED, POLL_EXPIRED, POLL_PENDING, POLL_SLOW_DOWN, RE_PLAIN_EMAIL, SLOW_DOWN_STEP_MS } from './constants/credentials.constants.js';
4
- import { pollEnrollmentSession, revokeDevice, startEnrollmentSession } from './device-api.js';
3
+ import { DEVICE_SOURCE_BATCH_CODE, POLL_DENIED, POLL_EXPIRED, POLL_PENDING, POLL_SLOW_DOWN, RE_PLAIN_EMAIL, SLOW_DOWN_STEP_MS } from './constants/credentials.constants.js';
4
+ import { pollEnrollmentSession, redeemEnrollmentCode, revokeDevice, startEnrollmentSession } from './device-api.js';
5
5
  import { writeAccessToken } from './device-state.js';
6
6
  import { credentialId } from './identity.js';
7
7
  import { saveSecret } from './secret-store.js';
@@ -61,6 +61,24 @@ export async function signInDevice(ctx, input) {
61
61
  }
62
62
  return { error: 'the sign-in code expired before it was approved; run setup again' };
63
63
  }
64
+ /**
65
+ * Enroll this machine with an admin-issued code, for one that has no browser
66
+ * (SPEC R4). No install key and no prompt: the code names the organization and
67
+ * the identity, and is spent by this one redeem. The credential is kept exactly
68
+ * as a sign-in's is.
69
+ *
70
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
71
+ * @param input - Gateway, code, installation and label.
72
+ * @returns The device to name in the config and its secret, or the reason there is none.
73
+ */
74
+ export async function enrollWithCode(ctx, input) {
75
+ const redeemed = await redeemEnrollmentCode({ ...input, timeoutMs: ctx.timeoutMs, fetchFn: ctx.fetchFn });
76
+ if (redeemed.ok)
77
+ return keep(ctx, input.endpoint, redeemed.value, { source: DEVICE_SOURCE_BATCH_CODE, codeId: credentialId(input.code) });
78
+ if (redeemed.refusal)
79
+ return { error: `the enrollment code was refused (${redeemed.refusal}): it is unknown, used, expired or revoked; ask your admin for a new one. Nothing was written` };
80
+ return { error: `could not redeem the enrollment code with ${input.endpoint} (${redeemed.status ?? 'no response'}); nothing was written` };
81
+ }
64
82
  /**
65
83
  * Store an approved credential. The gateway has issued it by now, so a store
66
84
  * that fails is undone on the platform too: nothing would name the device, and
@@ -68,16 +86,17 @@ export async function signInDevice(ctx, input) {
68
86
  *
69
87
  * @param ctx - Paths, environment, timeout, fetch and keychain runner.
70
88
  * @param endpoint - The gateway that issued it.
71
- * @param issued - The credential the poll returned.
89
+ * @param issued - The credential the poll or the redeem returned.
90
+ * @param enrolledBy - How it was enrolled, when not by sign-in, and the code's fingerprint.
72
91
  * @returns The device and its secret, or the reason it could not be kept.
73
92
  */
74
- async function keep(ctx, endpoint, issued) {
93
+ async function keep(ctx, endpoint, issued, enrolledBy) {
75
94
  const id = credentialId(issued.deviceId);
76
95
  const files = identityPaths(ctx.paths, `device:${id}`);
77
96
  try {
78
97
  const store = await saveSecret(ctx, id, issued.deviceSecret);
79
98
  await writeAccessToken(files.accessTokenFile, { accessToken: issued.accessToken, obtainedAt: ctx.env.now().toISOString(), expiresAt: issued.accessTokenExpiresAt });
80
- return { device: { id, store, endpoint }, deviceSecret: issued.deviceSecret, developerEmail: typeof issued.developerEmail === 'string' && RE_PLAIN_EMAIL.test(issued.developerEmail) ? issued.developerEmail : undefined };
99
+ return { device: { id, store, endpoint, ...enrolledBy }, deviceSecret: issued.deviceSecret, developerEmail: typeof issued.developerEmail === 'string' && RE_PLAIN_EMAIL.test(issued.developerEmail) ? issued.developerEmail : undefined };
81
100
  }
82
101
  catch {
83
102
  await revokeDevice({ endpoint, deviceSecret: issued.deviceSecret, timeoutMs: ctx.timeoutMs, fetchFn: ctx.fetchFn });
@@ -3,7 +3,7 @@ import type { issuedDeviceCredentialSchema, refreshedAccessTokenSchema, startedE
3
3
  import type { accessTokenCacheSchema, deviceStateSchema } from '../schemas/device-state.schema.js';
4
4
  import type { Env } from '../../core/types/core.types.js';
5
5
  import type { AgentWatchPaths } from '../../storage/types/storage.types.js';
6
- import type { CREDENTIAL_STORE_KINDS } from '../constants/credentials.constants.js';
6
+ import type { CREDENTIAL_STORE_KINDS, DEVICE_SOURCE_BATCH_CODE } from '../constants/credentials.constants.js';
7
7
  /** Which backend holds a device secret. */
8
8
  export type CredentialStoreKind = (typeof CREDENTIAL_STORE_KINDS)[number];
9
9
  /**
@@ -20,6 +20,10 @@ export interface DeviceCredentialRef {
20
20
  * before it was recorded.
21
21
  */
22
22
  readonly endpoint?: string;
23
+ /** Set when an admin-issued code enrolled it; absent for a sign-in or an install-key exchange. */
24
+ readonly source?: typeof DEVICE_SOURCE_BATCH_CODE;
25
+ /** Fingerprint of the code that enrolled it, so a re-run with the same, spent code keeps the device. */
26
+ readonly codeId?: string;
23
27
  }
24
28
  /** The credential fields of a config, a root override or an effective config. */
25
29
  export interface CredentialFields {
@@ -109,6 +113,13 @@ export interface PollSessionInput extends DeviceRouteInput {
109
113
  readonly deviceCode: string;
110
114
  readonly installationId: string;
111
115
  }
116
+ /** One redeem of an admin-issued enrollment code. The code is the secret. */
117
+ export interface RedeemCodeInput extends DeviceRouteInput {
118
+ readonly code: string;
119
+ readonly installationId: string;
120
+ /** This machine's label, shown to the admin. */
121
+ readonly name: string;
122
+ }
112
123
  /** A browser sign-in the gateway approved and this machine kept. */
113
124
  export interface SignedIn {
114
125
  readonly device: DeviceCredentialRef;
@@ -73,7 +73,8 @@ function thrownReason(error) {
73
73
  */
74
74
  function decisionUrl(request) {
75
75
  const url = new URL(request.url);
76
- url.searchParams.set(DEVELOPER_ID_PARAM, request.developerId);
76
+ if (request.developerId)
77
+ url.searchParams.set(DEVELOPER_ID_PARAM, request.developerId);
77
78
  // Both or neither. The platform drops a half-stated pair, so sending one half
78
79
  // would only cost the request a parameter nobody reads.
79
80
  if (request.checkout) {
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import { enforcementUrl } from '../config/config.js';
3
3
  import { ENFORCEMENT_WINDOW_MS } from '../config/constants/config.constants.js';
4
4
  import { debugLog } from '../core/logger.js';
5
+ import { DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
5
6
  import { deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
6
7
  import { sha256Hex } from '../events/event-id.js';
7
8
  import { BackendCooldown } from '../transport/cooldown.js';
@@ -30,12 +31,13 @@ import { requestDecision } from './decision-client.js';
30
31
  */
31
32
  export async function resolveEnforcement(options) {
32
33
  const url = enforcementUrl(options.config);
33
- // A device's install key stays in the file for Codex and Gemini, but this
34
+ // A device's install key stays in the file to enroll again, but this
34
35
  // identity sends as the device: only the caller's cached access token will do.
35
36
  const token = options.bearer ?? (deviceFor(options.config) ? undefined : options.config.token);
36
37
  const developerId = options.developerId;
37
- // Nothing was asked, so nobody said no.
38
- if (!enforcementWouldAsk(options.config) || !url || !developerId)
38
+ // Nothing was asked, so nobody said no. A code-enrolled device needs no email:
39
+ // the gateway judges it as the identity the code names.
40
+ if (!enforcementWouldAsk(options.config) || !url || (!developerId && deviceFor(options.config)?.source !== DEVICE_SOURCE_BATCH_CODE))
39
41
  return ALLOW;
40
42
  try {
41
43
  return await decideThroughCache(options, url, token, developerId);
@@ -87,13 +89,13 @@ export function enforcementWouldAsk(config) {
87
89
  * @param options - As given to {@link resolveEnforcement}.
88
90
  * @param url - The decision endpoint.
89
91
  * @param token - Edge token, when there is one to ask with.
90
- * @param developerId - Identity to ask about.
92
+ * @param developerId - Identity to ask about, absent for a code-enrolled device.
91
93
  * @returns The decision to act on.
92
94
  */
93
95
  async function decideThroughCache(options, url, token, developerId) {
94
96
  const cache = new DecisionCache(path.join(options.paths.dataDir, ENFORCEMENT_CACHE_FILE_NAME), options.now);
95
97
  // `enforcementWouldAsk` already required a credential, so there is an identity.
96
- const key = decisionKey(url, identityOf(options.config) ?? '', developerId, options.checkout, options.model);
98
+ const key = decisionKey(url, identityOf(options.config) ?? '', developerId ?? '', options.checkout, options.model);
97
99
  const cached = await cache.read(key);
98
100
  if (cached)
99
101
  return cached;
@@ -75,8 +75,8 @@ export interface DecisionRequest {
75
75
  readonly checkout?: EnforcementCheckout;
76
76
  readonly url: string;
77
77
  readonly token: string;
78
- /** The same identity `turn.summary.developer_id` carries. */
79
- readonly developerId: string;
78
+ /** The same identity `turn.summary.developer_id` carries; absent, the gateway judges the device's own. */
79
+ readonly developerId?: string;
80
80
  readonly installationId?: string;
81
81
  /** The model this session is on, when the collector learned one. */
82
82
  readonly model?: string;
@@ -2,6 +2,7 @@ import type { CanonicalEventType } from '../../events/types/events.types.js';
2
2
  /** Stage names, used in the flow definition and in its debug trace. */
3
3
  export declare const STAGE_RESOLVE_CONTEXT = "resolve-context";
4
4
  export declare const STAGE_PARSE_EVENTS = "parse-events";
5
+ export declare const STAGE_AWAIT_SIGN_IN = "await-sign-in";
5
6
  /** Open folders a tool hook nominates, at most: half of a turn's checkout slots. */
6
7
  export declare const MAX_WORKSPACE_ROOTS = 4;
7
8
  export declare const STAGE_NOMINATE = "nominate";
@@ -13,11 +14,13 @@ export declare const STAGE_ENFORCE = "enforce";
13
14
  export declare const STAGE_ENRICH = "enrich";
14
15
  export declare const STAGE_TRACK_TURN = "track-turn";
15
16
  export declare const STAGE_DELIVER = "deliver";
17
+ export declare const STAGE_REWRITE_BEARERS = "rewrite-bearers";
16
18
  export declare const STAGE_SNAPSHOT = "repo-snapshot";
17
19
  /** Reasons a stage ends the flow early. */
18
20
  export declare const STOP_NO_EVENTS = "provider produced no canonical events";
19
21
  export declare const STOP_DRY_RUN = "dry run: nothing delivered";
20
22
  export declare const STOP_NO_SNAPSHOT = "no closed turn, or git capture is off";
23
+ export declare const STOP_NOT_SIGNED_IN = "installed for an organization, not signed in yet: nothing is sent or queued";
21
24
  /**
22
25
  * Canonical event type whose presence makes a payload the turn's gate.
23
26
  *
@@ -1,6 +1,7 @@
1
1
  /** Stage names, used in the flow definition and in its debug trace. */
2
2
  export const STAGE_RESOLVE_CONTEXT = 'resolve-context';
3
3
  export const STAGE_PARSE_EVENTS = 'parse-events';
4
+ export const STAGE_AWAIT_SIGN_IN = 'await-sign-in';
4
5
  /** Open folders a tool hook nominates, at most: half of a turn's checkout slots. */
5
6
  export const MAX_WORKSPACE_ROOTS = 4;
6
7
  export const STAGE_NOMINATE = 'nominate';
@@ -12,11 +13,13 @@ export const STAGE_ENFORCE = 'enforce';
12
13
  export const STAGE_ENRICH = 'enrich';
13
14
  export const STAGE_TRACK_TURN = 'track-turn';
14
15
  export const STAGE_DELIVER = 'deliver';
16
+ export const STAGE_REWRITE_BEARERS = 'rewrite-bearers';
15
17
  export const STAGE_SNAPSHOT = 'repo-snapshot';
16
18
  /** Reasons a stage ends the flow early. */
17
19
  export const STOP_NO_EVENTS = 'provider produced no canonical events';
18
20
  export const STOP_DRY_RUN = 'dry run: nothing delivered';
19
21
  export const STOP_NO_SNAPSHOT = 'no closed turn, or git capture is off';
22
+ export const STOP_NOT_SIGNED_IN = 'installed for an organization, not signed in yet: nothing is sent or queued';
20
23
  /**
21
24
  * Canonical event type whose presence makes a payload the turn's gate.
22
25
  *
@@ -5,9 +5,10 @@ import { applyProductCapture } from '../privacy/product-capture.js';
5
5
  import { debugLog } from '../core/logger.js';
6
6
  import { next, runFlow, step, stop } from '../core/pipe.js';
7
7
  import { loadEffectiveConfig } from '../config/repo-config.js';
8
- import { CREDENTIAL_BUDGET_SHARE } from '../credentials/constants/credentials.constants.js';
8
+ import { CREDENTIAL_BUDGET_SHARE, NOT_SIGNED_IN } from '../credentials/constants/credentials.constants.js';
9
9
  import { cachedBearer, resolveBearer } from '../credentials/credentials.js';
10
- import { hasCredential, identityOf } from '../credentials/identity.js';
10
+ import { awaitingSignIn, deviceFor, hasCredential, identityOf } from '../credentials/identity.js';
11
+ import { cachedAccessToken } from '../credentials/token-refresher.js';
11
12
  import { credentialScope, inheritedRootConfig, selectRoot, servesMultipleIdentities } from '../config/root-config.js';
12
13
  import { DECISION_BLOCK } from '../enforcement/constants/enforcement.constants.js';
13
14
  import { enforcementWouldAsk, resolveEnforcement } from '../enforcement/enforcement.js';
@@ -17,6 +18,8 @@ import { readGateCheckout } from '../git/gate-checkout.js';
17
18
  import { checkoutRootOf } from '../git/checkout-root.js';
18
19
  import { normalizeRemote } from '../git/remote-sanitize.js';
19
20
  import { developerIdentity, runGit } from '../git/git-context.js';
21
+ import { rewriteNativeBearers } from '../providers/shared/bearer-rewrite.js';
22
+ import { isUninstalled } from '../storage/uninstalled.js';
20
23
  import { shellDirectories } from '../providers/shared/shell-directories.js';
21
24
  import { runSnapshotPipeline } from '../snapshot/snapshot-pipeline.js';
22
25
  import { SnapshotStateStore } from '../snapshot/snapshot-state.js';
@@ -35,14 +38,15 @@ import { installedPackage, startUpdateCheck, updateNotice } from '../update/upda
35
38
  import { TurnStateStore } from '../turns/turn-state.js';
36
39
  import { MAX_TURN_CHECKOUTS, SHELL_REREAD_TYPES, TOOL_START_TYPES } from '../turns/constants/turns.constants.js';
37
40
  import { resolveSurface, trackTurnOutcome } from '../turns/turn-tracker.js';
38
- import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, MAX_WORKSPACE_ROOTS, STAGE_NOMINATE, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STAGE_UNTRACED, STAGE_UPDATE, QUIET_SESSION_SOURCES, STOP_DRY_RUN, STOP_NO_EVENTS, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
41
+ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, MAX_WORKSPACE_ROOTS, STAGE_NOMINATE, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_REWRITE_BEARERS, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STAGE_UNTRACED, STAGE_UPDATE, QUIET_SESSION_SOURCES, STOP_DRY_RUN, STAGE_AWAIT_SIGN_IN, STOP_NO_EVENTS, STOP_NOT_SIGNED_IN, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
39
42
  /**
40
43
  * The hook flow, as the list of stages it is.
41
44
  *
42
45
  * Read top to bottom, this is the whole contract of the hook path: work out
43
46
  * where we are and what the effective config says, turn the payload into
44
47
  * canonical events, ask whether this turn may start at all, attach development
45
- * context, assemble the turn, deliver, and — when a turn has just closed — tell
48
+ * context, assemble the turn, deliver, keep the Codex and Gemini files on the
49
+ * live access token, and — when a turn has just closed — tell
46
50
  * the platform what this repository's recent branches look like.
47
51
  * Every stage takes the whole state and returns the next one, so adding or
48
52
  * reordering a step is a change to this array rather than to a call graph.
@@ -50,6 +54,7 @@ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, S
50
54
  const HOOK_STAGES = [
51
55
  step(STAGE_RESOLVE_CONTEXT, resolveContext),
52
56
  step(STAGE_PARSE_EVENTS, parseEvents),
57
+ step(STAGE_AWAIT_SIGN_IN, awaitSignIn),
53
58
  step(STAGE_NOMINATE, nominate),
54
59
  step(STAGE_UNTRACED, untracedNotice),
55
60
  step(STAGE_UPDATE, updateNoticeStage),
@@ -57,6 +62,7 @@ const HOOK_STAGES = [
57
62
  step(STAGE_ENRICH, enrich),
58
63
  step(STAGE_TRACK_TURN, trackTurnStage),
59
64
  step(STAGE_DELIVER, deliver),
65
+ step(STAGE_REWRITE_BEARERS, rewriteBearers),
60
66
  step(STAGE_SNAPSHOT, snapshot)
61
67
  ];
62
68
  /**
@@ -157,6 +163,29 @@ async function nominate(state) {
157
163
  return next(state);
158
164
  }
159
165
  }
166
+ /**
167
+ * Stop here on an MDM install whose developer has not signed in: nothing is
168
+ * enriched, tracked, sent or queued, because nothing is anyone's yet. A session
169
+ * start says how to finish, the one place the developer is sure to see it.
170
+ *
171
+ * @param state - Current flow state.
172
+ * @returns The state unchanged, or a stop carrying the sign-in notice.
173
+ */
174
+ async function awaitSignIn(state) {
175
+ if (!awaitingSignIn(state.config))
176
+ return next(state);
177
+ return stop(isLoudSessionStart(state) && !state.dryRun ? { ...state, notice: NOT_SIGNED_IN } : state, STOP_NOT_SIGNED_IN);
178
+ }
179
+ /**
180
+ * Whether this payload is a developer starting or resuming work, the moment a
181
+ * notice is worth showing; not a `/clear` or `/compact` mid-session.
182
+ *
183
+ * @param state - Current flow state.
184
+ * @returns True for a session start that is not a quiet one.
185
+ */
186
+ function isLoudSessionStart(state) {
187
+ return state.events.some((event) => event.event.type === 'session.started') && !QUIET_SESSION_SOURCES.has(String(asRecord(state.payload)?.['source']));
188
+ }
160
189
  /**
161
190
  * Tell the developer, as a session starts or resumes, that npm has a newer release.
162
191
  *
@@ -172,9 +201,7 @@ async function nominate(state) {
172
201
  async function updateNoticeStage(state) {
173
202
  if (state.dryRun || state.notice !== undefined || !state.config.updateNotices || !state.provider.getNoticeResponse)
174
203
  return next(state);
175
- if (!state.events.some((event) => event.event.type === 'session.started'))
176
- return next(state);
177
- if (QUIET_SESSION_SOURCES.has(String(asRecord(state.payload)?.['source'])))
204
+ if (!isLoudSessionStart(state))
178
205
  return next(state);
179
206
  const notice = await updateNotice(state.paths.dataDir, state.env.now(), installedPackage().version, () => startUpdateCheck(state.env));
180
207
  return next(notice === undefined ? state : { ...state, notice });
@@ -503,6 +530,28 @@ async function deliver(state) {
503
530
  debugLog(`delivery: sent=${delivery.delivered} queued=${delivery.queued} drained=${delivery.drained} rejected=${delivery.rejected}`);
504
531
  return next({ ...state, delivery });
505
532
  }
533
+ /**
534
+ * Keep Codex and Gemini on the machine's live access token (AWT-357).
535
+ *
536
+ * They read their OTLP header from their own config once, when a session
537
+ * starts, so a file still holding a replaced token would start the next
538
+ * session on one about to expire. After `deliver`, which refreshed the token
539
+ * when it was due, and from the cache only: no network, no keychain. The
540
+ * machine's token, whatever identity this payload sent as, because those files
541
+ * are machine-wide. Never fails the hook.
542
+ *
543
+ * @param state - Current flow state.
544
+ * @returns The state, unchanged.
545
+ */
546
+ async function rewriteBearers(state) {
547
+ const machine = state.globalConfig.config;
548
+ if (!deviceFor(machine) || (await isUninstalled(state.paths)))
549
+ return next(state);
550
+ const bearer = await cachedAccessToken(credentialContext(state, state.config.delivery.timeoutMs), machine).catch(() => undefined);
551
+ if (bearer)
552
+ await rewriteNativeBearers(state.paths, bearer);
553
+ return next(state);
554
+ }
506
555
  /**
507
556
  * Describe the repository's recent branches, after the turn has been delivered.
508
557
  *
@@ -1,3 +1,4 @@
1
+ import { foldMcpNames } from '../providers/shared/tooling.js';
1
2
  import { sanitizeValue } from './sanitizer.js';
2
3
  /**
3
4
  * Reapply current capture policy to persisted records before queueing or sending.
@@ -35,6 +36,7 @@ export function applyProductCapture(event, capture) {
35
36
  return sanitizeValue({
36
37
  ...event,
37
38
  prompt: undefined,
39
+ tools_used: capture?.mcpNames === false ? foldMcpNames(summary.tools_used) : summary.tools_used,
38
40
  response: undefined,
39
41
  prompt_text: capture?.promptText === true ? summary.prompt_text : undefined,
40
42
  tool_inputs: capture?.toolInput === true ? summary.tool_inputs : undefined,
@@ -1,6 +1,6 @@
1
1
  import type { Env } from '../../core/types/core.types.js';
2
2
  import type { AgentWatchConfig, OtelSignalName } from '../../config/types/config.types.js';
3
- import type { NativeTelemetryConfigurator, NativeTelemetryStatus, SetupContext, SetupOutcome } from '../types/provider.types.js';
3
+ import type { BearerRewriteContext, NativeTelemetryConfigurator, NativeTelemetryStatus, SetupContext, SetupOutcome } from '../types/provider.types.js';
4
4
  /**
5
5
  * Configures Codex's own OTLP export.
6
6
  *
@@ -44,6 +44,17 @@ export declare class CodexOtelConfigurator implements NativeTelemetryConfigurato
44
44
  * install state.
45
45
  */
46
46
  uninstall(context: SetupContext): Promise<SetupOutcome>;
47
+ /**
48
+ * Swap the bearer in our exporters for the current one.
49
+ *
50
+ * Only the bearer in our own `[otel]` table changes: an MCP server's
51
+ * `Authorization` that Codex parked inside our markers is not ours. No
52
+ * backup: one per rotation would collect copies of every token.
53
+ *
54
+ * @param context - The recorded file, its contents as read and the current bearer.
55
+ * @returns True when the file was rewritten.
56
+ */
57
+ rewriteBearer(context: BearerRewriteContext): Promise<boolean>;
47
58
  /**
48
59
  * Where the managed block's exporters send. The block is AgentWatch's whole,
49
60
  * so every endpoint in it is.