@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
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { asRecord } from '../../core/object.js';
3
- import { CREDENTIAL_STORE_KINDS, RE_DEVICE_ID } from '../../credentials/constants/credentials.constants.js';
3
+ import { CREDENTIAL_STORE_KINDS, DEVICE_SOURCE_BATCH_CODE, RE_DEVICE_ID } from '../../credentials/constants/credentials.constants.js';
4
4
  import { AGENT_WATCH_HOSTS, CUSTOM_ENDPOINT_MESSAGE, CUSTOM_ENDPOINTS_KEY, DELIVERABLE_URL_MESSAGE, DEVICE_URL_FIELDS, ROOTS_KEY, ROOT_URL_FIELDS, URL_FIELDS, LOOPBACK_HOSTS, DEFAULT_DRAIN_BATCH_SIZE, DEFAULT_ENFORCEMENT_CACHE_TTL_MS, DEFAULT_ENFORCEMENT_TIMEOUT_MS, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_EVENT_AGE_DAYS, DEFAULT_MAX_QUEUE_EVENTS, DEFAULT_SEND_TIMEOUT_MS } from '../constants/config.constants.js';
5
5
  /**
6
6
  * The content flags, off.
@@ -50,7 +50,9 @@ export const captureSchema = z
50
50
  /** The provider's native session name/title, scrubbed and bounded. A generated title can paraphrase the first prompt; the edge never derives one from the prompt. */
51
51
  sessionTitle: z.boolean().default(false),
52
52
  git: z.boolean().default(true),
53
- files: z.boolean().default(true)
53
+ files: z.boolean().default(true),
54
+ /** MCP server and tool names in `tools_used`; false folds them into `mcp`. Metadata, not content. */
55
+ mcpNames: z.boolean().default(true)
54
56
  })
55
57
  .strip();
56
58
  /** Tuning for the in-hook send and the machine-global offline queue. */
@@ -384,7 +386,9 @@ const deviceCredential = z
384
386
  .object({
385
387
  id: z.string().regex(RE_DEVICE_ID),
386
388
  store: z.enum(CREDENTIAL_STORE_KINDS),
387
- endpoint: z.string().optional().catch(undefined)
389
+ endpoint: z.string().optional().catch(undefined),
390
+ source: z.literal(DEVICE_SOURCE_BATCH_CODE).optional().catch(undefined),
391
+ codeId: z.string().optional().catch(undefined)
388
392
  })
389
393
  .strip()
390
394
  .optional()
@@ -429,6 +433,11 @@ export const configSchema = z
429
433
  /** The install key, until it is exchanged for `device` (AWT-356). */
430
434
  token: z.string().optional(),
431
435
  device: deviceCredential,
436
+ /**
437
+ * The organization an enrollment URL named. Beside no credential it marks an
438
+ * MDM install whose developer has not signed in yet: it sends nothing.
439
+ */
440
+ organizationId: z.string().optional(),
432
441
  installationId: z.string().optional(),
433
442
  /** Developer identity attached to turn summaries; falls back to `git config user.email`. */
434
443
  developerEmail: z.string().optional(),
@@ -457,11 +466,11 @@ export const configSchema = z
457
466
  untracedNotices: z.boolean().default(true),
458
467
  /** At session start, say when npm has a newer release; checked at most once a day, in the background. */
459
468
  updateNotices: z.boolean().default(true),
460
- capture: captureSchema.default({}),
461
- emit: emitSchema.default({}),
462
- otel: otelSchema.default({}),
463
- delivery: deliverySchema.default({}),
464
- enforcement: enforcementSchema.default({})
469
+ capture: captureSchema.prefault({}),
470
+ emit: emitSchema.prefault({}),
471
+ otel: otelSchema.prefault({}),
472
+ delivery: deliverySchema.prefault({}),
473
+ enforcement: enforcementSchema.prefault({})
465
474
  })
466
475
  .passthrough()
467
476
  .transform((config) => ({
@@ -53,6 +53,10 @@ export declare const TOKEN_PATH = "/v1/devices/token";
53
53
  /** AWT-275 browser sign-in (RFC 8628): start a session, then poll it with the device code in the body. */
54
54
  export declare const ENROLLMENT_SESSION_PATH = "/v1/devices/enrollment-sessions";
55
55
  export declare const ENROLLMENT_SESSION_TOKEN_PATH = "/v1/devices/enrollment-sessions/token";
56
+ /** AWT-275 unattended enrollment: an admin-issued, single-use code in the body. */
57
+ export declare const ENROLL_CODE_PATH = "/v1/devices/enroll-code";
58
+ /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
59
+ export declare const DEVICE_SOURCE_BATCH_CODE = "batch-code";
56
60
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
57
61
  export declare const POLL_PENDING = "authorization_pending";
58
62
  export declare const POLL_SLOW_DOWN = "slow_down";
@@ -66,6 +70,8 @@ export declare const REVOKE_PATH = "/v1/devices/revoke";
66
70
  export declare const REFUSAL_TOKEN_EXPIRED = "token_expired";
67
71
  export declare const REFUSAL_DEVICE_REVOKED = "device_revoked";
68
72
  export declare const REFUSAL_INSTALL_KEY_RETIRED = "install_key_retired";
73
+ /** The one answer to any code that cannot be redeemed: unknown, used, expired or revoked alike. */
74
+ export declare const REFUSAL_ENROLLMENT_CODE_INVALID = "enrollment_code_invalid";
69
75
  /** The one refusal any run may answer with a new enrollment: the secret only aged out, nobody revoked it. */
70
76
  export declare const REFUSAL_SECRET_EXPIRED = "device_secret_expired";
71
77
  /**
@@ -109,3 +115,5 @@ export declare const ENROLL_RETRY_MS = 3600000;
109
115
  * the gateway already approved.
110
116
  */
111
117
  export declare const RE_PLAIN_EMAIL: RegExp;
118
+ /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
119
+ export declare const NOT_SIGNED_IN = "AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then";
@@ -54,6 +54,10 @@ export const TOKEN_PATH = '/v1/devices/token';
54
54
  /** AWT-275 browser sign-in (RFC 8628): start a session, then poll it with the device code in the body. */
55
55
  export const ENROLLMENT_SESSION_PATH = '/v1/devices/enrollment-sessions';
56
56
  export const ENROLLMENT_SESSION_TOKEN_PATH = '/v1/devices/enrollment-sessions/token';
57
+ /** AWT-275 unattended enrollment: an admin-issued, single-use code in the body. */
58
+ export const ENROLL_CODE_PATH = '/v1/devices/enroll-code';
59
+ /** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
60
+ export const DEVICE_SOURCE_BATCH_CODE = 'batch-code';
57
61
  /** The RFC 8628 answers of a poll that are not failures: keep waiting. */
58
62
  export const POLL_PENDING = 'authorization_pending';
59
63
  export const POLL_SLOW_DOWN = 'slow_down';
@@ -67,6 +71,8 @@ export const REVOKE_PATH = '/v1/devices/revoke';
67
71
  export const REFUSAL_TOKEN_EXPIRED = 'token_expired';
68
72
  export const REFUSAL_DEVICE_REVOKED = 'device_revoked';
69
73
  export const REFUSAL_INSTALL_KEY_RETIRED = 'install_key_retired';
74
+ /** The one answer to any code that cannot be redeemed: unknown, used, expired or revoked alike. */
75
+ export const REFUSAL_ENROLLMENT_CODE_INVALID = 'enrollment_code_invalid';
70
76
  /** The one refusal any run may answer with a new enrollment: the secret only aged out, nobody revoked it. */
71
77
  export const REFUSAL_SECRET_EXPIRED = 'device_secret_expired';
72
78
  /**
@@ -77,7 +83,7 @@ export const REFUSAL_SECRET_EXPIRED = 'device_secret_expired';
77
83
  */
78
84
  export const DEVICE_REFUSALS = new Set([REFUSAL_DEVICE_REVOKED, 'device_unknown', REFUSAL_SECRET_EXPIRED]);
79
85
  /** Every reason the edge acts on, from any route. */
80
- export const KNOWN_REFUSALS = new Set([REFUSAL_TOKEN_EXPIRED, REFUSAL_INSTALL_KEY_RETIRED, ...DEVICE_REFUSALS]);
86
+ export const KNOWN_REFUSALS = new Set([REFUSAL_TOKEN_EXPIRED, REFUSAL_INSTALL_KEY_RETIRED, REFUSAL_ENROLLMENT_CODE_INVALID, ...DEVICE_REFUSALS]);
81
87
  /**
82
88
  * The share of the hook's delivery budget credential work may spend: a
83
89
  * keychain read, a refresh or an exchange together. The send gets the rest, so
@@ -110,3 +116,5 @@ export const ENROLL_RETRY_MS = 3_600_000;
110
116
  * the gateway already approved.
111
117
  */
112
118
  export const RE_PLAIN_EMAIL = /^[^\s@\p{Cc}\p{Cf}]{1,64}@[^\s@\p{Cc}\p{Cf}]{1,189}$/u;
119
+ /** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
120
+ export const NOT_SIGNED_IN = 'AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then';
@@ -1,9 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { isUninstalled } from '../storage/uninstalled.js';
3
3
  import { identityPaths } from '../transport/queue-partition.js';
4
- import { CREDENTIALS_DIR_NAME } from './constants/credentials.constants.js';
4
+ import { CREDENTIALS_DIR_NAME, DEVICE_SOURCE_BATCH_CODE, NOT_SIGNED_IN } from './constants/credentials.constants.js';
5
5
  import { readDeviceState } from './device-state.js';
6
- import { deviceFor, identityOf } from './identity.js';
6
+ import { awaitingSignIn, deviceFor, identityOf } from './identity.js';
7
7
  import { storeLabel } from './secret-store.js';
8
8
  /**
9
9
  * One line on this identity's credential, for `status` and `doctor`: where the
@@ -18,6 +18,8 @@ import { storeLabel } from './secret-store.js';
18
18
  export async function describeCredential(paths, config, scope) {
19
19
  if (await isUninstalled(paths, scope))
20
20
  return { level: 'warn', detail: 'uninstalled — run `agentwatch setup` to enroll this machine again' };
21
+ if (awaitingSignIn(config))
22
+ return { level: 'warn', detail: NOT_SIGNED_IN };
21
23
  const device = deviceFor(config);
22
24
  if (!device && config.token)
23
25
  return { level: 'warn', detail: 'install key, not yet exchanged for a device credential; the next run retries' };
@@ -27,8 +29,10 @@ export async function describeCredential(paths, config, scope) {
27
29
  if (refusal) {
28
30
  return { level: 'fail', detail: `device credential refused by the backend (${refusal.reason}) since ${refusal.since}; events are queued — enroll again with \`agentwatch setup --token <install key>\`` };
29
31
  }
32
+ // SPEC R4: an admin-assigned identity is marked as such wherever it shows.
33
+ const how = device.source === DEVICE_SOURCE_BATCH_CODE ? ', enrolled with an admin-issued code' : '';
30
34
  if (device.store === 'file') {
31
- return { level: 'warn', detail: `device credential in ${storeLabel('file')}: ${path.join(paths.configDir, CREDENTIALS_DIR_NAME)}` };
35
+ return { level: 'warn', detail: `device credential in ${storeLabel('file')}: ${path.join(paths.configDir, CREDENTIALS_DIR_NAME)}${how}` };
32
36
  }
33
- return { level: 'ok', detail: `device credential in ${storeLabel(device.store)}` };
37
+ return { level: 'ok', detail: `device credential in ${storeLabel(device.store)}${how}` };
34
38
  }
@@ -4,8 +4,8 @@ import type { CredentialContext, DeviceCredentialRef, DeviceForgetResult } from
4
4
  * The bearer to send for this config, doing the network work it needs.
5
5
  *
6
6
  * A config whose device is listed sends that device's access token, refreshed
7
- * when due, and never its install key (which stays in the file for Codex and
8
- * Gemini, AWT-357). An install key with no device yet is offered for exchange
7
+ * when due, and never its install key (which stays in the config to enroll
8
+ * again after the secret expires). An install key with no device yet is offered for exchange
9
9
  * first and presented itself only while that fails. A device the gateway
10
10
  * refused is enrolled again when `migrateInstallKey` allows it, and its install
11
11
  * key is never sent in its place. Undefined means "nothing to send with": the
@@ -32,6 +32,20 @@ export declare function resolveBearer(ctx: CredentialContext, config: AgentWatch
32
32
  * @returns The bearer, or undefined (never a throw).
33
33
  */
34
34
  export declare function cachedBearer(ctx: CredentialContext, config: AgentWatchConfig): Promise<string | undefined>;
35
+ /**
36
+ * The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
37
+ * the device access token, refreshed when due. Never the device secret. The
38
+ * install key while there is no access token: no device yet (its exchange
39
+ * is failing), or a device whose refresh is in cooldown or offline. Writing
40
+ * no header would get every export refused, and the hook only swaps an
41
+ * existing bearer. The hook replaces the key once a device token exists. For
42
+ * setup and `on`, which may refresh; the hook rewrites from the cache.
43
+ *
44
+ * @param ctx - Paths, clock, timeout and keychain runner.
45
+ * @param config - The machine config: those files are machine-wide.
46
+ * @returns The access token, the install key, or undefined (never a throw).
47
+ */
48
+ export declare function nativeExporterBearer(ctx: CredentialContext, config: AgentWatchConfig): Promise<string | undefined>;
35
49
  /**
36
50
  * Remove a device secret and its cached token, unless the config still names
37
51
  * that device anywhere: a root may share it with the machine, or with the
@@ -19,8 +19,8 @@ import { cachedAccessToken, currentAccessToken } from './token-refresher.js';
19
19
  * The bearer to send for this config, doing the network work it needs.
20
20
  *
21
21
  * A config whose device is listed sends that device's access token, refreshed
22
- * when due, and never its install key (which stays in the file for Codex and
23
- * Gemini, AWT-357). An install key with no device yet is offered for exchange
22
+ * when due, and never its install key (which stays in the config to enroll
23
+ * again after the secret expires). An install key with no device yet is offered for exchange
24
24
  * first and presented itself only while that fails. A device the gateway
25
25
  * refused is enrolled again when `migrateInstallKey` allows it, and its install
26
26
  * key is never sent in its place. Undefined means "nothing to send with": the
@@ -79,6 +79,30 @@ export async function cachedBearer(ctx, config) {
79
79
  return undefined;
80
80
  }
81
81
  }
82
+ /**
83
+ * The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
84
+ * the device access token, refreshed when due. Never the device secret. The
85
+ * install key while there is no access token: no device yet (its exchange
86
+ * is failing), or a device whose refresh is in cooldown or offline. Writing
87
+ * no header would get every export refused, and the hook only swaps an
88
+ * existing bearer. The hook replaces the key once a device token exists. For
89
+ * setup and `on`, which may refresh; the hook rewrites from the cache.
90
+ *
91
+ * @param ctx - Paths, clock, timeout and keychain runner.
92
+ * @param config - The machine config: those files are machine-wide.
93
+ * @returns The access token, the install key, or undefined (never a throw).
94
+ */
95
+ export async function nativeExporterBearer(ctx, config) {
96
+ try {
97
+ if (await isUninstalled(ctx.paths))
98
+ return undefined;
99
+ return (deviceFor(config) ? await currentAccessToken(ctx, config) : undefined) ?? config.token;
100
+ }
101
+ catch (error) {
102
+ debugLog('credentials: resolving the native exporter bearer failed:', error);
103
+ return undefined;
104
+ }
105
+ }
82
106
  /**
83
107
  * Remove a device secret and its cached token, unless the config still names
84
108
  * that device anywhere: a root may share it with the machine, or with the
@@ -138,8 +162,8 @@ export async function forgetDeviceCredentials(ctx) {
138
162
  const releases = await holdEnrollLocks(ctx, keys.map(credentialId).sort());
139
163
  let held = new Map();
140
164
  let invalid = false;
141
- let marked = true;
142
- let written = 'unchanged';
165
+ let marked;
166
+ let written;
143
167
  try {
144
168
  marked = await markUninstalled(ctx.paths, before.state === 'ok' ? configScopes(before.config.roots) : undefined, ctx.env.now()).then(() => true, (error) => {
145
169
  debugLog('uninstall: writing the marker failed:', error);
@@ -148,7 +172,8 @@ export async function forgetDeviceCredentials(ctx) {
148
172
  written = await updateConfig(ctx.paths, (loaded) => {
149
173
  invalid = loaded.state === 'invalid';
150
174
  held = loaded.state === 'ok' ? heldDevices(loaded.config) : new Map();
151
- if (held.size === 0)
175
+ // A deferred install holds no device, only the organization it waits to sign in to.
176
+ if (held.size === 0 && (loaded.state !== 'ok' || loaded.config.organizationId === undefined))
152
177
  return undefined;
153
178
  const roots = loaded.config.roots ? Object.fromEntries(Object.entries(loaded.config.roots).map(([key, root]) => [key, omitKeys(root, DEVICE_KEY)])) : undefined;
154
179
  return { ...omitKeys(loaded.config, DEVICE_KEY), ...(roots ? { roots } : {}) };
@@ -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
@@ -6,44 +6,15 @@ export declare const issuedDeviceCredentialSchema: z.ZodObject<{
6
6
  deviceSecretExpiresAt: z.ZodString;
7
7
  accessToken: z.ZodString;
8
8
  accessTokenExpiresAt: z.ZodString;
9
- /**
10
- * A browser sign-in's approver, the device's developer (AWT-555); older
11
- * gateways send none. Any shape parses: a bad value must not refuse a device
12
- * the gateway already issued, so the sign-in checks it instead.
13
- */
14
9
  developerEmail: z.ZodOptional<z.ZodUnknown>;
15
- }, "strip", z.ZodTypeAny, {
16
- deviceId: string;
17
- deviceSecret: string;
18
- deviceSecretExpiresAt: string;
19
- accessToken: string;
20
- accessTokenExpiresAt: string;
21
- developerEmail?: unknown;
22
- }, {
23
- deviceId: string;
24
- deviceSecret: string;
25
- deviceSecretExpiresAt: string;
26
- accessToken: string;
27
- accessTokenExpiresAt: string;
28
- developerEmail?: unknown;
29
- }>;
10
+ }, z.core.$strip>;
30
11
  /** `POST /v1/devices/token` answer. The device secret is not rotated, so it is not in it. */
31
12
  export declare const refreshedAccessTokenSchema: z.ZodObject<{
32
13
  deviceId: z.ZodString;
33
14
  accessToken: z.ZodString;
34
15
  accessTokenExpiresAt: z.ZodString;
35
16
  deviceSecretExpiresAt: z.ZodString;
36
- }, "strip", z.ZodTypeAny, {
37
- deviceId: string;
38
- deviceSecretExpiresAt: string;
39
- accessToken: string;
40
- accessTokenExpiresAt: string;
41
- }, {
42
- deviceId: string;
43
- deviceSecretExpiresAt: string;
44
- accessToken: string;
45
- accessTokenExpiresAt: string;
46
- }>;
17
+ }, z.core.$strip>;
47
18
  /** `POST /v1/devices/enrollment-sessions` answer: the codes of one browser sign-in. */
48
19
  export declare const startedEnrollmentSessionSchema: z.ZodObject<{
49
20
  deviceCode: z.ZodString;
@@ -52,26 +23,8 @@ export declare const startedEnrollmentSessionSchema: z.ZodObject<{
52
23
  verificationUriComplete: z.ZodString;
53
24
  expiresIn: z.ZodNumber;
54
25
  interval: z.ZodNumber;
55
- }, "strip", z.ZodTypeAny, {
56
- deviceCode: string;
57
- userCode: string;
58
- verificationUri: string;
59
- verificationUriComplete: string;
60
- expiresIn: number;
61
- interval: number;
62
- }, {
63
- deviceCode: string;
64
- userCode: string;
65
- verificationUri: string;
66
- verificationUriComplete: string;
67
- expiresIn: number;
68
- interval: number;
69
- }>;
26
+ }, z.core.$strip>;
70
27
  /** A poll refused the RFC 6749 §5.2 way: `400 { "error": "…" }`. */
71
28
  export declare const pollErrorSchema: z.ZodObject<{
72
29
  error: z.ZodString;
73
- }, "strip", z.ZodTypeAny, {
74
- error: string;
75
- }, {
76
- error: string;
77
- }>;
30
+ }, z.core.$strip>;
@@ -4,48 +4,13 @@ export declare const accessTokenCacheSchema: z.ZodObject<{
4
4
  accessToken: z.ZodString;
5
5
  obtainedAt: z.ZodString;
6
6
  expiresAt: z.ZodString;
7
- }, "strip", z.ZodTypeAny, {
8
- accessToken: string;
9
- obtainedAt: string;
10
- expiresAt: string;
11
- }, {
12
- accessToken: string;
13
- obtainedAt: string;
14
- expiresAt: string;
15
- }>;
7
+ }, z.core.$strip>;
16
8
  /** What one identity remembers about its device credential, beside the token. */
17
9
  export declare const deviceStateSchema: z.ZodObject<{
18
- /**
19
- * The gateway refused the device secret; nothing but a new enrollment fixes
20
- * it. An expired secret is enrolled again by any run; a revoked or unknown
21
- * device only by setup, so a hook never undoes an admin's revocation.
22
- */
23
10
  refusal: z.ZodOptional<z.ZodObject<{
24
11
  reason: z.ZodString;
25
12
  since: z.ZodString;
26
- }, "strip", z.ZodTypeAny, {
27
- reason: string;
28
- since: string;
29
- }, {
30
- reason: string;
31
- since: string;
32
- }>>;
33
- /** When the install key was last offered for exchange, so a failure backs off. */
13
+ }, z.core.$strip>>;
34
14
  enrollAttemptAt: z.ZodOptional<z.ZodString>;
35
- /** When a Windows hook last started a background refresh, so it starts one, not one per hook. */
36
15
  backgroundRefreshAt: z.ZodOptional<z.ZodString>;
37
- }, "strip", z.ZodTypeAny, {
38
- refusal?: {
39
- reason: string;
40
- since: string;
41
- } | undefined;
42
- enrollAttemptAt?: string | undefined;
43
- backgroundRefreshAt?: string | undefined;
44
- }, {
45
- refusal?: {
46
- reason: string;
47
- since: string;
48
- } | undefined;
49
- enrollAttemptAt?: string | undefined;
50
- backgroundRefreshAt?: string | undefined;
51
- }>;
16
+ }, z.core.$strip>;
@@ -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) {