@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.
- package/CHANGELOG.md +75 -0
- package/README.md +10 -6
- package/SECURITY.md +7 -4
- package/dist/cli/constants/cli.constants.d.ts +2 -0
- package/dist/cli/constants/cli.constants.js +3 -1
- package/dist/cli/doctor.js +13 -2
- package/dist/cli/setup.js +138 -29
- package/dist/cli/toggle.js +5 -1
- package/dist/cli/types/cli.types.d.ts +6 -0
- package/dist/cli/uninstall.js +1 -1
- package/dist/cli.js +14 -3
- package/dist/config/config-store.d.ts +1 -1
- package/dist/config/config-store.js +2 -2
- package/dist/config/constants/config.constants.d.ts +4 -1
- package/dist/config/constants/config.constants.js +7 -2
- package/dist/config/repo-config.js +1 -1
- package/dist/config/schemas/config.schema.d.ts +113 -767
- package/dist/config/schemas/config.schema.js +17 -8
- package/dist/credentials/constants/credentials.constants.d.ts +8 -0
- package/dist/credentials/constants/credentials.constants.js +9 -1
- package/dist/credentials/credential-status.js +8 -4
- package/dist/credentials/credentials.d.ts +16 -2
- package/dist/credentials/credentials.js +30 -5
- package/dist/credentials/device-api.d.ts +10 -1
- package/dist/credentials/device-api.js +12 -1
- package/dist/credentials/identity.d.ts +12 -1
- package/dist/credentials/identity.js +12 -1
- package/dist/credentials/migration.d.ts +1 -1
- package/dist/credentials/migration.js +1 -1
- package/dist/credentials/schemas/device-api.schema.d.ts +4 -51
- package/dist/credentials/schemas/device-state.schema.d.ts +3 -38
- package/dist/credentials/sign-in.d.ts +14 -1
- package/dist/credentials/sign-in.js +24 -5
- package/dist/credentials/types/credentials.types.d.ts +12 -1
- package/dist/enforcement/decision-client.js +2 -1
- package/dist/enforcement/enforcement.js +7 -5
- package/dist/enforcement/types/enforcement.types.d.ts +2 -2
- package/dist/git/code-state.d.ts +33 -0
- package/dist/git/code-state.js +44 -0
- package/dist/git/constants/git.constants.d.ts +6 -0
- package/dist/git/constants/git.constants.js +6 -0
- package/dist/git/index.d.ts +2 -1
- package/dist/git/index.js +1 -0
- package/dist/git/types/git.types.d.ts +6 -0
- package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
- package/dist/pipeline/constants/pipeline.constants.js +3 -0
- package/dist/pipeline/hook-pipeline.js +56 -7
- package/dist/privacy/command-fingerprint.d.ts +42 -0
- package/dist/privacy/command-fingerprint.js +249 -0
- package/dist/privacy/constants/command-fingerprint.constants.d.ts +34 -0
- package/dist/privacy/constants/command-fingerprint.constants.js +38 -0
- package/dist/privacy/index.d.ts +3 -1
- package/dist/privacy/index.js +2 -0
- package/dist/privacy/product-capture.js +20 -0
- package/dist/privacy/types/privacy.types.d.ts +7 -0
- package/dist/providers/antigravity/antigravity.adapter.js +3 -0
- package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +18 -492
- package/dist/providers/claude/claude.adapter.js +12 -1
- package/dist/providers/claude/constants/claude.constants.d.ts +6 -0
- package/dist/providers/claude/constants/claude.constants.js +6 -0
- package/dist/providers/claude/schemas/claude.schema.d.ts +1 -43
- package/dist/providers/codex/codex.adapter.js +14 -0
- package/dist/providers/codex/codex.otel.d.ts +12 -1
- package/dist/providers/codex/codex.otel.js +61 -11
- package/dist/providers/codex/constants/codex.otel.constants.d.ts +5 -0
- package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
- package/dist/providers/codex/schemas/codex.schema.d.ts +1 -41
- package/dist/providers/constants/provider.constants.d.ts +8 -0
- package/dist/providers/constants/provider.constants.js +8 -0
- package/dist/providers/cursor/constants/cursor.constants.d.ts +2 -0
- package/dist/providers/cursor/constants/cursor.constants.js +2 -0
- package/dist/providers/cursor/cursor.adapter.js +84 -5
- package/dist/providers/cursor/schemas/cursor.schema.d.ts +5 -85
- package/dist/providers/gemini/constants/gemini.constants.d.ts +2 -0
- package/dist/providers/gemini/constants/gemini.constants.js +2 -0
- package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +16 -1
- package/dist/providers/gemini/constants/gemini.otel.constants.js +16 -1
- package/dist/providers/gemini/gemini.detect.d.ts +11 -0
- package/dist/providers/gemini/gemini.detect.js +14 -1
- package/dist/providers/gemini/gemini.hooks.d.ts +3 -3
- package/dist/providers/gemini/gemini.hooks.js +5 -5
- package/dist/providers/gemini/gemini.otel.d.ts +14 -4
- package/dist/providers/gemini/gemini.otel.js +418 -107
- package/dist/providers/gemini/schemas/gemini.schema.d.ts +1 -49
- package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
- package/dist/providers/shared/bearer-rewrite.js +46 -0
- package/dist/providers/shared/constants/tooling.constants.d.ts +6 -0
- package/dist/providers/shared/constants/tooling.constants.js +6 -0
- package/dist/providers/shared/event-builder.d.ts +17 -2
- package/dist/providers/shared/event-builder.js +43 -3
- package/dist/providers/shared/install-record.d.ts +2 -0
- package/dist/providers/shared/install-record.js +3 -2
- package/dist/providers/shared/tooling.d.ts +35 -0
- package/dist/providers/shared/tooling.js +61 -1
- package/dist/providers/shared/types/adapter.types.d.ts +18 -0
- package/dist/providers/types/provider.types.d.ts +24 -0
- package/dist/storage/atomic-file.d.ts +14 -0
- package/dist/storage/atomic-file.js +19 -0
- package/dist/storage/constants/storage.constants.d.ts +2 -0
- package/dist/storage/constants/storage.constants.js +2 -0
- package/dist/storage/schemas/storage.schema.d.ts +11 -175
- package/dist/storage/schemas/storage.schema.js +7 -1
- package/dist/transport/schemas/queue.schema.d.ts +1 -16
- package/dist/transport/schemas/queue.schema.js +1 -1
- package/dist/turns/constants/turns.constants.d.ts +17 -0
- package/dist/turns/constants/turns.constants.js +17 -0
- package/dist/turns/index.d.ts +3 -2
- package/dist/turns/index.js +1 -0
- package/dist/turns/tool-events.d.ts +15 -0
- package/dist/turns/tool-events.js +59 -0
- package/dist/turns/turn-state.js +2 -2
- package/dist/turns/turn-summary.d.ts +1 -1
- package/dist/turns/turn-summary.js +1 -0
- package/dist/turns/turn-tracker.js +138 -7
- package/dist/turns/types/turn-state.types.d.ts +28 -1
- package/dist/turns/types/turn-summary.types.d.ts +30 -0
- package/dist/turns/types/turn-tracker.types.d.ts +10 -0
- package/dist/turns/work-checkout.d.ts +5 -3
- package/dist/turns/work-checkout.js +46 -12
- package/docs/AUDIT_PROMPT.md +11 -0
- package/docs/DATA_HANDLING.md +69 -14
- package/docs/ENTERPRISE_DEPLOYMENT.md +21 -5
- package/package.json +9 -8
|
@@ -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
|
|
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
|
-
|
|
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
|
|
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;
|
|
@@ -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
|
/**
|
package/dist/git/index.d.ts
CHANGED
|
@@ -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
|
+
}
|
|
@@ -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,
|
|
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
|
|
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
|
*
|
|
@@ -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
|
+
}
|