@eserstack/agents 0.0.0-stage → 5.0.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/LICENSE +13 -0
- package/README.md +163 -2
- package/dist/adapter.d.ts +71 -0
- package/dist/adapter.js +75 -0
- package/dist/adapters/claude-code.d.ts +3 -0
- package/dist/adapters/claude-code.js +14 -0
- package/dist/adapters/codex.d.ts +3 -0
- package/dist/adapters/codex.js +13 -0
- package/dist/adapters/opencode.d.ts +3 -0
- package/dist/adapters/opencode.js +13 -0
- package/dist/guards/git.d.ts +110 -0
- package/dist/guards/git.js +527 -0
- package/dist/mod.d.ts +22 -0
- package/dist/mod.js +7 -0
- package/dist/registry.d.ts +13 -0
- package/dist/registry.js +15 -0
- package/package.json +40 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2023-present Eser Ozvataf and other contributors.
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,164 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 🤖 [@eserstack/agents](./)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/agents` is published
|
|
4
|
+
> on npm under the same name (`pnpm add @eserstack/agents`); the JSR versions
|
|
5
|
+
> stay available but get no updates.
|
|
6
|
+
|
|
7
|
+
`@eserstack/agents` finds interactive coding agents (Claude Code, OpenCode,
|
|
8
|
+
Codex) on `PATH` and builds the spec to launch one in a terminal pane. It also
|
|
9
|
+
holds the read-only git guard: pure predicates that decide whether a shell
|
|
10
|
+
command only reads git state or writes to the repository, including writes
|
|
11
|
+
hidden in subshells, pipes and scripts. `@eserstack/mux` owns the panes and
|
|
12
|
+
PTYs, and noskills uses the guard in its PreToolUse hook.
|
|
13
|
+
|
|
14
|
+
The package does not read an agent's state from its terminal output. An agent
|
|
15
|
+
reports its state itself through ACP `session/update` events.
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
Look up an adapter and build the spawn spec for it:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import * as agents from "@eserstack/agents";
|
|
23
|
+
|
|
24
|
+
const adapter =
|
|
25
|
+
agents.getAgentAdapter("claude-code") ?? agents.defaultAgentAdapter();
|
|
26
|
+
const spec = await adapter.buildSpawnSpec({
|
|
27
|
+
cwd: "your_project_dir",
|
|
28
|
+
cols: 120,
|
|
29
|
+
rows: 40,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
if (spec === null) {
|
|
33
|
+
console.log(`${adapter.displayName} is not installed`);
|
|
34
|
+
} else {
|
|
35
|
+
console.log(spec.command, spec.args); // "claude" []
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`buildSpawnSpec` returns `null` when none of the adapter's binaries is on
|
|
40
|
+
`PATH`.
|
|
41
|
+
|
|
42
|
+
## Adapters
|
|
43
|
+
|
|
44
|
+
An `AgentAdapter` has an `id`, a `displayName`, `capabilities`, and two
|
|
45
|
+
functions:
|
|
46
|
+
|
|
47
|
+
- `resolveCommand()` returns the first binary found on `PATH`, or `null`.
|
|
48
|
+
- `buildSpawnSpec(ctx)` returns `{ command, args, env, cwd }`, or `null` when
|
|
49
|
+
the binary is missing. `env` merges `ctx.baseEnv` and `ctx.extraEnv`, with
|
|
50
|
+
`extraEnv` winning.
|
|
51
|
+
|
|
52
|
+
A found binary is cached for the adapter's lifetime. A miss is not cached, so a
|
|
53
|
+
long-running process picks up an agent installed after the first lookup.
|
|
54
|
+
|
|
55
|
+
| Adapter | `id` | Binaries tried |
|
|
56
|
+
| -------------------------- | ------------- | ----------------------- |
|
|
57
|
+
| `agents.claudeCodeAdapter` | `claude-code` | `claude`, `claude-code` |
|
|
58
|
+
| `agents.opencodeAdapter` | `opencode` | `opencode` |
|
|
59
|
+
| `agents.codexAdapter` | `codex` | `codex` |
|
|
60
|
+
|
|
61
|
+
The registry lists them in that order:
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
import * as agents from "@eserstack/agents";
|
|
65
|
+
|
|
66
|
+
agents.listAgentAdapters().map((a) => a.id); // ["claude-code", "opencode", "codex"]
|
|
67
|
+
agents.getAgentAdapter("codex"); // the Codex adapter, or undefined for an unknown id
|
|
68
|
+
agents.defaultAgentAdapter(); // the Claude Code adapter
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Your own adapter
|
|
72
|
+
|
|
73
|
+
`createCliAgentAdapter` builds an adapter for any CLI agent from its binary
|
|
74
|
+
names, tried in order:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import * as agents from "@eserstack/agents";
|
|
78
|
+
|
|
79
|
+
const aider = agents.createCliAgentAdapter({
|
|
80
|
+
id: "aider",
|
|
81
|
+
displayName: "Aider",
|
|
82
|
+
candidates: ["aider"],
|
|
83
|
+
capabilities: { supportsBracketedPaste: false },
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const command = await aider.resolveCommand(); // "aider", or null
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`capabilities.supportsBracketedPaste` defaults to `true`.
|
|
90
|
+
|
|
91
|
+
### Binary discovery
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
import * as agents from "@eserstack/agents";
|
|
95
|
+
|
|
96
|
+
await agents.isOnPath("git"); // true when `which git` (`where` on Windows) succeeds
|
|
97
|
+
await agents.resolveFirstOnPath(["claude", "claude-code"]); // first hit, or null
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Git Guard
|
|
101
|
+
|
|
102
|
+
`agents.gitGuard` decides whether a shell command only reads git state. Every
|
|
103
|
+
function is pure: it inspects the command text and does no I/O.
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
import * as agents from "@eserstack/agents";
|
|
107
|
+
|
|
108
|
+
agents.gitGuard.isGitAllowed("git log --oneline"); // true
|
|
109
|
+
agents.gitGuard.isGitAllowed("git push origin main"); // false
|
|
110
|
+
agents.gitGuard.isGitAllowed("ls -la"); // true: the guard only governs git
|
|
111
|
+
|
|
112
|
+
agents.gitGuard.hasGitWrite("bash -c 'git push origin main'"); // true
|
|
113
|
+
agents.gitGuard.extractGitInvocations("git status && git commit -m wip");
|
|
114
|
+
// ["git status", "git commit -m wip"]
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
| Function | What it answers |
|
|
118
|
+
| --------------------------------- | -------------------------------------------------------------------------------- |
|
|
119
|
+
| `isGitAllowed(command)` | Is this single command segment a read-only git command (or not git at all)? |
|
|
120
|
+
| `isGitReadOnly(command)` | Alias of `isGitAllowed`, kept for older callers |
|
|
121
|
+
| `extractGitInvocations(command)` | Every `git ...` fragment in chains, multi-line scripts, `$(...)` and backticks |
|
|
122
|
+
| `containsGitWriteBypass(command)` | Does a subshell, `eval`, pipe or command substitution carry a git write? |
|
|
123
|
+
| `hasGitWrite(command)` | Does the command perform or smuggle any git write? |
|
|
124
|
+
| `feedsShellFromStdin(command)` | Does a shell in the command read its script from stdin or a heredoc? |
|
|
125
|
+
| `shellScriptTargets(command)` | Which script files the command runs (`sh run.sh`, `source x.sh`) |
|
|
126
|
+
| `writesFile(command, path)` | Does the command itself write `path` (`> path`, `>> path`, `tee path`)? |
|
|
127
|
+
| `stripFlagValues(command)` | The command with quoted flag values removed, so `--answer="use git"` is not read |
|
|
128
|
+
|
|
129
|
+
The guard classifies text. It cannot tell what a program assembles at run time,
|
|
130
|
+
for example `python -c` building `git push` from parts, so treat it as one layer
|
|
131
|
+
of a read-only policy rather than the whole of it.
|
|
132
|
+
|
|
133
|
+
A wrapper that sits in front of the git binary sees the actual arguments
|
|
134
|
+
instead. These functions decide on that argument vector, without the program
|
|
135
|
+
name:
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
import * as agents from "@eserstack/agents";
|
|
139
|
+
|
|
140
|
+
agents.gitGuard.isGitArgsAllowed(["-C", "/repo", "log"]); // true
|
|
141
|
+
agents.gitGuard.isGitArgsAllowed(["commit", "-m", "wip"]); // false
|
|
142
|
+
agents.gitGuard.isGitRemoteWrite(["push", "origin", "main"]); // true
|
|
143
|
+
agents.gitGuard.splitGitArgs(["-C", "/repo", "commit", "-m", "wip"]);
|
|
144
|
+
// { globalOptions: ["-C", "/repo"], subcommand: "commit", subcommandArgs: ["-m", "wip"] }
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| Function | What it answers |
|
|
148
|
+
| ------------------------ | --------------------------------------------------------------------- |
|
|
149
|
+
| `isGitArgsAllowed(args)` | Does git, run with these arguments, only read repository state? |
|
|
150
|
+
| `isGitRemoteWrite(args)` | Does it send commits to another repository (`push`, `send-pack`)? |
|
|
151
|
+
| `splitGitArgs(args)` | The global options before the subcommand, the subcommand and its args |
|
|
152
|
+
|
|
153
|
+
The allowlists behind them are exported too (`GIT_ALLOWED_SUBCOMMANDS`,
|
|
154
|
+
`GIT_CONDITIONAL_READS`, the global option sets, `GIT_INFO_OPTIONS` and
|
|
155
|
+
`GIT_REMOTE_WRITE_SUBCOMMANDS`), so a wrapper script generated from them stays
|
|
156
|
+
in step with the guard. noskills builds its agent-session git wrapper this way.
|
|
157
|
+
|
|
158
|
+
## 🔗 Links
|
|
159
|
+
|
|
160
|
+
- [`@eserstack/noskills`](https://github.com/eser/stack/tree/main/pkg/@eserstack/noskills):
|
|
161
|
+
the orchestrator whose hooks use the git guard and whose manager launches
|
|
162
|
+
agents through these adapters
|
|
163
|
+
- [npm package](https://www.npmjs.com/package/@eserstack/agents)
|
|
164
|
+
- [eser/stack on GitHub](https://github.com/eser/stack)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** What the consumer knows about the pane an agent is launched in. */
|
|
2
|
+
export type SpawnContext = {
|
|
3
|
+
/** Directory the agent starts in. */
|
|
4
|
+
readonly cwd: string;
|
|
5
|
+
/** Pane width in character columns. */
|
|
6
|
+
readonly cols: number;
|
|
7
|
+
/** Pane height in character rows. */
|
|
8
|
+
readonly rows: number;
|
|
9
|
+
/** Environment the agent starts with, usually the consumer's own. */
|
|
10
|
+
readonly baseEnv?: Record<string, string>;
|
|
11
|
+
/**
|
|
12
|
+
* Variables added on top of `baseEnv` (for example session ids from the
|
|
13
|
+
* consumer). A key set in both takes this value.
|
|
14
|
+
*/
|
|
15
|
+
readonly extraEnv?: Record<string, string>;
|
|
16
|
+
};
|
|
17
|
+
/** How to launch an agent: the program, its arguments and environment. */
|
|
18
|
+
export type SpawnSpec = {
|
|
19
|
+
/** Binary name as found on PATH (for example "claude"). */
|
|
20
|
+
readonly command: string;
|
|
21
|
+
/** Arguments passed to the binary. */
|
|
22
|
+
readonly args: readonly string[];
|
|
23
|
+
/** Full environment for the process: `baseEnv` merged with `extraEnv`. */
|
|
24
|
+
readonly env: Record<string, string>;
|
|
25
|
+
/** Directory to start the process in; when absent, the spawner picks one. */
|
|
26
|
+
readonly cwd?: string;
|
|
27
|
+
};
|
|
28
|
+
/** Terminal features an agent's TUI handles. */
|
|
29
|
+
export type AgentCapabilities = {
|
|
30
|
+
/**
|
|
31
|
+
* True if the agent accepts bracketed paste, so a multi-line paste arrives
|
|
32
|
+
* as one input instead of a key press per line.
|
|
33
|
+
*/
|
|
34
|
+
readonly supportsBracketedPaste: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** Finds an interactive coding agent on PATH and builds its spawn spec. */
|
|
37
|
+
export interface AgentAdapter {
|
|
38
|
+
/** Stable id used for lookup (for example "claude-code"). */
|
|
39
|
+
readonly id: string;
|
|
40
|
+
/** Name shown to people (for example "Claude Code"). */
|
|
41
|
+
readonly displayName: string;
|
|
42
|
+
/** Terminal features the agent handles. */
|
|
43
|
+
readonly capabilities: AgentCapabilities;
|
|
44
|
+
/** Resolve the binary on PATH; null when not installed. */
|
|
45
|
+
resolveCommand(): Promise<string | null>;
|
|
46
|
+
/** Full spawn spec, or null when the binary isn't found. */
|
|
47
|
+
buildSpawnSpec(ctx: SpawnContext): Promise<SpawnSpec | null>;
|
|
48
|
+
}
|
|
49
|
+
/** True if `name` resolves on PATH (cross-platform `which`/`where`). */
|
|
50
|
+
export declare const isOnPath: (name: string) => Promise<boolean>;
|
|
51
|
+
/** Return the first candidate found on PATH, or null. */
|
|
52
|
+
export declare const resolveFirstOnPath: (candidates: readonly string[]) => Promise<string | null>;
|
|
53
|
+
/** Options for {@link createCliAgentAdapter}. */
|
|
54
|
+
export type CliAdapterOptions = {
|
|
55
|
+
/** Stable id used for lookup (for example "aider"). */
|
|
56
|
+
readonly id: string;
|
|
57
|
+
/** Name shown to people (for example "Aider"). */
|
|
58
|
+
readonly displayName: string;
|
|
59
|
+
/** PATH candidates, tried in order (e.g. ["claude", "claude-code"]). */
|
|
60
|
+
readonly candidates: readonly string[];
|
|
61
|
+
/**
|
|
62
|
+
* Capabilities that differ from the defaults; every capability not given
|
|
63
|
+
* here is true.
|
|
64
|
+
*/
|
|
65
|
+
readonly capabilities?: Partial<AgentCapabilities>;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Build an adapter for an interactive CLI agent. The built-in adapters are thin
|
|
69
|
+
* configs over this.
|
|
70
|
+
*/
|
|
71
|
+
export declare const createCliAgentAdapter: (opts: CliAdapterOptions) => AgentAdapter;
|
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* The runtime agent-adapter abstraction: how to discover and launch an
|
|
4
|
+
* interactive coding agent in a pane.
|
|
5
|
+
*
|
|
6
|
+
* It used to read agent state as well, by matching regexes against the last ten
|
|
7
|
+
* rows of the terminal. That is gone: agent state now arrives as ACP
|
|
8
|
+
* session/update events, which the agent reports about itself rather than being
|
|
9
|
+
* inferred from how its TUI happens to render this week. What remains here is
|
|
10
|
+
* binary discovery and spawning, which a terminal pane genuinely needs.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import * as exec from "@eserstack/shell/exec";
|
|
15
|
+
import * as crossRuntime from "@eserstack/standards/cross-runtime";
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Binary discovery
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
/** True if `name` resolves on PATH (cross-platform `which`/`where`). */
|
|
20
|
+
export const isOnPath = async (name) => {
|
|
21
|
+
const probe = crossRuntime.getPlatform() === "windows" ? "where" : "which";
|
|
22
|
+
try {
|
|
23
|
+
const code = await exec.exec `${probe} ${name}`.noThrow().code();
|
|
24
|
+
return code === 0;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/** Return the first candidate found on PATH, or null. */
|
|
31
|
+
export const resolveFirstOnPath = async (candidates) => {
|
|
32
|
+
for (const name of candidates) {
|
|
33
|
+
// Candidates are probed in priority order and the first hit wins, so later
|
|
34
|
+
// candidates are not spawned once one resolves.
|
|
35
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
36
|
+
if (await isOnPath(name))
|
|
37
|
+
return name;
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Build an adapter for an interactive CLI agent. The built-in adapters are thin
|
|
43
|
+
* configs over this.
|
|
44
|
+
*/
|
|
45
|
+
export const createCliAgentAdapter = (opts) => {
|
|
46
|
+
// Cache only a positive result: a "not found" is re-probed so a binary
|
|
47
|
+
// installed after the first lookup is picked up by a long-lived process.
|
|
48
|
+
let cached = null;
|
|
49
|
+
const resolveCommand = async () => {
|
|
50
|
+
if (cached !== null)
|
|
51
|
+
return cached;
|
|
52
|
+
cached = await resolveFirstOnPath(opts.candidates);
|
|
53
|
+
return cached;
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
id: opts.id,
|
|
57
|
+
displayName: opts.displayName,
|
|
58
|
+
capabilities: {
|
|
59
|
+
supportsBracketedPaste: true,
|
|
60
|
+
...opts.capabilities,
|
|
61
|
+
},
|
|
62
|
+
resolveCommand,
|
|
63
|
+
async buildSpawnSpec(ctx) {
|
|
64
|
+
const command = await resolveCommand();
|
|
65
|
+
if (command === null)
|
|
66
|
+
return null;
|
|
67
|
+
return {
|
|
68
|
+
command,
|
|
69
|
+
args: [],
|
|
70
|
+
env: { ...ctx.baseEnv, ...ctx.extraEnv },
|
|
71
|
+
cwd: ctx.cwd,
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code adapter — ports the discovery the noskills manager used
|
|
4
|
+
* (`which claude || which claude-code`).
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import * as adapter from "../adapter.js";
|
|
9
|
+
/** Adapter for Claude Code: looks for `claude`, then `claude-code` on PATH. */
|
|
10
|
+
export const claudeCodeAdapter = adapter.createCliAgentAdapter({
|
|
11
|
+
id: "claude-code",
|
|
12
|
+
displayName: "Claude Code",
|
|
13
|
+
candidates: ["claude", "claude-code"],
|
|
14
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Codex adapter — binary discovery only.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import * as adapter from "../adapter.js";
|
|
8
|
+
/** Adapter for Codex: looks for `codex` on PATH. */
|
|
9
|
+
export const codexAdapter = adapter.createCliAgentAdapter({
|
|
10
|
+
id: "codex",
|
|
11
|
+
displayName: "Codex",
|
|
12
|
+
candidates: ["codex"],
|
|
13
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* OpenCode adapter — binary discovery only.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import * as adapter from "../adapter.js";
|
|
8
|
+
/** Adapter for OpenCode: looks for `opencode` on PATH. */
|
|
9
|
+
export const opencodeAdapter = adapter.createCliAgentAdapter({
|
|
10
|
+
id: "opencode",
|
|
11
|
+
displayName: "OpenCode",
|
|
12
|
+
candidates: ["opencode"],
|
|
13
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure git-guard predicates: decide whether a shell command only READS git
|
|
3
|
+
* state, and detect write operations smuggled through subshells/pipes.
|
|
4
|
+
*
|
|
5
|
+
* This is the canonical copy: noskills re-exports these predicates for its
|
|
6
|
+
* PreToolUse hook, so the hook and this package share one allowlist.
|
|
7
|
+
*
|
|
8
|
+
* Each predicate is side-effect free and checks a single command segment unless
|
|
9
|
+
* noted; callers split on `&&`/`;`/`|` or use {@link extractGitInvocations}.
|
|
10
|
+
* {@link isGitArgsAllowed} decides on the argument vector git actually
|
|
11
|
+
* receives, for a wrapper that sits in front of the git binary.
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
/** Subcommands that only read repository state, whatever their arguments. */
|
|
16
|
+
export declare const GIT_ALLOWED_SUBCOMMANDS: ReadonlySet<string>;
|
|
17
|
+
/**
|
|
18
|
+
* Subcommands that read only when their first argument is one of the listed
|
|
19
|
+
* values. The empty string stands for no argument at all (`git branch`).
|
|
20
|
+
*/
|
|
21
|
+
export declare const GIT_CONDITIONAL_READS: ReadonlyMap<string, ReadonlySet<string>>;
|
|
22
|
+
/**
|
|
23
|
+
* Options before the subcommand that take a value: as the next argument
|
|
24
|
+
* (`-C dir`), or after `=` for the long ones (`--git-dir=dir`).
|
|
25
|
+
*/
|
|
26
|
+
export declare const GIT_GLOBAL_FLAGS_WITH_ARG: ReadonlySet<string>;
|
|
27
|
+
/**
|
|
28
|
+
* Long options before the subcommand that take their value only after `=`.
|
|
29
|
+
* Without a value, `--exec-path` prints the path and exits, so it is listed
|
|
30
|
+
* in {@link GIT_INFO_OPTIONS} as well.
|
|
31
|
+
*/
|
|
32
|
+
export declare const GIT_GLOBAL_FLAGS_INLINE_ARG: ReadonlySet<string>;
|
|
33
|
+
/** Options before the subcommand that take no value. */
|
|
34
|
+
export declare const GIT_GLOBAL_FLAGS_NO_ARG: ReadonlySet<string>;
|
|
35
|
+
/**
|
|
36
|
+
* Options that take the place of a subcommand: git prints something and exits
|
|
37
|
+
* (`git --version`, `git --help`).
|
|
38
|
+
*/
|
|
39
|
+
export declare const GIT_INFO_OPTIONS: ReadonlySet<string>;
|
|
40
|
+
/**
|
|
41
|
+
* Subcommands that send commits to another repository. A push reaches the
|
|
42
|
+
* project's remote from any clone, so callers that scope writes to one
|
|
43
|
+
* repository still refuse these everywhere.
|
|
44
|
+
*/
|
|
45
|
+
export declare const GIT_REMOTE_WRITE_SUBCOMMANDS: ReadonlySet<string>;
|
|
46
|
+
/**
|
|
47
|
+
* True if a single git command segment is read-only (allowed). Non-git commands
|
|
48
|
+
* return true (the guard only governs git). Handles path-prefixed invocations
|
|
49
|
+
* (`/usr/bin/git`, `./git`, `git.exe`) and a word boundary so look-alikes like
|
|
50
|
+
* `github-cli` / `git-lfs` are not misparsed as git subcommands.
|
|
51
|
+
*/
|
|
52
|
+
export declare const isGitAllowed: (command: string) => boolean;
|
|
53
|
+
/** A git argument vector split at its subcommand. */
|
|
54
|
+
export type GitArgs = {
|
|
55
|
+
/** The options before the subcommand (`-C dir`, `--git-dir=x`). */
|
|
56
|
+
readonly globalOptions: readonly string[];
|
|
57
|
+
/** The subcommand, or `""` when there is none (bare `git`). */
|
|
58
|
+
readonly subcommand: string;
|
|
59
|
+
/** Everything after the subcommand. */
|
|
60
|
+
readonly subcommandArgs: readonly string[];
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Splits the arguments git receives (without the program name) into the
|
|
64
|
+
* global options, the subcommand and its arguments. An option git prints and
|
|
65
|
+
* exits on (`--version`) stands in the subcommand's place.
|
|
66
|
+
*/
|
|
67
|
+
export declare const splitGitArgs: (args: readonly string[]) => GitArgs;
|
|
68
|
+
/**
|
|
69
|
+
* True if git, run with these arguments (without the program name), only
|
|
70
|
+
* reads repository state. Decides on the argument vector itself, so it holds
|
|
71
|
+
* for a program an interpreter assembled at run time as well as for typed
|
|
72
|
+
* commands.
|
|
73
|
+
*/
|
|
74
|
+
export declare const isGitArgsAllowed: (args: readonly string[]) => boolean;
|
|
75
|
+
/** True if git, run with these arguments, sends commits to another repository. */
|
|
76
|
+
export declare const isGitRemoteWrite: (args: readonly string[]) => boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Backward-compatible alias of {@link isGitAllowed}: true if a single git
|
|
79
|
+
* command segment only reads repository state.
|
|
80
|
+
*/
|
|
81
|
+
export declare const isGitReadOnly: (command: string) => boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Extract every `git <subcommand> …` fragment from a command string, handling
|
|
84
|
+
* multi-line scripts, `&&`/`||`/`;` chains, `$(git …)`, and backticks.
|
|
85
|
+
*/
|
|
86
|
+
export declare const extractGitInvocations: (command: string) => readonly string[];
|
|
87
|
+
/**
|
|
88
|
+
* True if a command smuggles a git WRITE through a subshell (`bash -c …`),
|
|
89
|
+
* `eval`, pipe chain, or command substitution. Complements {@link isGitAllowed}.
|
|
90
|
+
*/
|
|
91
|
+
export declare const containsGitWriteBypass: (command: string) => boolean;
|
|
92
|
+
/** True if a shell in the command takes its script from stdin or a heredoc. */
|
|
93
|
+
export declare const feedsShellFromStdin: (command: string) => boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Script files a command runs through a shell (`sh run.sh`, `bash -e x.sh`,
|
|
96
|
+
* `source x.sh`, `. x.sh`). The caller can read them; their content is not in
|
|
97
|
+
* the command text.
|
|
98
|
+
*/
|
|
99
|
+
export declare const shellScriptTargets: (command: string) => readonly string[];
|
|
100
|
+
/** True if the command itself writes `path` (`> path`, `>> path`, `tee path`). */
|
|
101
|
+
export declare const writesFile: (command: string, path: string) => boolean;
|
|
102
|
+
/**
|
|
103
|
+
* Strip quoted flag values so user-provided text (e.g. `--answer="use git"`)
|
|
104
|
+
* isn't scanned as a command.
|
|
105
|
+
*/
|
|
106
|
+
export declare const stripFlagValues: (command: string) => string;
|
|
107
|
+
/**
|
|
108
|
+
* Convenience: true if `command` performs (or smuggles) any git write.
|
|
109
|
+
*/
|
|
110
|
+
export declare const hasGitWrite: (command: string) => boolean;
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Pure git-guard predicates: decide whether a shell command only READS git
|
|
4
|
+
* state, and detect write operations smuggled through subshells/pipes.
|
|
5
|
+
*
|
|
6
|
+
* This is the canonical copy: noskills re-exports these predicates for its
|
|
7
|
+
* PreToolUse hook, so the hook and this package share one allowlist.
|
|
8
|
+
*
|
|
9
|
+
* Each predicate is side-effect free and checks a single command segment unless
|
|
10
|
+
* noted; callers split on `&&`/`;`/`|` or use {@link extractGitInvocations}.
|
|
11
|
+
* {@link isGitArgsAllowed} decides on the argument vector git actually
|
|
12
|
+
* receives, for a wrapper that sits in front of the git binary.
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
/** Subcommands that only read repository state, whatever their arguments. */
|
|
17
|
+
export const GIT_ALLOWED_SUBCOMMANDS = new Set([
|
|
18
|
+
"log",
|
|
19
|
+
"diff",
|
|
20
|
+
"status",
|
|
21
|
+
"show",
|
|
22
|
+
"blame",
|
|
23
|
+
"rev-parse",
|
|
24
|
+
"ls-files",
|
|
25
|
+
"ls-tree",
|
|
26
|
+
"cat-file",
|
|
27
|
+
"describe",
|
|
28
|
+
"shortlog",
|
|
29
|
+
"name-rev",
|
|
30
|
+
"for-each-ref",
|
|
31
|
+
"rev-list",
|
|
32
|
+
"help",
|
|
33
|
+
"version",
|
|
34
|
+
]);
|
|
35
|
+
/**
|
|
36
|
+
* Subcommands that read only when their first argument is one of the listed
|
|
37
|
+
* values. The empty string stands for no argument at all (`git branch`).
|
|
38
|
+
*/
|
|
39
|
+
export const GIT_CONDITIONAL_READS = new Map([
|
|
40
|
+
[
|
|
41
|
+
"branch",
|
|
42
|
+
new Set([
|
|
43
|
+
"",
|
|
44
|
+
"--list",
|
|
45
|
+
"-l",
|
|
46
|
+
"-a",
|
|
47
|
+
"--all",
|
|
48
|
+
"-r",
|
|
49
|
+
"--remotes",
|
|
50
|
+
"-v",
|
|
51
|
+
"--verbose",
|
|
52
|
+
"--contains",
|
|
53
|
+
"--no-contains",
|
|
54
|
+
"--merged",
|
|
55
|
+
"--no-merged",
|
|
56
|
+
"--show-current",
|
|
57
|
+
]),
|
|
58
|
+
],
|
|
59
|
+
["tag", new Set(["", "-l", "--list", "-v", "--verify", "-n"])],
|
|
60
|
+
["stash", new Set(["list", "show"])],
|
|
61
|
+
["remote", new Set(["", "-v", "--verbose", "show", "get-url"])],
|
|
62
|
+
["reflog", new Set(["", "show"])],
|
|
63
|
+
]);
|
|
64
|
+
/**
|
|
65
|
+
* Options before the subcommand that take a value: as the next argument
|
|
66
|
+
* (`-C dir`), or after `=` for the long ones (`--git-dir=dir`).
|
|
67
|
+
*/
|
|
68
|
+
export const GIT_GLOBAL_FLAGS_WITH_ARG = new Set([
|
|
69
|
+
"-C",
|
|
70
|
+
"-c",
|
|
71
|
+
"--git-dir",
|
|
72
|
+
"--work-tree",
|
|
73
|
+
"--namespace",
|
|
74
|
+
"--super-prefix",
|
|
75
|
+
"--config-env",
|
|
76
|
+
"--attr-source",
|
|
77
|
+
]);
|
|
78
|
+
/**
|
|
79
|
+
* Long options before the subcommand that take their value only after `=`.
|
|
80
|
+
* Without a value, `--exec-path` prints the path and exits, so it is listed
|
|
81
|
+
* in {@link GIT_INFO_OPTIONS} as well.
|
|
82
|
+
*/
|
|
83
|
+
export const GIT_GLOBAL_FLAGS_INLINE_ARG = new Set([
|
|
84
|
+
"--exec-path",
|
|
85
|
+
]);
|
|
86
|
+
/** Options before the subcommand that take no value. */
|
|
87
|
+
export const GIT_GLOBAL_FLAGS_NO_ARG = new Set([
|
|
88
|
+
"--no-replace-objects",
|
|
89
|
+
"--no-lazy-fetch",
|
|
90
|
+
"--no-advice",
|
|
91
|
+
"--bare",
|
|
92
|
+
"--no-optional-locks",
|
|
93
|
+
"--literal-pathspecs",
|
|
94
|
+
"--glob-pathspecs",
|
|
95
|
+
"--noglob-pathspecs",
|
|
96
|
+
"--icase-pathspecs",
|
|
97
|
+
"--no-pager",
|
|
98
|
+
"-P",
|
|
99
|
+
"--paginate",
|
|
100
|
+
"-p",
|
|
101
|
+
]);
|
|
102
|
+
/**
|
|
103
|
+
* Options that take the place of a subcommand: git prints something and exits
|
|
104
|
+
* (`git --version`, `git --help`).
|
|
105
|
+
*/
|
|
106
|
+
export const GIT_INFO_OPTIONS = new Set([
|
|
107
|
+
"--version",
|
|
108
|
+
"-v",
|
|
109
|
+
"--help",
|
|
110
|
+
"-h",
|
|
111
|
+
"--exec-path",
|
|
112
|
+
"--html-path",
|
|
113
|
+
"--man-path",
|
|
114
|
+
"--info-path",
|
|
115
|
+
]);
|
|
116
|
+
/**
|
|
117
|
+
* Subcommands that send commits to another repository. A push reaches the
|
|
118
|
+
* project's remote from any clone, so callers that scope writes to one
|
|
119
|
+
* repository still refuse these everywhere.
|
|
120
|
+
*/
|
|
121
|
+
export const GIT_REMOTE_WRITE_SUBCOMMANDS = new Set([
|
|
122
|
+
"push",
|
|
123
|
+
"send-pack",
|
|
124
|
+
]);
|
|
125
|
+
// `git config` is decided on all of its arguments, not the first one: a scope
|
|
126
|
+
// flag such as --global says where to look, not what to do, so
|
|
127
|
+
// `git config --global user.name x` is a write.
|
|
128
|
+
const GIT_CONFIG_READ_ACTIONS = new Set([
|
|
129
|
+
"--get",
|
|
130
|
+
"--get-all",
|
|
131
|
+
"--get-regexp",
|
|
132
|
+
"--get-urlmatch",
|
|
133
|
+
"--get-color",
|
|
134
|
+
"--get-colorbool",
|
|
135
|
+
"--list",
|
|
136
|
+
"-l",
|
|
137
|
+
]);
|
|
138
|
+
const GIT_CONFIG_READ_SUBCOMMANDS = new Set([
|
|
139
|
+
"get",
|
|
140
|
+
"list",
|
|
141
|
+
]);
|
|
142
|
+
// Flags that only narrow where config is read from or how it is printed.
|
|
143
|
+
const GIT_CONFIG_NEUTRAL_FLAGS = new Set([
|
|
144
|
+
"--global",
|
|
145
|
+
"--local",
|
|
146
|
+
"--system",
|
|
147
|
+
"--worktree",
|
|
148
|
+
"--show-origin",
|
|
149
|
+
"--show-scope",
|
|
150
|
+
"--name-only",
|
|
151
|
+
"--null",
|
|
152
|
+
"-z",
|
|
153
|
+
"--includes",
|
|
154
|
+
"--no-includes",
|
|
155
|
+
"--bool",
|
|
156
|
+
"--int",
|
|
157
|
+
"--bool-or-int",
|
|
158
|
+
"--path",
|
|
159
|
+
"--expiry-date",
|
|
160
|
+
"--no-type",
|
|
161
|
+
"--fixed-value",
|
|
162
|
+
"--all",
|
|
163
|
+
]);
|
|
164
|
+
const GIT_CONFIG_FLAGS_WITH_ARG = new Set([
|
|
165
|
+
"--file",
|
|
166
|
+
"-f",
|
|
167
|
+
"--blob",
|
|
168
|
+
"--type",
|
|
169
|
+
"--default",
|
|
170
|
+
"--url",
|
|
171
|
+
]);
|
|
172
|
+
/** True if the arguments after `git config` only read configuration. */
|
|
173
|
+
const isGitConfigRead = (args) => {
|
|
174
|
+
let readAction = false;
|
|
175
|
+
const positionals = [];
|
|
176
|
+
for (let i = 0; i < args.length; i++) {
|
|
177
|
+
const arg = args[i];
|
|
178
|
+
if (GIT_CONFIG_READ_ACTIONS.has(arg)) {
|
|
179
|
+
readAction = true;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (GIT_CONFIG_NEUTRAL_FLAGS.has(arg))
|
|
183
|
+
continue;
|
|
184
|
+
if (GIT_CONFIG_FLAGS_WITH_ARG.has(arg)) {
|
|
185
|
+
i += 1;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (arg.startsWith("--") && arg.includes("=")) {
|
|
189
|
+
const name = arg.slice(0, arg.indexOf("="));
|
|
190
|
+
if (GIT_CONFIG_FLAGS_WITH_ARG.has(name))
|
|
191
|
+
continue;
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
// Any other flag (--add, --unset, --replace-all, --edit, -e,
|
|
195
|
+
// --rename-section, --remove-section, --comment, ...) may write.
|
|
196
|
+
if (arg.startsWith("-"))
|
|
197
|
+
return false;
|
|
198
|
+
positionals.push(arg);
|
|
199
|
+
}
|
|
200
|
+
if (readAction)
|
|
201
|
+
return true;
|
|
202
|
+
const [first] = positionals;
|
|
203
|
+
if (first !== undefined && GIT_CONFIG_READ_SUBCOMMANDS.has(first)) {
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
// `git config <name>` reads one key; a second positional is its new value.
|
|
207
|
+
return positionals.length === 1;
|
|
208
|
+
};
|
|
209
|
+
/** True for `--name=value` where `--name` is a global option with a value. */
|
|
210
|
+
const isInlineGlobalFlag = (arg) => {
|
|
211
|
+
const eq = arg.indexOf("=");
|
|
212
|
+
if (!arg.startsWith("--") || eq === -1)
|
|
213
|
+
return false;
|
|
214
|
+
const name = arg.slice(0, eq);
|
|
215
|
+
return (GIT_GLOBAL_FLAGS_WITH_ARG.has(name) || GIT_GLOBAL_FLAGS_INLINE_ARG.has(name));
|
|
216
|
+
};
|
|
217
|
+
const extractGitSubcommandIndex = (tokens) => {
|
|
218
|
+
let i = 0;
|
|
219
|
+
while (i < tokens.length) {
|
|
220
|
+
const arg = tokens[i];
|
|
221
|
+
if (GIT_GLOBAL_FLAGS_WITH_ARG.has(arg)) {
|
|
222
|
+
i += 2;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (GIT_GLOBAL_FLAGS_NO_ARG.has(arg)) {
|
|
226
|
+
i += 1;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (isInlineGlobalFlag(arg)) {
|
|
230
|
+
i += 1;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (arg.startsWith("-C") && arg.length > 2) {
|
|
234
|
+
i += 1;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (arg.startsWith("-c") && arg.length > 2 && arg.includes("=")) {
|
|
238
|
+
i += 1;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
return i;
|
|
242
|
+
}
|
|
243
|
+
return -1;
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Removes shell quoting and backslash escapes from one word, so `g''it`,
|
|
247
|
+
* `"git"`, `'git'` and `\\git` all read as the program the shell will run.
|
|
248
|
+
*/
|
|
249
|
+
const unquoteWord = (word) => word.replace(/["'\\]/g, "");
|
|
250
|
+
/** True if the program token resolves to the git binary (path/extension aware). */
|
|
251
|
+
const isGitProgram = (token) => {
|
|
252
|
+
const word = unquoteWord(token);
|
|
253
|
+
const base = (word.split(/[/\\]/).pop() ?? word).toLowerCase();
|
|
254
|
+
return base === "git" || base === "git.exe";
|
|
255
|
+
};
|
|
256
|
+
// Words that run the rest of the line as a command: `env git push`,
|
|
257
|
+
// `command git push`, `sudo git push`.
|
|
258
|
+
const COMMAND_PREFIX_WORDS = new Set([
|
|
259
|
+
"env",
|
|
260
|
+
"command",
|
|
261
|
+
"exec",
|
|
262
|
+
"sudo",
|
|
263
|
+
"nohup",
|
|
264
|
+
"time",
|
|
265
|
+
"nice",
|
|
266
|
+
"builtin",
|
|
267
|
+
]);
|
|
268
|
+
const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
269
|
+
/**
|
|
270
|
+
* Index of the program token in a segment: skips `NAME=value` assignments and
|
|
271
|
+
* wrapper words such as `env` or `sudo` (and the flags `env`/`sudo` take).
|
|
272
|
+
*/
|
|
273
|
+
const programIndex = (tokens) => {
|
|
274
|
+
let i = 0;
|
|
275
|
+
while (i < tokens.length) {
|
|
276
|
+
const word = unquoteWord(tokens[i]);
|
|
277
|
+
if (ENV_ASSIGNMENT.test(word)) {
|
|
278
|
+
i += 1;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (COMMAND_PREFIX_WORDS.has(word.toLowerCase())) {
|
|
282
|
+
i += 1;
|
|
283
|
+
while (i < tokens.length && tokens[i].startsWith("-"))
|
|
284
|
+
i += 1;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
return i;
|
|
288
|
+
}
|
|
289
|
+
return -1;
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* True if the program is chosen at run time from a variable (`$GIT push`,
|
|
293
|
+
* `${G} push`), so the text cannot tell whether it is git.
|
|
294
|
+
*/
|
|
295
|
+
const isDynamicProgram = (token) => /^\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[^}]+\})$/.test(unquoteWord(token));
|
|
296
|
+
/**
|
|
297
|
+
* True if a single git command segment is read-only (allowed). Non-git commands
|
|
298
|
+
* return true (the guard only governs git). Handles path-prefixed invocations
|
|
299
|
+
* (`/usr/bin/git`, `./git`, `git.exe`) and a word boundary so look-alikes like
|
|
300
|
+
* `github-cli` / `git-lfs` are not misparsed as git subcommands.
|
|
301
|
+
*/
|
|
302
|
+
export const isGitAllowed = (command) => {
|
|
303
|
+
const trimmed = command.trim();
|
|
304
|
+
if (trimmed.length === 0)
|
|
305
|
+
return true;
|
|
306
|
+
const allTokens = trimmed.split(/\s+/);
|
|
307
|
+
const progIdx = programIndex(allTokens);
|
|
308
|
+
if (progIdx === -1)
|
|
309
|
+
return true; // only assignments / wrappers
|
|
310
|
+
const tokens = allTokens.slice(progIdx);
|
|
311
|
+
// A program picked from a variable may be git; the guard cannot see which.
|
|
312
|
+
if (isDynamicProgram(tokens[0]) && tokens.length > 1)
|
|
313
|
+
return false;
|
|
314
|
+
if (!isGitProgram(tokens[0]))
|
|
315
|
+
return true; // not a git invocation
|
|
316
|
+
return isGitArgsAllowed(tokens.slice(1).map(unquoteWord));
|
|
317
|
+
};
|
|
318
|
+
/**
|
|
319
|
+
* Splits the arguments git receives (without the program name) into the
|
|
320
|
+
* global options, the subcommand and its arguments. An option git prints and
|
|
321
|
+
* exits on (`--version`) stands in the subcommand's place.
|
|
322
|
+
*/
|
|
323
|
+
export const splitGitArgs = (args) => {
|
|
324
|
+
const subIndex = extractGitSubcommandIndex(args);
|
|
325
|
+
if (subIndex === -1) {
|
|
326
|
+
return { globalOptions: args, subcommand: "", subcommandArgs: [] };
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
globalOptions: args.slice(0, subIndex),
|
|
330
|
+
subcommand: args[subIndex],
|
|
331
|
+
subcommandArgs: args.slice(subIndex + 1),
|
|
332
|
+
};
|
|
333
|
+
};
|
|
334
|
+
/**
|
|
335
|
+
* True if git, run with these arguments (without the program name), only
|
|
336
|
+
* reads repository state. Decides on the argument vector itself, so it holds
|
|
337
|
+
* for a program an interpreter assembled at run time as well as for typed
|
|
338
|
+
* commands.
|
|
339
|
+
*/
|
|
340
|
+
export const isGitArgsAllowed = (args) => {
|
|
341
|
+
const { subcommand, subcommandArgs } = splitGitArgs(args);
|
|
342
|
+
if (subcommand === "")
|
|
343
|
+
return true; // bare "git" shows help
|
|
344
|
+
if (GIT_ALLOWED_SUBCOMMANDS.has(subcommand))
|
|
345
|
+
return true;
|
|
346
|
+
if (GIT_INFO_OPTIONS.has(subcommand))
|
|
347
|
+
return true;
|
|
348
|
+
if (subcommand === "config")
|
|
349
|
+
return isGitConfigRead(subcommandArgs);
|
|
350
|
+
const readTokens = GIT_CONDITIONAL_READS.get(subcommand);
|
|
351
|
+
if (readTokens !== undefined) {
|
|
352
|
+
const nextToken = subcommandArgs[0] ?? "";
|
|
353
|
+
if (readTokens.has(nextToken))
|
|
354
|
+
return true;
|
|
355
|
+
}
|
|
356
|
+
return false;
|
|
357
|
+
};
|
|
358
|
+
/** True if git, run with these arguments, sends commits to another repository. */
|
|
359
|
+
export const isGitRemoteWrite = (args) => GIT_REMOTE_WRITE_SUBCOMMANDS.has(splitGitArgs(args).subcommand);
|
|
360
|
+
/**
|
|
361
|
+
* Backward-compatible alias of {@link isGitAllowed}: true if a single git
|
|
362
|
+
* command segment only reads repository state.
|
|
363
|
+
*/
|
|
364
|
+
export const isGitReadOnly = isGitAllowed;
|
|
365
|
+
/**
|
|
366
|
+
* Extract every `git <subcommand> …` fragment from a command string, handling
|
|
367
|
+
* multi-line scripts, `&&`/`||`/`;` chains, `$(git …)`, and backticks.
|
|
368
|
+
*/
|
|
369
|
+
export const extractGitInvocations = (command) => {
|
|
370
|
+
const invocations = [];
|
|
371
|
+
// Split on the bare separators and let the per-phrase trim() below absorb the
|
|
372
|
+
// surrounding whitespace. Padding the separators (/\s*(?:…|\n)\s*/) made `\s*`
|
|
373
|
+
// and the `\n` alternative overlap, so a command padded with a long whitespace
|
|
374
|
+
// run backtracked quadratically — a hostile tool argument could stall the
|
|
375
|
+
// guard, and with it the driving loop, for minutes.
|
|
376
|
+
const phrases = command.split(/&&|\|\||;|\n/);
|
|
377
|
+
for (const phrase of phrases) {
|
|
378
|
+
const trimmed = phrase.trim();
|
|
379
|
+
if (trimmed.length === 0)
|
|
380
|
+
continue;
|
|
381
|
+
// A program token the fragment scan below cannot see because it is
|
|
382
|
+
// quoted or escaped (`"git" push`, `g''it push`, `\\git push`) or picked
|
|
383
|
+
// from a variable (`$GIT push`). Plain `git`, in any case, is found below.
|
|
384
|
+
const words = trimmed.split(/\s+/);
|
|
385
|
+
const progIdx = programIndex(words);
|
|
386
|
+
if (progIdx !== -1) {
|
|
387
|
+
const prog = words[progIdx];
|
|
388
|
+
const hidden = unquoteWord(prog) !== prog && isGitProgram(prog);
|
|
389
|
+
if (hidden || isDynamicProgram(prog)) {
|
|
390
|
+
const tail = words.slice(progIdx).join(" ");
|
|
391
|
+
invocations.push((tail.split(/[|&;)`]/)[0] ?? tail).trim());
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (!/git/i.test(trimmed))
|
|
395
|
+
continue;
|
|
396
|
+
// Preceding class includes / and \ so path-prefixed git (/usr/bin/git) is caught.
|
|
397
|
+
const gitFragments = trimmed.matchAll(/(?:^|[\s($`/\\])git\b/gi);
|
|
398
|
+
for (const m of gitFragments) {
|
|
399
|
+
const matchStr = m[0];
|
|
400
|
+
const gitOffset = matchStr.toLowerCase().indexOf("git");
|
|
401
|
+
const idx = (m.index ?? 0) + gitOffset;
|
|
402
|
+
const rest = trimmed.slice(idx);
|
|
403
|
+
const fragment = (rest.split(/[;&|$)`'"]/)[0] ?? rest).trim();
|
|
404
|
+
if (fragment.toLowerCase().startsWith("git"))
|
|
405
|
+
invocations.push(fragment);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return invocations;
|
|
409
|
+
};
|
|
410
|
+
/**
|
|
411
|
+
* True if a command smuggles a git WRITE through a subshell (`bash -c …`),
|
|
412
|
+
* `eval`, pipe chain, or command substitution. Complements {@link isGitAllowed}.
|
|
413
|
+
*/
|
|
414
|
+
export const containsGitWriteBypass = (command) => {
|
|
415
|
+
// Any *sh shell (bash/zsh/ksh/dash/sh, optionally path-prefixed) with a -c
|
|
416
|
+
// variant (-c/-lc/-ic), and an inner string that may be plain- or $'…'-quoted.
|
|
417
|
+
const subshellPatterns = [
|
|
418
|
+
/(?:^|\s)(?:\S*\/)?[a-z]*sh\s+-\w*c\s+\$?["'](.+?)["']/g,
|
|
419
|
+
/(?:^|\s)(?:\S*\/)?[a-z]*sh\s+-\w*c\s+(\S+)/g,
|
|
420
|
+
/eval\s+["'](.+?)["']/g,
|
|
421
|
+
];
|
|
422
|
+
for (const pattern of subshellPatterns) {
|
|
423
|
+
let match;
|
|
424
|
+
while ((match = pattern.exec(command)) !== null) {
|
|
425
|
+
const inner = match[1] ?? "";
|
|
426
|
+
if (inner.includes("git") && !isGitAllowed(inner))
|
|
427
|
+
return true;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// Pipe chains: any segment that is a git write (path-aware via isGitAllowed).
|
|
431
|
+
// Plain string split, not /\s*\|\s*/: that pattern re-scanned a whitespace run
|
|
432
|
+
// from every offset before failing on the missing `|`, which is quadratic on a
|
|
433
|
+
// padded command. The trim() below yields the same segments.
|
|
434
|
+
const segments = command.split("|");
|
|
435
|
+
for (const seg of segments) {
|
|
436
|
+
const trimSeg = seg.trim();
|
|
437
|
+
if (trimSeg.length > 0 && !isGitAllowed(trimSeg))
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
// Catch $(git …), `git …`, and path-prefixed git anywhere.
|
|
441
|
+
const gitFragments = command.matchAll(/(?:^|[\s($`/\\])git\b/gi);
|
|
442
|
+
for (const m of gitFragments) {
|
|
443
|
+
const matchStr = m[0];
|
|
444
|
+
const gitOffset = matchStr.toLowerCase().indexOf("git");
|
|
445
|
+
const idx = (m.index ?? 0) + gitOffset;
|
|
446
|
+
const rest = command.slice(idx);
|
|
447
|
+
const fragment = (rest.split(/[;&|$)`'"]/)[0] ?? "").trim();
|
|
448
|
+
if (fragment.toLowerCase().startsWith("git") && !isGitAllowed(fragment)) {
|
|
449
|
+
return true;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
// A shell that reads its script from stdin (`… | sh`, `sh <<< '…'`,
|
|
453
|
+
// `sh << EOF`) runs text the checks above only saw inside quotes. Scan the
|
|
454
|
+
// whole command with quoting removed.
|
|
455
|
+
if (feedsShellFromStdin(command)) {
|
|
456
|
+
const unquoted = command.replace(/["'\\]/g, "");
|
|
457
|
+
for (const inv of extractGitInvocations(unquoted)) {
|
|
458
|
+
if (!isGitAllowed(inv))
|
|
459
|
+
return true;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return false;
|
|
463
|
+
};
|
|
464
|
+
const SHELL_PROGRAM = String.raw `(?:\S*\/)?(?:ba|z|k|da|a)?sh`;
|
|
465
|
+
/** A pipe into a shell: `... | sh`, `... | bash -s`. */
|
|
466
|
+
const PIPE_INTO_SHELL = new RegExp(String.raw `\|\s*${SHELL_PROGRAM}(?:\s+-\w+)*\s*(?:$|[;&|)])`, "m");
|
|
467
|
+
/** A shell reading a heredoc: `sh <<EOF`. */
|
|
468
|
+
const SHELL_HEREDOC = new RegExp(String.raw `(?:^|[\s;&|(])${SHELL_PROGRAM}(?:\s+-\w+)*\s*<<`, "m");
|
|
469
|
+
/** True if a shell in the command takes its script from stdin or a heredoc. */
|
|
470
|
+
export const feedsShellFromStdin = (command) => PIPE_INTO_SHELL.test(command) || SHELL_HEREDOC.test(command);
|
|
471
|
+
/**
|
|
472
|
+
* Script files a command runs through a shell (`sh run.sh`, `bash -e x.sh`,
|
|
473
|
+
* `source x.sh`, `. x.sh`). The caller can read them; their content is not in
|
|
474
|
+
* the command text.
|
|
475
|
+
*/
|
|
476
|
+
export const shellScriptTargets = (command) => {
|
|
477
|
+
const targets = [];
|
|
478
|
+
const phrases = command.split(/&&|\|\||;|\n|\|/);
|
|
479
|
+
for (const phrase of phrases) {
|
|
480
|
+
const words = phrase.trim().split(/\s+/).map(unquoteWord);
|
|
481
|
+
const progIdx = programIndex(words);
|
|
482
|
+
if (progIdx === -1)
|
|
483
|
+
continue;
|
|
484
|
+
const prog = (words[progIdx].split("/").pop() ?? "").toLowerCase();
|
|
485
|
+
let i = progIdx + 1;
|
|
486
|
+
if (/^(?:ba|z|k|da|a)?sh$/.test(prog)) {
|
|
487
|
+
while (i < words.length && words[i].startsWith("-")) {
|
|
488
|
+
if (/c/.test(words[i])) {
|
|
489
|
+
i = -1; // `sh -c '…'` runs a string, handled elsewhere
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
i += 1;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
else if (prog !== "source" && prog !== ".") {
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (i >= 0 && i < words.length && !words[i].startsWith("<")) {
|
|
499
|
+
targets.push(words[i]);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return targets;
|
|
503
|
+
};
|
|
504
|
+
/** True if the command itself writes `path` (`> path`, `>> path`, `tee path`). */
|
|
505
|
+
export const writesFile = (command, path) => {
|
|
506
|
+
const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
507
|
+
return new RegExp(String.raw `(?:>>?|\btee(?:\s+-a)?)\s*["']?${escaped}["']?(?:\s|$|[;&|])`).test(command);
|
|
508
|
+
};
|
|
509
|
+
/**
|
|
510
|
+
* Strip quoted flag values so user-provided text (e.g. `--answer="use git"`)
|
|
511
|
+
* isn't scanned as a command.
|
|
512
|
+
*/
|
|
513
|
+
export const stripFlagValues = (command) => command
|
|
514
|
+
.replace(/--\w+='[^']*'/g, "")
|
|
515
|
+
.replace(/--\w+="[^"]*"/g, "")
|
|
516
|
+
.replace(/--\w+=\S*/g, "");
|
|
517
|
+
/**
|
|
518
|
+
* Convenience: true if `command` performs (or smuggles) any git write.
|
|
519
|
+
*/
|
|
520
|
+
export const hasGitWrite = (command) => {
|
|
521
|
+
const cleaned = stripFlagValues(command);
|
|
522
|
+
for (const inv of extractGitInvocations(cleaned)) {
|
|
523
|
+
if (!isGitAllowed(inv))
|
|
524
|
+
return true;
|
|
525
|
+
}
|
|
526
|
+
return containsGitWriteBypass(cleaned);
|
|
527
|
+
};
|
package/dist/mod.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@eserstack/agents` — binary discovery and spawn specs for interactive coding
|
|
3
|
+
* agents.
|
|
4
|
+
*
|
|
5
|
+
* An {@link AgentAdapter} knows how to find and launch a coding agent (Claude
|
|
6
|
+
* Code, OpenCode, Codex). Pairs with `@eserstack/mux`, which owns panes and
|
|
7
|
+
* PTYs, and reuses the shared git guard.
|
|
8
|
+
*
|
|
9
|
+
* The autonomous driving loop that used to live here is gone, along with the
|
|
10
|
+
* regex state matchers it depended on: an agent's state now arrives as ACP
|
|
11
|
+
* session/update events reported by the agent itself, rather than being guessed
|
|
12
|
+
* from the last ten rows of its TUI.
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
export type { AgentAdapter, AgentCapabilities, CliAdapterOptions, SpawnContext, SpawnSpec, } from "./adapter.ts";
|
|
17
|
+
export { createCliAgentAdapter, isOnPath, resolveFirstOnPath, } from "./adapter.ts";
|
|
18
|
+
export { defaultAgentAdapter, getAgentAdapter, listAgentAdapters, } from "./registry.ts";
|
|
19
|
+
export { claudeCodeAdapter } from "./adapters/claude-code.ts";
|
|
20
|
+
export { opencodeAdapter } from "./adapters/opencode.ts";
|
|
21
|
+
export { codexAdapter } from "./adapters/codex.ts";
|
|
22
|
+
export * as gitGuard from "./guards/git.ts";
|
package/dist/mod.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
export { createCliAgentAdapter, isOnPath, resolveFirstOnPath, } from "./adapter.js";
|
|
3
|
+
export { defaultAgentAdapter, getAgentAdapter, listAgentAdapters, } from "./registry.js";
|
|
4
|
+
export { claudeCodeAdapter } from "./adapters/claude-code.js";
|
|
5
|
+
export { opencodeAdapter } from "./adapters/opencode.js";
|
|
6
|
+
export { codexAdapter } from "./adapters/codex.js";
|
|
7
|
+
export * as gitGuard from "./guards/git.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-adapter registry. Mirrors the sync/adapter registry pattern: a flat list
|
|
3
|
+
* plus id lookup, with claude-code as the default.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import type { AgentAdapter } from "./adapter.ts";
|
|
8
|
+
/** All registered adapters. */
|
|
9
|
+
export declare const listAgentAdapters: () => readonly AgentAdapter[];
|
|
10
|
+
/** Look up an adapter by id (e.g. "claude-code"), or undefined. */
|
|
11
|
+
export declare const getAgentAdapter: (id: string) => AgentAdapter | undefined;
|
|
12
|
+
/** The default adapter (Claude Code). */
|
|
13
|
+
export declare const defaultAgentAdapter: () => AgentAdapter;
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as claudeCode from "./adapters/claude-code.js";
|
|
3
|
+
import * as opencode from "./adapters/opencode.js";
|
|
4
|
+
import * as codex from "./adapters/codex.js";
|
|
5
|
+
const ADAPTERS = [
|
|
6
|
+
claudeCode.claudeCodeAdapter,
|
|
7
|
+
opencode.opencodeAdapter,
|
|
8
|
+
codex.codexAdapter,
|
|
9
|
+
];
|
|
10
|
+
/** All registered adapters. */
|
|
11
|
+
export const listAgentAdapters = () => ADAPTERS;
|
|
12
|
+
/** Look up an adapter by id (e.g. "claude-code"), or undefined. */
|
|
13
|
+
export const getAgentAdapter = (id) => ADAPTERS.find((a) => a.id === id);
|
|
14
|
+
/** The default adapter (Claude Code). */
|
|
15
|
+
export const defaultAgentAdapter = () => claudeCode.claudeCodeAdapter;
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eserstack/agents",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "5.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/eser/stack",
|
|
8
|
+
"directory": "pkg/@eserstack/agents"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/**/*.js",
|
|
12
|
+
"dist/**/*.d.ts",
|
|
13
|
+
"dist/**/*.json"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/mod.d.ts",
|
|
18
|
+
"import": "./dist/mod.js"
|
|
19
|
+
},
|
|
20
|
+
"./adapter": {
|
|
21
|
+
"types": "./dist/adapter.d.ts",
|
|
22
|
+
"import": "./dist/adapter.js"
|
|
23
|
+
},
|
|
24
|
+
"./registry": {
|
|
25
|
+
"types": "./dist/registry.d.ts",
|
|
26
|
+
"import": "./dist/registry.js"
|
|
27
|
+
},
|
|
28
|
+
"./guards": {
|
|
29
|
+
"types": "./dist/guards/git.d.ts",
|
|
30
|
+
"import": "./dist/guards/git.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@eserstack/shell": "5.0.0",
|
|
35
|
+
"@eserstack/standards": "5.0.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@eserstack/test-kit": "5.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "node ../../../etc/scripts/build-library.ts"
|
|
42
|
+
}
|
|
6
43
|
}
|