@agent-watch-ai/edge 0.4.0 → 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 (74) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -3
  3. package/SECURITY.md +1 -1
  4. package/dist/config/config-store.js +1 -1
  5. package/dist/config/repo-config.js +1 -1
  6. package/dist/config/schemas/config.schema.d.ts +93 -857
  7. package/dist/config/schemas/config.schema.js +5 -5
  8. package/dist/credentials/credentials.js +2 -2
  9. package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
  10. package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
  11. package/dist/git/code-state.d.ts +33 -0
  12. package/dist/git/code-state.js +44 -0
  13. package/dist/git/constants/git.constants.d.ts +6 -0
  14. package/dist/git/constants/git.constants.js +6 -0
  15. package/dist/git/index.d.ts +2 -1
  16. package/dist/git/index.js +1 -0
  17. package/dist/git/types/git.types.d.ts +6 -0
  18. package/dist/privacy/command-fingerprint.d.ts +42 -0
  19. package/dist/privacy/command-fingerprint.js +249 -0
  20. package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
  21. package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
  22. package/dist/privacy/index.d.ts +3 -1
  23. package/dist/privacy/index.js +2 -0
  24. package/dist/privacy/product-capture.js +19 -1
  25. package/dist/privacy/types/privacy.types.d.ts +7 -0
  26. package/dist/providers/antigravity/antigravity.adapter.js +3 -0
  27. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
  28. package/dist/providers/claude/claude.adapter.js +12 -1
  29. package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
  30. package/dist/providers/claude/constants/claude.constants.js +6 -0
  31. package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
  32. package/dist/providers/codex/codex.adapter.js +14 -0
  33. package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
  34. package/dist/providers/cursor/cursor.adapter.js +5 -2
  35. package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
  36. package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
  37. package/dist/providers/gemini/constants/gemini.constants.js +2 -0
  38. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +10 -1
  39. package/dist/providers/gemini/constants/gemini.otel.constants.js +11 -2
  40. package/dist/providers/gemini/gemini.detect.d.ts +11 -0
  41. package/dist/providers/gemini/gemini.detect.js +14 -1
  42. package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
  43. package/dist/providers/gemini/gemini.hooks.js +5 -5
  44. package/dist/providers/gemini/gemini.otel.d.ts +6 -6
  45. package/dist/providers/gemini/gemini.otel.js +392 -121
  46. package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
  47. package/dist/providers/shared/event-builder.d.ts +17 -2
  48. package/dist/providers/shared/event-builder.js +43 -3
  49. package/dist/providers/shared/install-record.d.ts +2 -0
  50. package/dist/providers/shared/install-record.js +3 -2
  51. package/dist/providers/shared/tooling.d.ts +7 -0
  52. package/dist/providers/shared/tooling.js +10 -1
  53. package/dist/providers/shared/types/adapter.types.d.ts +18 -0
  54. package/dist/storage/schemas/storage.schema.d.ts +11 -175
  55. package/dist/storage/schemas/storage.schema.js +7 -1
  56. package/dist/transport/schemas/queue.schema.d.ts +1 -16
  57. package/dist/transport/schemas/queue.schema.js +1 -1
  58. package/dist/turns/constants/turns.constants.d.ts +17 -0
  59. package/dist/turns/constants/turns.constants.js +17 -0
  60. package/dist/turns/index.d.ts +3 -2
  61. package/dist/turns/index.js +1 -0
  62. package/dist/turns/tool-events.d.ts +15 -0
  63. package/dist/turns/tool-events.js +59 -0
  64. package/dist/turns/turn-state.js +2 -2
  65. package/dist/turns/turn-summary.d.ts +1 -1
  66. package/dist/turns/turn-summary.js +1 -0
  67. package/dist/turns/turn-tracker.js +138 -7
  68. package/dist/turns/types/turn-state.types.d.ts +28 -1
  69. package/dist/turns/types/turn-summary.types.d.ts +30 -0
  70. package/dist/turns/types/turn-tracker.types.d.ts +10 -0
  71. package/docs/AUDIT_PROMPT.md +11 -0
  72. package/docs/DATA_HANDLING.md +58 -10
  73. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -1
  74. package/package.json +9 -8
@@ -466,11 +466,11 @@ export const configSchema = z
466
466
  untracedNotices: z.boolean().default(true),
467
467
  /** At session start, say when npm has a newer release; checked at most once a day, in the background. */
468
468
  updateNotices: z.boolean().default(true),
469
- capture: captureSchema.default({}),
470
- emit: emitSchema.default({}),
471
- otel: otelSchema.default({}),
472
- delivery: deliverySchema.default({}),
473
- enforcement: enforcementSchema.default({})
469
+ capture: captureSchema.prefault({}),
470
+ emit: emitSchema.prefault({}),
471
+ otel: otelSchema.prefault({}),
472
+ delivery: deliverySchema.prefault({}),
473
+ enforcement: enforcementSchema.prefault({})
474
474
  })
475
475
  .passthrough()
476
476
  .transform((config) => ({
@@ -162,8 +162,8 @@ export async function forgetDeviceCredentials(ctx) {
162
162
  const releases = await holdEnrollLocks(ctx, keys.map(credentialId).sort());
163
163
  let held = new Map();
164
164
  let invalid = false;
165
- let marked = true;
166
- let written = 'unchanged';
165
+ let marked;
166
+ let written;
167
167
  try {
168
168
  marked = await markUninstalled(ctx.paths, before.state === 'ok' ? configScopes(before.config.roots) : undefined, ctx.env.now()).then(() => true, (error) => {
169
169
  debugLog('uninstall: writing the marker failed:', error);
@@ -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>;
@@ -0,0 +1,33 @@
1
+ import type { CodeState, GitRunner } from './types/git.types.js';
2
+ export type { CodeState } from './types/git.types.js';
3
+ /** Hashes what one git command writes to stdout; undefined unless it exits 0. */
4
+ export type GitDigester = (args: readonly string[], cwd: string, timeoutMs: number) => Promise<string | undefined>;
5
+ /**
6
+ * HEAD and a digest of the uncommitted diff, taken in the completion hook of
7
+ * a check so a later run of it can be told to cover an earlier one only on
8
+ * the same code (workflow SPEC §11.2). Only for an allowlisted call that ran
9
+ * for a minute: the processes are on the agent's path.
10
+ *
11
+ * Read-only on purpose. `git stash create`, which the plan named, refreshes
12
+ * and writes the index under a lock `--no-optional-locks` does not cover, so
13
+ * it could fail the agent's own `git commit`. `git diff HEAD --binary` writes
14
+ * nothing, and is streamed into the hash, so no diff is cut at a buffer and
15
+ * a failed or timed-out run sends no digest rather than a wrong one. A clean
16
+ * checkout digests the empty diff. Untracked files are not covered.
17
+ *
18
+ * @param cwd - Where the call ran.
19
+ * @param run - Git runner; injectable for tests.
20
+ * @param digest - Streaming hasher; injectable for tests.
21
+ * @param timeoutMs - Budget per git process.
22
+ * @returns The state, or undefined outside a repository or before its first commit.
23
+ */
24
+ export declare function codeStateAt(cwd: string, run?: GitRunner, digest?: GitDigester, timeoutMs?: number): Promise<CodeState | undefined>;
25
+ /**
26
+ * sha256 of a git command's stdout, streamed: never buffered, never cut.
27
+ *
28
+ * @param args - Argument vector.
29
+ * @param cwd - Working directory.
30
+ * @param timeoutMs - Kill budget.
31
+ * @returns The hex digest when git exits 0, else undefined. Never rejects.
32
+ */
33
+ export declare const digestGitOutput: GitDigester;
@@ -0,0 +1,44 @@
1
+ import { spawn } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
+ import { GIT_NO_OPTIONAL_LOCKS, GIT_TIMEOUT_MS, RE_OBJECT_ID, UNCOMMITTED_DIFF_ARGS } from './constants/git.constants.js';
4
+ import { runGit } from './git-context.js';
5
+ /**
6
+ * HEAD and a digest of the uncommitted diff, taken in the completion hook of
7
+ * a check so a later run of it can be told to cover an earlier one only on
8
+ * the same code (workflow SPEC §11.2). Only for an allowlisted call that ran
9
+ * for a minute: the processes are on the agent's path.
10
+ *
11
+ * Read-only on purpose. `git stash create`, which the plan named, refreshes
12
+ * and writes the index under a lock `--no-optional-locks` does not cover, so
13
+ * it could fail the agent's own `git commit`. `git diff HEAD --binary` writes
14
+ * nothing, and is streamed into the hash, so no diff is cut at a buffer and
15
+ * a failed or timed-out run sends no digest rather than a wrong one. A clean
16
+ * checkout digests the empty diff. Untracked files are not covered.
17
+ *
18
+ * @param cwd - Where the call ran.
19
+ * @param run - Git runner; injectable for tests.
20
+ * @param digest - Streaming hasher; injectable for tests.
21
+ * @param timeoutMs - Budget per git process.
22
+ * @returns The state, or undefined outside a repository or before its first commit.
23
+ */
24
+ export async function codeStateAt(cwd, run = runGit, digest = digestGitOutput, timeoutMs = GIT_TIMEOUT_MS) {
25
+ const [commit, diffFp] = await Promise.all([run(['rev-parse', 'HEAD'], cwd, timeoutMs), digest(UNCOMMITTED_DIFF_ARGS, cwd, timeoutMs)]);
26
+ if (commit === undefined || !RE_OBJECT_ID.test(commit))
27
+ return undefined;
28
+ return { commit, diffFp };
29
+ }
30
+ /**
31
+ * sha256 of a git command's stdout, streamed: never buffered, never cut.
32
+ *
33
+ * @param args - Argument vector.
34
+ * @param cwd - Working directory.
35
+ * @param timeoutMs - Kill budget.
36
+ * @returns The hex digest when git exits 0, else undefined. Never rejects.
37
+ */
38
+ export const digestGitOutput = (args, cwd, timeoutMs) => new Promise((resolve) => {
39
+ const hash = crypto.createHash('sha256');
40
+ const child = spawn('git', [GIT_NO_OPTIONAL_LOCKS, ...args], { cwd, timeout: timeoutMs, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
41
+ child.stdout.on('data', (chunk) => hash.update(chunk));
42
+ child.on('error', () => resolve(undefined));
43
+ child.on('close', (code) => resolve(code === 0 ? hash.digest('hex') : undefined));
44
+ });
@@ -4,6 +4,12 @@ export declare const GIT_TIMEOUT_MS = 1000;
4
4
  export declare const MAX_CHANGED_FILES = 50;
5
5
  /** Prepended to every git call: status and diff then never write `index.lock`. */
6
6
  export declare const GIT_NO_OPTIONAL_LOCKS = "--no-optional-locks";
7
+ /**
8
+ * The uncommitted diff a check's `diff_fp` digests: byte-stable across runs on
9
+ * one machine, so none of the user's diff config (external drivers, textconv,
10
+ * colour, prefixes, rename detection) can change it between two runs.
11
+ */
12
+ export declare const UNCOMMITTED_DIFF_ARGS: readonly string[];
7
13
  /** stdout ceiling per git process. */
8
14
  export declare const GIT_MAX_BUFFER_BYTES: number;
9
15
  /**
@@ -4,6 +4,12 @@ export const GIT_TIMEOUT_MS = 1000;
4
4
  export const MAX_CHANGED_FILES = 50;
5
5
  /** Prepended to every git call: status and diff then never write `index.lock`. */
6
6
  export const GIT_NO_OPTIONAL_LOCKS = '--no-optional-locks';
7
+ /**
8
+ * The uncommitted diff a check's `diff_fp` digests: byte-stable across runs on
9
+ * one machine, so none of the user's diff config (external drivers, textconv,
10
+ * colour, prefixes, rename detection) can change it between two runs.
11
+ */
12
+ export const UNCOMMITTED_DIFF_ARGS = ['diff', 'HEAD', '--binary', '--no-ext-diff', '--no-textconv', '--no-color', '--no-renames', '--src-prefix=a/', '--dst-prefix=b/'];
7
13
  /** stdout ceiling per git process. */
8
14
  export const GIT_MAX_BUFFER_BYTES = 1024 * 1024;
9
15
  /**
@@ -2,9 +2,10 @@
2
2
  * Where the work happened: repository, branch, commit and dirty files, with
3
3
  * remote credentials stripped before anything is stored or sent.
4
4
  */
5
- export type { GitContext, GitContextOptions, GitRunner, GitUserEmailOptions, RemoteParts } from './types/git.types.js';
5
+ export type { CodeState, GitContext, GitContextOptions, GitRunner, GitUserEmailOptions, RemoteParts } from './types/git.types.js';
6
6
  export type { BranchCommit, BranchRef, CommitFile, SnapshotBranch } from './types/snapshot.types.js';
7
7
  export type { RepositoryRootFinder } from './types/repository-root.types.js';
8
+ export { codeStateAt } from './code-state.js';
8
9
  export { collectGitContext, developerIdentity, gitUserEmail, runGit } from './git-context.js';
9
10
  export { collectBranchCommits, collectBranchRefs, parseCommitFiles, resolveDefaultBranch } from './repo-snapshot.js';
10
11
  export { normalizeRemote, remoteHash, stripRemoteCredentials } from './remote-sanitize.js';
package/dist/git/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { codeStateAt } from './code-state.js';
1
2
  export { collectGitContext, developerIdentity, gitUserEmail, runGit } from './git-context.js';
2
3
  export { collectBranchCommits, collectBranchRefs, parseCommitFiles, resolveDefaultBranch } from './repo-snapshot.js';
3
4
  export { normalizeRemote, remoteHash, stripRemoteCredentials } from './remote-sanitize.js';
@@ -89,3 +89,9 @@ export interface ContentHash {
89
89
  readonly path: string;
90
90
  readonly blob_sha: string;
91
91
  }
92
+ /** The code a check ran on (workflow SPEC §11.2): HEAD plus a digest of the working tree. */
93
+ export interface CodeState {
94
+ readonly commit: string;
95
+ /** sha256 of `git diff HEAD --binary`; absent when git could not say. */
96
+ readonly diffFp?: string;
97
+ }
@@ -0,0 +1,42 @@
1
+ import type { CommandFingerprint } from './types/privacy.types.js';
2
+ /**
3
+ * The command as the fingerprint sees it: split into segments on `&&`, `||`,
4
+ * `;`, `|`, `&` and line breaks; quotes and escapes undone; comments,
5
+ * redirections with their targets, leading `VAR=value` words and `cd` segments
6
+ * dropped; each segment's words joined by one space and the segments by LF.
7
+ *
8
+ * ponytail: a lexer, not a shell. `$(…)` and backticks stay literal text, a
9
+ * heredoc body reads as further segments, and `"a b"` meets `a b`. Two
10
+ * commands that differ only there share a digest, which is the direction to
11
+ * err in: a repeated status poll must still look repeated.
12
+ *
13
+ * @param command - The command text; anything else reads as empty.
14
+ * @returns The normalised command, `''` when nothing is left.
15
+ */
16
+ export declare function normaliseCommand(command: unknown): string;
17
+ /**
18
+ * The first segment on the check allowlist, normalised as {@link normaliseCommand} does.
19
+ *
20
+ * @param command - The command text.
21
+ * @returns The segment, or null when no segment is a check.
22
+ */
23
+ export declare function checkSegment(command: unknown): string | null;
24
+ /**
25
+ * The digest the edge sends for a shell call. A check is fingerprinted on its
26
+ * matching segment only, so `cd pkg && npm test` and `npm test 2>&1 | tail`
27
+ * are the same run of the same check. Unkeyed: core stores only its re-key
28
+ * under the tenant's key.
29
+ *
30
+ * @param command - The command text, read in memory and dropped.
31
+ * @returns The digest and whether a segment is on the check allowlist.
32
+ */
33
+ export declare function commandFingerprint(command: unknown): CommandFingerprint;
34
+ /**
35
+ * The command a shell tool's input states: a string, or an argv whose
36
+ * `bash -lc <script>` wrapper is unwrapped and any other words joined, as core
37
+ * reads Codex's argv.
38
+ *
39
+ * @param value - The command field as the payload carries it.
40
+ * @returns The command text, or undefined when there is none.
41
+ */
42
+ export declare function commandText(value: unknown): string | undefined;
@@ -0,0 +1,249 @@
1
+ import { sha256Hex } from '../events/event-id.js';
2
+ import { CHECK_PROGRAMS, CHECK_SCRIPTS, DOUBLE_QUOTE_ESCAPES, MAX_COMMAND_CODE_POINTS, RE_ASSIGNMENT, RE_DUPLICATION_CHAR, RE_FD_PREFIX, RE_PYTHON, RE_SCRIPT_VARIANT, RUN_SCRIPT_WORDS, SCRIPT_RUNNERS, SHELL_SCRIPT_FLAGS, SHELL_WRAPPERS, SUBCOMMAND_CHECKS } from './constants/command-fingerprint.constants.js';
3
+ /*
4
+ * A port of core's `@agent-watch/fingerprint` command scheme (AWT-674). Core
5
+ * fingerprints the same call from the agent's OTLP export, so the two must
6
+ * agree to the byte: `tests/command-fingerprint.test.ts` replays core's golden
7
+ * vectors against this file. Change a rule there first, never here alone.
8
+ */
9
+ /**
10
+ * The command as the fingerprint sees it: split into segments on `&&`, `||`,
11
+ * `;`, `|`, `&` and line breaks; quotes and escapes undone; comments,
12
+ * redirections with their targets, leading `VAR=value` words and `cd` segments
13
+ * dropped; each segment's words joined by one space and the segments by LF.
14
+ *
15
+ * ponytail: a lexer, not a shell. `$(…)` and backticks stay literal text, a
16
+ * heredoc body reads as further segments, and `"a b"` meets `a b`. Two
17
+ * commands that differ only there share a digest, which is the direction to
18
+ * err in: a repeated status poll must still look repeated.
19
+ *
20
+ * @param command - The command text; anything else reads as empty.
21
+ * @returns The normalised command, `''` when nothing is left.
22
+ */
23
+ export function normaliseCommand(command) {
24
+ return segmentsOf(command)
25
+ .map((words) => words.join(' '))
26
+ .join('\n');
27
+ }
28
+ /**
29
+ * The first segment on the check allowlist, normalised as {@link normaliseCommand} does.
30
+ *
31
+ * @param command - The command text.
32
+ * @returns The segment, or null when no segment is a check.
33
+ */
34
+ export function checkSegment(command) {
35
+ const segment = segmentsOf(command).find(isCheckCommand);
36
+ return segment === undefined ? null : segment.join(' ');
37
+ }
38
+ /**
39
+ * The digest the edge sends for a shell call. A check is fingerprinted on its
40
+ * matching segment only, so `cd pkg && npm test` and `npm test 2>&1 | tail`
41
+ * are the same run of the same check. Unkeyed: core stores only its re-key
42
+ * under the tenant's key.
43
+ *
44
+ * @param command - The command text, read in memory and dropped.
45
+ * @returns The digest and whether a segment is on the check allowlist.
46
+ */
47
+ export function commandFingerprint(command) {
48
+ const check = checkSegment(command);
49
+ if (check !== null)
50
+ return { digest: sha256Hex(check), matchesCheck: true };
51
+ const normalised = normaliseCommand(command);
52
+ return { digest: normalised === '' ? null : sha256Hex(normalised), matchesCheck: false };
53
+ }
54
+ /**
55
+ * The command a shell tool's input states: a string, or an argv whose
56
+ * `bash -lc <script>` wrapper is unwrapped and any other words joined, as core
57
+ * reads Codex's argv.
58
+ *
59
+ * @param value - The command field as the payload carries it.
60
+ * @returns The command text, or undefined when there is none.
61
+ */
62
+ export function commandText(value) {
63
+ if (typeof value === 'string')
64
+ return value || undefined;
65
+ if (!Array.isArray(value))
66
+ return undefined;
67
+ const argv = value.filter((word) => typeof word === 'string');
68
+ const [program = '', flag = '', script] = argv;
69
+ if (argv.length === 0)
70
+ return undefined;
71
+ const wrapped = SHELL_WRAPPERS.has(basename(program)) && SHELL_SCRIPT_FLAGS.has(flag);
72
+ return wrapped && argv.length === 3 && script !== undefined ? script : argv.join(' ');
73
+ }
74
+ function segmentsOf(command) {
75
+ if (typeof command !== 'string')
76
+ return [];
77
+ return new CommandLexer(clampCodePoints(command.normalize('NFC'), MAX_COMMAND_CODE_POINTS))
78
+ .segments()
79
+ .map(withoutAssignments)
80
+ .filter((words) => words.length > 0 && words[0] !== 'cd');
81
+ }
82
+ /** Drops the `VAR=value` words that set a command's environment; a bare assignment leaves nothing. */
83
+ function withoutAssignments(words) {
84
+ const first = words.findIndex((word) => !RE_ASSIGNMENT.test(word));
85
+ return first === -1 ? [] : words.slice(first);
86
+ }
87
+ function isCheckCommand(words) {
88
+ const program = basename(words[0] ?? '');
89
+ const args = words.slice(1).filter((word) => !word.startsWith('-'));
90
+ if (CHECK_PROGRAMS.has(program))
91
+ return true;
92
+ if (program === 'npx')
93
+ return isCheckCommand(args);
94
+ if (RE_PYTHON.test(program) && words[1] === '-m')
95
+ return isCheckCommand(words.slice(2));
96
+ if (SCRIPT_RUNNERS.has(program))
97
+ return isCheckScript(args);
98
+ return SUBCOMMAND_CHECKS.get(program)?.has(args[0] ?? '') ?? false;
99
+ }
100
+ /** `npm test`, `npm run lint`, `pnpm run test:unit`. A flag's separate value can hide the script. */
101
+ function isCheckScript(args) {
102
+ const script = RUN_SCRIPT_WORDS.has(args[0] ?? '') ? args[1] : args[0];
103
+ return script !== undefined && CHECK_SCRIPTS.has(script.replace(RE_SCRIPT_VARIANT, ''));
104
+ }
105
+ function basename(word) {
106
+ return word.slice(word.lastIndexOf('/') + 1);
107
+ }
108
+ /**
109
+ * Words per segment, in one pass. Operators are recognised outside quotes
110
+ * only. The rules, in the order they are tried at each character, are the
111
+ * vectors file's `rules.lexer`.
112
+ */
113
+ class CommandLexer {
114
+ text;
115
+ done = [];
116
+ words = [];
117
+ word = null;
118
+ /** The next word is a redirection target and is dropped. */
119
+ dropNext = false;
120
+ constructor(text) {
121
+ this.text = text;
122
+ }
123
+ segments() {
124
+ let i = 0;
125
+ while (i < this.text.length)
126
+ i = this.step(i);
127
+ this.endSegment();
128
+ return this.done;
129
+ }
130
+ /** Reads one token's worth from `i` and returns where the next one starts. */
131
+ step(i) {
132
+ const char = this.text.charAt(i);
133
+ if (char === '\\')
134
+ return this.escaped(i);
135
+ if (char === "'")
136
+ return this.singleQuoted(i);
137
+ if (char === '"')
138
+ return this.doubleQuoted(i);
139
+ if (char === '#' && this.word === null)
140
+ return this.lineEnd(i);
141
+ return this.operator(i, char);
142
+ }
143
+ operator(i, char) {
144
+ const next = this.text[i + 1];
145
+ if (char === '&' && next === '>')
146
+ return this.redirection(i + 1);
147
+ if (char === '>' || char === '<')
148
+ return this.redirection(i);
149
+ const separator = separatorLength(char, next);
150
+ if (separator > 0) {
151
+ this.endSegment();
152
+ return i + separator;
153
+ }
154
+ if (char === ' ' || char === '\t') {
155
+ this.endWord();
156
+ return i + 1;
157
+ }
158
+ this.append(char);
159
+ return i + 1;
160
+ }
161
+ escaped(i) {
162
+ const next = this.text[i + 1];
163
+ if (next !== '\n')
164
+ this.append(next ?? '\\');
165
+ return i + 2;
166
+ }
167
+ singleQuoted(i) {
168
+ const close = this.text.indexOf("'", i + 1);
169
+ const end = close === -1 ? this.text.length : close;
170
+ this.append(this.text.slice(i + 1, end));
171
+ return end + 1;
172
+ }
173
+ doubleQuoted(i) {
174
+ let j = i + 1;
175
+ this.append('');
176
+ while (j < this.text.length && this.text[j] !== '"')
177
+ j = this.doubleQuotedStep(j);
178
+ return j + 1;
179
+ }
180
+ doubleQuotedStep(j) {
181
+ const char = this.text.charAt(j);
182
+ const next = this.text.charAt(j + 1);
183
+ if (char === '\\' && next === '\n')
184
+ return j + 2;
185
+ if (char === '\\' && DOUBLE_QUOTE_ESCAPES.has(next)) {
186
+ this.append(next);
187
+ return j + 2;
188
+ }
189
+ this.append(char);
190
+ return j + 1;
191
+ }
192
+ lineEnd(i) {
193
+ const newline = this.text.indexOf('\n', i);
194
+ return newline === -1 ? this.text.length : newline;
195
+ }
196
+ /** `i` is at the first `<` or `>`. */
197
+ redirection(i) {
198
+ if (this.word !== null && RE_FD_PREFIX.test(this.word))
199
+ this.word = null;
200
+ this.endWord();
201
+ let j = i + 1;
202
+ while (this.text[j] === '>' || this.text[j] === '<')
203
+ j += 1;
204
+ if (this.text[j] !== '&') {
205
+ this.dropNext = true;
206
+ return this.text[j] === '|' ? j + 1 : j;
207
+ }
208
+ const start = j + 1;
209
+ let end = start;
210
+ while (end < this.text.length && RE_DUPLICATION_CHAR.test(this.text.charAt(end)))
211
+ end += 1;
212
+ // `>&file` names a target the way `>file` does.
213
+ this.dropNext = end === start;
214
+ return end;
215
+ }
216
+ append(text) {
217
+ this.word = (this.word ?? '') + text;
218
+ }
219
+ endWord() {
220
+ const word = this.word;
221
+ if (word === null)
222
+ return;
223
+ this.word = null;
224
+ if (this.dropNext) {
225
+ this.dropNext = false;
226
+ return;
227
+ }
228
+ this.words.push(word);
229
+ }
230
+ endSegment() {
231
+ this.endWord();
232
+ this.dropNext = false;
233
+ if (this.words.length > 0)
234
+ this.done.push(this.words);
235
+ this.words = [];
236
+ }
237
+ }
238
+ /** How many characters a segment separator at this position spans; 0 when there is none. */
239
+ function separatorLength(char, next) {
240
+ if (char === '|' || char === '&')
241
+ return next === '|' || next === '&' ? 2 : 1;
242
+ return char === ';' || char === '\n' ? 1 : 0;
243
+ }
244
+ /** The first `max` code points, so no port cuts a surrogate pair: Python's `text[:max]`. */
245
+ function clampCodePoints(text, max) {
246
+ if (text.length <= max)
247
+ return text;
248
+ return Array.from(text).slice(0, max).join('');
249
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Names the rules in `tests/fixtures/command-vectors.json`, a byte copy of
3
+ * core's `packages/fingerprint/test/command-vectors.json`. Command digests
4
+ * from different schemes never compare.
5
+ */
6
+ export declare const COMMAND_SCHEME = "agent-watch-command/1";
7
+ /**
8
+ * A check is an allowlisted command that ran this long (workflow SPEC §12.1).
9
+ * The edge decides the flag, since only it holds the duration and the command
10
+ * together; core sees the flag alone.
11
+ */
12
+ export declare const CHECK_MIN_DURATION_MS = 60000;
13
+ /** Bounds the lexer's work on hostile input; core cuts at the same code point. */
14
+ export declare const MAX_COMMAND_CODE_POINTS = 16384;
15
+ /** `npm`, `pnpm` and `yarn` scripts that are checks, alone or as `name:variant` (`test:unit`). */
16
+ export declare const CHECK_SCRIPTS: ReadonlySet<string>;
17
+ export declare const CHECK_PROGRAMS: ReadonlySet<string>;
18
+ export declare const SCRIPT_RUNNERS: ReadonlySet<string>;
19
+ /** `go test`, `cargo test`, `make test`, `make check`: the first argument decides. */
20
+ export declare const SUBCOMMAND_CHECKS: ReadonlyMap<string, ReadonlySet<string>>;
21
+ /** The `npm run` words that name a script as their next argument. */
22
+ export declare const RUN_SCRIPT_WORDS: ReadonlySet<string>;
23
+ /** Inside `"…"`, a backslash escapes only these. */
24
+ export declare const DOUBLE_QUOTE_ESCAPES: ReadonlySet<string>;
25
+ /** Shells whose `-c` / `-lc` script is the command an argv runs. */
26
+ export declare const SHELL_WRAPPERS: ReadonlySet<string>;
27
+ export declare const SHELL_SCRIPT_FLAGS: ReadonlySet<string>;
28
+ export declare const RE_ASSIGNMENT: RegExp;
29
+ export declare const RE_FD_PREFIX: RegExp;
30
+ export declare const RE_PYTHON: RegExp;
31
+ /** What may follow `>&` in a duplication (`2>&1`, `>&-`). */
32
+ export declare const RE_DUPLICATION_CHAR: RegExp;
33
+ /** A script's `:variant` suffix (`test:unit`). */
34
+ export declare const RE_SCRIPT_VARIANT: RegExp;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Names the rules in `tests/fixtures/command-vectors.json`, a byte copy of
3
+ * core's `packages/fingerprint/test/command-vectors.json`. Command digests
4
+ * from different schemes never compare.
5
+ */
6
+ export const COMMAND_SCHEME = 'agent-watch-command/1';
7
+ /**
8
+ * A check is an allowlisted command that ran this long (workflow SPEC §12.1).
9
+ * The edge decides the flag, since only it holds the duration and the command
10
+ * together; core sees the flag alone.
11
+ */
12
+ export const CHECK_MIN_DURATION_MS = 60_000;
13
+ /** Bounds the lexer's work on hostile input; core cuts at the same code point. */
14
+ export const MAX_COMMAND_CODE_POINTS = 16_384;
15
+ /** `npm`, `pnpm` and `yarn` scripts that are checks, alone or as `name:variant` (`test:unit`). */
16
+ export const CHECK_SCRIPTS = new Set(['test', 'verify', 'lint', 'typecheck', 'check', 'build']);
17
+ export const CHECK_PROGRAMS = new Set(['vitest', 'jest', 'tsc', 'pytest', 'pr-tests.sh']);
18
+ export const SCRIPT_RUNNERS = new Set(['npm', 'pnpm', 'yarn']);
19
+ /** `go test`, `cargo test`, `make test`, `make check`: the first argument decides. */
20
+ export const SUBCOMMAND_CHECKS = new Map([
21
+ ['go', new Set(['test'])],
22
+ ['cargo', new Set(['test'])],
23
+ ['make', new Set(['test', 'check'])]
24
+ ]);
25
+ /** The `npm run` words that name a script as their next argument. */
26
+ export const RUN_SCRIPT_WORDS = new Set(['run', 'run-script']);
27
+ /** Inside `"…"`, a backslash escapes only these. */
28
+ export const DOUBLE_QUOTE_ESCAPES = new Set(['"', '\\', '$', '`']);
29
+ /** Shells whose `-c` / `-lc` script is the command an argv runs. */
30
+ export const SHELL_WRAPPERS = new Set(['bash', 'sh', 'zsh']);
31
+ export const SHELL_SCRIPT_FLAGS = new Set(['-c', '-lc']);
32
+ export const RE_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
33
+ export const RE_FD_PREFIX = /^\d+$/;
34
+ export const RE_PYTHON = /^python[0-9.]*$/;
35
+ /** What may follow `>&` in a duplication (`2>&1`, `>&-`). */
36
+ export const RE_DUPLICATION_CHAR = /[0-9-]/;
37
+ /** A script's `:variant` suffix (`test:unit`). */
38
+ export const RE_SCRIPT_VARIANT = /:.*/s;