@ory/amp 1.9.1 → 1.10.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/README.md CHANGED
@@ -12,9 +12,11 @@ One command installs two independent halves:
12
12
  ## What you'll need
13
13
 
14
14
  - [Amp](https://ampcode.com), installed
15
+ <!-- BEGIN GENERATED requirements -->
15
16
  - Node.js **22 or newer**
16
17
  - [Docker](https://docs.docker.com/get-docker/) — only if you want to run Ory locally
17
18
  - macOS or Linux (Windows works via WSL2)
19
+ <!-- END GENERATED requirements -->
18
20
 
19
21
  ## Get started
20
22
 
@@ -100,19 +102,28 @@ Then a denied tool is actually blocked and Amp shows why.
100
102
 
101
103
  Amp gets the plugin in two pieces that work together:
102
104
 
103
- - **A permission gate** registered in Amp's settings (`~/.config/amp/settings.json`) under the `amp.permissions` key. Before every tool call, Amp hands the tool and its params to this compatibility gate and reads the answer from its **exit code**: `0` = allow, `1` = ask, `≥2` = reject (the reason on stderr is shown to Amp).
104
- - **An in-process plugin** at `<project>/.amp/plugins/ory.ts`, which Amp's built-in TypeScript runtime loads to sign you in, authorize tool calls with Amp's exact thread ID, and record results. Its native `tool.call` response can block with `reject-and-continue`.
105
+ - **A permission gate** registered in your Amp user settings under the `amp.permissions` key, so it is not tied to one project. Before a tool call, Amp runs the gate with the tool's parameters as JSON on stdin and the tool name and thread in the `AGENT_TOOL_NAME` and `AMP_THREAD_ID` environment variables, and reads the answer from its **exit code**: `0` = allow, `1` = ask, `≥2` = reject (the reason on stderr is shown to Amp).
106
+ - **An in-process plugin** at `<project>/.amp/plugins/ory.ts`, which Amp's built-in TypeScript runtime loads to sign you in and record results. If sign-in is declined or fails, it shows an Amp notification (`Ory sign-in did not complete: <reason>. Tool calls may be denied this session.`); the session still starts.
105
107
 
106
- Amp gives the gate 10 seconds to answer and treats a slower gate as a reject, so the plugin sets its own shorter deadline (5 seconds, adjustable with `ORY_AMP_CHECK_TIMEOUT_MS`) and lets the tool through if the Ory check is slow, stuck, or unreachable — it never leaves you hanging.
108
+ **Each tool call is checked by the permission gate, and by the in-process plugin when it is installed.** Amp's plugin API has no "no decision" result for `tool.call`, so the plugin cannot defer to the gate. It checks every call itself (and can block with `reject-and-continue`) rather than return `allow` unchecked. In a project with the plugin installed, a call can therefore be checked twice. A call is never left unchecked. `install` adds the gate after your existing `amp.permissions` rules, because Amp uses the first matching rule.
109
+
110
+ **Which settings file.** `install` and `uninstall` edit the user settings file Amp reads: the file `AMP_SETTINGS_FILE` names when that variable is set, otherwise `settings.json` in `$XDG_CONFIG_HOME/amp` (default `~/.config/amp`), otherwise `settings.jsonc` beside it when only that file exists. When both files exist, Amp reads `settings.json`, and so does the plugin. A file passed only with Amp's `--settings-file` flag is not seen; set `AMP_SETTINGS_FILE` instead. Amp reads these files as JSON with comments, and the plugin keeps your comments and every other key. The `amp.permissions` value itself is rewritten, so a comment inside that list is not kept. If the file does not parse, `install` and `uninstall` stop with an error and change nothing. `uninstall` removes only the Ory rule; it removes the `amp.permissions` key only when no other rule is left. `status` shows which file is in use.
111
+
112
+ **When Amp runs the gate.** Amp applies `amp.permissions` rules only while its Permissions switch is on. With `amp.dangerouslyAllowAll` set to `true`, `--dangerously-allow-all`, or permissions turned off for the session, Amp skips every rule, the gate included. The in-process plugin still checks each call in projects where it is installed. This describes Amp `0.0.1793462430`; Amp's current documentation no longer describes `amp.permissions` and points to plugins for controlling tools, so a later Amp release may stop running the gate.
113
+
114
+ **Shell commands.** Amp has three shell tools, and which one the model gets depends on the agent mode: `Bash` (command in `cmd`), `shell_command`, and `async_shell_command` (command in `command`). Shell-command blocks apply to all three.
115
+
116
+ Amp gives the gate 10 seconds to answer and treats a slower gate as a reject, so the plugin sets its own shorter deadline (5 seconds, adjustable with `ORY_AMP_CHECK_TIMEOUT_MS`). When that deadline passes before the gate can resolve the project's posture, the tool is rejected with a reason that says the check timed out, instead of Amp's generic timeout.
107
117
 
108
118
  The Ory skills land under `<project>/.agents/skills/`. `uninstall` removes the gate, the plugin, and the skills.
109
119
 
110
- **MCP servers.** Amp documents MCP tool names as `mcp__<server>__<tool>` ([Plugin API](https://ampcode.com/docs/plugin-api)). The plugin's `tool.call` handler checks a call with that name as `McpServer:<server>` and `McpTool:<server>:<tool>`, and the gate applies the same check when Amp's (undocumented) delegate payload carries that name; Agent Security resolves the reported server name to a cataloged server, and other tools keep the native check. By default, though, Amp does not send MCP tools to the model one by one: agents reach MCP servers through `code_exec` (with `tool_search`), and those calls arrive as a single `code_exec` tool call that names no server, so they are checked as the native `code_exec` tool. Only MCP tools an agent exposes directly carry the `mcp__` name. No fingerprints are sent, because Amp's payload does not say how a server is launched.
120
+ **MCP servers.** Amp documents MCP tool names as `mcp__<server>__<tool>` ([Plugin API](https://ampcode.com/docs/plugin-api)). The plugin's `tool.call` handler checks a call with that name as `McpServer:<server>` and `McpTool:<server>:<tool>`, and the gate applies the same check to the `AGENT_TOOL_NAME` Amp passes it; Agent Security resolves the reported server name to a cataloged server, and other tools keep the native check. By default, though, Amp does not send MCP tools to the model one by one: agents reach MCP servers through `code_exec` (with `tool_search`), and those calls arrive as a single `code_exec` tool call that names no server, so they are checked as the native `code_exec` tool. Only MCP tools an agent exposes directly carry the `mcp__` name. No fingerprints are sent, because Amp does not say how a server is launched.
111
121
 
112
122
  </details>
113
123
 
114
124
  ## Connect to Ory Agent Security
115
125
 
126
+ <!-- BEGIN GENERATED connect -->
116
127
  Copy the connection details from the [Ory Console](https://console.ory.sh) under **Agent Security**:
117
128
 
118
129
  | Value | Flag | Environment variable |
@@ -136,6 +147,7 @@ npx -y -p @ory/amp ory-amp configure \
136
147
  Sign-in runs at the start of every session and never blocks — a declined, skipped, or timed-out login simply leaves that session without a user identity.
137
148
 
138
149
  Settings are saved to `~/.config/ory-agent-plugins/config.json` and shared across all your Ory agent plugins; environment variables win when both are set. Running headless with an OAuth2 access token already? Set `ORY_USER_OAUTH2_TOKEN` and the browser step is skipped entirely.
150
+ <!-- END GENERATED connect -->
139
151
 
140
152
  ## Commands
141
153
 
@@ -153,14 +165,16 @@ All prefixed with `npx -y -p @ory/amp`.
153
165
 
154
166
  ## Troubleshooting
155
167
 
156
- - **Local Ory fails to start** — make sure Docker is running and ports `4000`, `4100`, `4455`, and `16686` are free.
168
+ - **Local Ory fails to start** — <!-- BEGIN GENERATED local-stack-ports -->make sure Docker is running and ports `4000`, `4100`, and `4455` are free.<!-- END GENERATED local-stack-ports -->
157
169
  - **Browser sign-in loops** (after connecting) — confirm the reserved login client has all four documented loopback redirect URIs; `agent unregister` only clears legacy agent OAuth state.
158
170
  - **Running an older CLI than expected** — `npx -p @ory/amp` (no version pin) reuses a previously-downloaded copy instead of re-resolving to the latest. The install banner prints the running version; confirm it with `npx -y -p @ory/amp ory-amp version`. To force the current release, clear the cache and reinstall: `rm -rf ~/.npm/_npx` then `npx -y -p @ory/amp ory-amp install`. Pinning an exact version (`@ory/amp@<version>`) also bypasses the cached copy.
159
171
  - **A tool check feels slow** — the plugin gives up on a stalled Ory check and lets the tool through; tune the deadline with `ORY_AMP_CHECK_TIMEOUT_MS`.
160
172
 
161
173
  ## Learn more
162
174
 
175
+ <!-- BEGIN GENERATED ory-links -->
163
176
  - [Ory documentation](https://www.ory.com/docs/) · [Ory Console](https://console.ory.sh) · [Ory Elements](https://github.com/ory/elements)
177
+ <!-- END GENERATED ory-links -->
164
178
  - [Amp documentation](https://ampcode.com)
165
179
 
166
180
  ## License
@@ -48,7 +48,7 @@ exports.installAmpOryAssets = installAmpOryAssets;
48
48
  exports.uninstallAmpOryAssets = uninstallAmpOryAssets;
49
49
  const fs = __importStar(require("node:fs"));
50
50
  const path = __importStar(require("node:path"));
51
- const argus_1 = require("@ory/argus");
51
+ const install_1 = require("@ory/argus/install");
52
52
  const RENDER_OPTS = {
53
53
  binName: "ory-amp",
54
54
  packageName: "@ory/amp",
@@ -64,28 +64,18 @@ function skillsRoot(projectDir) {
64
64
  function installAmpOryAssets(projectDir) {
65
65
  const skillsDir = skillsRoot(projectDir);
66
66
  fs.mkdirSync(skillsDir, { recursive: true });
67
- const guideSkills = (0, argus_1.renderOrySkills)("amp", RENDER_OPTS);
68
- const commandSkills = (0, argus_1.renderOryCommands)("amp", RENDER_OPTS).map(argus_1.commandToSkill);
69
- (0, argus_1.writeSkillTree)(skillsDir, [...guideSkills, ...commandSkills]);
70
- }
71
- function safeRmEmpty(dir) {
72
- try {
73
- if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {
74
- fs.rmdirSync(dir);
75
- }
76
- }
77
- catch {
78
- /* ignore — leave the dir if removal fails. */
79
- }
67
+ const guideSkills = (0, install_1.renderOrySkills)("amp", RENDER_OPTS);
68
+ const commandSkills = (0, install_1.renderOryCommands)("amp", RENDER_OPTS).map(install_1.commandToSkill);
69
+ (0, install_1.writeSkillTree)(skillsDir, [...guideSkills, ...commandSkills]);
80
70
  }
81
71
  /** Remove every skill + command-skill this plugin installed. */
82
72
  function uninstallAmpOryAssets(projectDir) {
83
73
  const skillsDir = skillsRoot(projectDir);
84
74
  if (!fs.existsSync(skillsDir))
85
75
  return;
86
- (0, argus_1.removeSkillDirs)(skillsDir, argus_1.ORY_SKILL_NAMES);
87
- (0, argus_1.removeSkillDirs)(skillsDir, argus_1.ORY_COMMAND_SKILL_NAMES);
88
- safeRmEmpty(skillsDir);
76
+ (0, install_1.removeSkillDirs)(skillsDir, install_1.ORY_SKILL_NAMES);
77
+ (0, install_1.removeSkillDirs)(skillsDir, install_1.ORY_COMMAND_SKILL_NAMES);
78
+ (0, install_1.removeDirIfEmpty)(skillsDir);
89
79
  // Clean up the parent `.agents` dir if we emptied it.
90
- safeRmEmpty(path.dirname(skillsDir));
80
+ (0, install_1.removeDirIfEmpty)(path.dirname(skillsDir));
91
81
  }
package/dist/cli/main.js CHANGED
@@ -45,134 +45,44 @@ var __importStar = (this && this.__importStar) || (function () {
45
45
  })();
46
46
  Object.defineProperty(exports, "__esModule", { value: true });
47
47
  const path = __importStar(require("node:path"));
48
- const os = __importStar(require("node:os"));
49
48
  const fs = __importStar(require("node:fs"));
50
- const argus_1 = require("@ory/argus");
49
+ const cli_1 = require("@ory/argus/cli");
50
+ const install_1 = require("@ory/argus/install");
51
+ const delegate_config_js_1 = require("../delegate-config.js");
52
+ const setup_js_1 = require("./setup.js");
51
53
  const PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
52
- function main() {
53
- const [command, ...args] = process.argv.slice(2);
54
- // `--help` after a matched subcommand: print usage, do nothing else.
55
- // Without this the switch below ignores the flag and `install --help`
56
- // performs a real install (#221).
57
- if ((0, argus_1.shouldPrintHelp)(command, args))
58
- return help();
59
- switch (command) {
60
- case "install":
61
- (0, argus_1.beginDeferNextSteps)();
62
- install(args);
63
- (0, argus_1.runPostInstall)("ory-amp", "amp", args).then(() => process.exit(0), (err) => {
64
- console.error(err.message ?? err);
65
- process.exit(1);
66
- });
67
- break;
68
- case "uninstall":
69
- uninstall(args);
70
- (0, argus_1.clearCredentialsForUninstall)({
71
- harness: "amp",
72
- purge: args.includes("--purge"),
73
- }).then(() => process.exit(0), (err) => {
74
- console.error(err.message ?? err);
75
- process.exit(1);
76
- });
77
- break;
78
- case "configure":
79
- (0, argus_1.runConfigureCommand)("ory-amp", args);
80
- break;
81
- case "agent":
82
- (0, argus_1.runAgentCommand)("ory-amp", "amp", args).then((code) => process.exit(code), (err) => {
83
- console.error(err.message ?? err);
84
- process.exit(1);
85
- });
86
- break;
87
- case "permissions":
88
- (0, argus_1.runPermissionsCommand)("ory-amp", "amp", args).then((code) => process.exit(code), (err) => {
89
- console.error(err.message ?? err);
90
- process.exit(1);
91
- });
92
- break;
93
- case "setup":
94
- require("./setup.js");
95
- break;
96
- case "status":
97
- status(args).then(() => process.exit(0), (err) => {
98
- console.error(err.message ?? err);
99
- process.exit(1);
100
- });
101
- break;
102
- case "watch":
103
- (0, argus_1.runWatchCommand)("ory-amp", "amp", args).then((code) => process.exit(code), (err) => { console.error(err.message ?? err); process.exit(1); });
104
- break;
105
- case "local":
106
- (0, argus_1.runLocalCommand)("ory-amp", args).catch((err) => {
107
- console.error(err.message ?? err);
108
- process.exit(1);
109
- });
110
- break;
111
- case "version":
112
- case "--version":
113
- case "-v":
114
- process.exit((0, argus_1.runVersionCommand)("ory-amp", args, { packageRoot: PACKAGE_ROOT }));
115
- break;
116
- case "help":
117
- case "--help":
118
- case "-h":
119
- case undefined:
120
- help();
121
- break;
122
- default:
123
- console.error(`Unknown command: ${command}`);
124
- help();
125
- process.exit(1);
126
- }
127
- }
128
54
  /**
129
55
  * Amp has no native plugin-registration CLI, so install delegates to the
130
56
  * setup writer, which registers the permission delegate in Amp's settings
131
57
  * and writes the in-process plugin loader at `.amp/plugins/ory.ts`.
132
58
  */
133
59
  function install(args) {
134
- process.argv = ["node", "setup.js", ...args];
135
- require("./setup.js");
136
- (0, argus_1.printEnvHelp)("ory-amp");
137
- }
138
- function uninstall(args) {
139
- process.argv = ["node", "setup.js", "--uninstall", ...args];
140
- require("./setup.js");
60
+ (0, setup_js_1.install)(args);
61
+ (0, cli_1.printEnvHelp)("ory-amp");
141
62
  }
142
- function parseProjectDir(args) {
143
- const idx = args.indexOf("--project-dir");
144
- if (idx !== -1 && args[idx + 1])
145
- return args[idx + 1];
146
- return process.cwd();
63
+ /** `Delegate:` status row: registered, not registered, or settings unreadable. */
64
+ function delegateStatus(settingsPath) {
65
+ try {
66
+ const rules = (0, install_1.readJsonFile)(settingsPath)["amp.permissions"];
67
+ return Array.isArray(rules) && rules.some(delegate_config_js_1.isOryDelegateEntry) ? "registered" : "NOT registered";
68
+ }
69
+ catch {
70
+ return "unknown (the settings file could not be parsed)";
71
+ }
147
72
  }
148
73
  async function status(args) {
149
- const projectDir = parseProjectDir(args);
150
- // Setup writes the delegate to Amp's user-global settings file (the
151
- // `--settings-file` default); the in-process loader lives under the
152
- // project's `.amp/plugins/`.
153
- const settingsPath = path.join(os.homedir(), ".config", "amp", "settings.json");
74
+ const projectDir = (0, setup_js_1.parseProjectDir)(args);
75
+ // The delegate lives in the user settings file Amp reads; the in-process
76
+ // loader lives under the project's `.amp/plugins/`.
77
+ const settingsPath = (0, delegate_config_js_1.ampSettingsPath)();
154
78
  const pluginFile = path.join(projectDir, ".amp", "plugins", "ory.ts");
155
- await (0, argus_1.runStatusCommand)("ory-amp", "amp", {
79
+ await (0, cli_1.runStatusCommand)("ory-amp", "amp", {
156
80
  title: "Amp",
157
81
  printPluginSection: () => {
158
82
  console.log("Permission delegate & plugin:");
159
83
  console.log(` Settings file: ${settingsPath}`);
160
- let delegateRegistered = false;
161
- try {
162
- if (fs.existsSync(settingsPath)) {
163
- const raw = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
164
- const perms = Array.isArray(raw["amp.permissions"])
165
- ? raw["amp.permissions"]
166
- : [];
167
- delegateRegistered = perms.some((p) => p?.to === "ory-amp-permission" ||
168
- /ory-hook-amp\.(js|cjs|mjs)$/.test(String(p?.to ?? "")));
169
- }
170
- }
171
- catch {
172
- /* ignore parse errors */
173
- }
174
- console.log(` Delegate: ${delegateRegistered ? "registered" : "NOT registered"}`);
175
- console.log(` Runtime: ${(0, argus_1.describeRuntimeHealth)((0, argus_1.checkRuntimeHealth)("amp"))}`);
84
+ console.log(` Delegate: ${delegateStatus(settingsPath)}`);
85
+ console.log(` Runtime: ${(0, install_1.describeRuntimeHealth)((0, install_1.checkRuntimeHealth)("amp"))}`);
176
86
  console.log(` In-process plugin: ${fs.existsSync(pluginFile) ? `installed (${pluginFile})` : "not installed"}`);
177
87
  },
178
88
  });
@@ -208,4 +118,21 @@ Examples:
208
118
  npx -y -p @ory/amp ory-amp status
209
119
  `);
210
120
  }
211
- main();
121
+ (0, cli_1.runHarnessCli)({
122
+ bin: "ory-amp",
123
+ harness: "amp",
124
+ packageRoot: PACKAGE_ROOT,
125
+ help,
126
+ install,
127
+ printInstallPlan: () => (0, setup_js_1.printInstallPlan)(),
128
+ uninstall: setup_js_1.uninstall,
129
+ setup: (args) => {
130
+ if (args.includes("--print"))
131
+ (0, setup_js_1.printInstallPlan)();
132
+ else if (args.includes("--uninstall"))
133
+ (0, setup_js_1.uninstall)(args);
134
+ else
135
+ (0, setup_js_1.install)(args);
136
+ },
137
+ status,
138
+ });
@@ -17,17 +17,37 @@
17
17
  * npx ory-amp-setup --print # Print config to stdout without writing
18
18
  * npx ory-amp-setup --uninstall # Remove Ory entries from settings + plugins
19
19
  *
20
- * Verified against the installed `amp` binary: the default settings file is
21
- * `~/.config/amp/settings.json` (the `--settings-file` default), with a flat
22
- * top-level `amp.permissions` array of `{ tool, action, to }`. Amp also ships
23
- * a native `amp permissions add <action> <tool> --to <program>` command (with
20
+ * Read from the installed `amp` build (0.0.1793462430): the user settings file
21
+ * is `AMP_SETTINGS_FILE` when set, else `settings.json` under
22
+ * `$XDG_CONFIG_HOME/amp` (default `~/.config/amp`), else `settings.jsonc`
23
+ * beside it when only that file exists. Amp parses either as JSONC. Setup
24
+ * edits the file Amp reads, keeps its comments and unrelated keys, and stops
25
+ * without writing when the file does not parse.
26
+ *
27
+ * `amp.permissions` is a flat top-level array of `{ tool, action, to }`. Amp
28
+ * also ships `amp permissions add <action> <tool> --to <program>` (with
24
29
  * `-w/--workspace` for project scope); the equivalent registration is:
25
30
  *
26
31
  * amp permissions add delegate '*' --to ory-amp-permission
27
32
  *
28
- * This setup writes the same entry into settings.json directly so the flow
33
+ * This setup writes the same entry into the settings file directly so the flow
29
34
  * works without shelling out. In-process plugins are discovered as direct
30
35
  * `*.ts` files under `.amp/plugins/` (project) or `~/.config/amp/plugins/`
31
36
  * (system), executed by Bun's TypeScript runtime.
32
37
  */
33
- export {};
38
+ /** `--project-dir <path>`, defaulting to the current directory. */
39
+ export declare function parseProjectDir(args: readonly string[]): string;
40
+ /** Describe the settings entry `install` writes. Resolves and writes nothing. */
41
+ export declare function printInstallPlan(): void;
42
+ /**
43
+ * Register the delegate, write the plugin loader, and install the skills.
44
+ * Throws `ConfigParseError` before changing anything when Amp's settings file
45
+ * does not parse.
46
+ */
47
+ export declare function install(args: string[]): void;
48
+ /**
49
+ * Remove the Ory delegate rule, the plugin loader, and the skills. Throws
50
+ * `ConfigParseError` before changing anything when Amp's settings file does
51
+ * not parse.
52
+ */
53
+ export declare function uninstall(args: string[]): void;
package/dist/cli/setup.js CHANGED
@@ -18,15 +18,20 @@
18
18
  * npx ory-amp-setup --print # Print config to stdout without writing
19
19
  * npx ory-amp-setup --uninstall # Remove Ory entries from settings + plugins
20
20
  *
21
- * Verified against the installed `amp` binary: the default settings file is
22
- * `~/.config/amp/settings.json` (the `--settings-file` default), with a flat
23
- * top-level `amp.permissions` array of `{ tool, action, to }`. Amp also ships
24
- * a native `amp permissions add <action> <tool> --to <program>` command (with
21
+ * Read from the installed `amp` build (0.0.1793462430): the user settings file
22
+ * is `AMP_SETTINGS_FILE` when set, else `settings.json` under
23
+ * `$XDG_CONFIG_HOME/amp` (default `~/.config/amp`), else `settings.jsonc`
24
+ * beside it when only that file exists. Amp parses either as JSONC. Setup
25
+ * edits the file Amp reads, keeps its comments and unrelated keys, and stops
26
+ * without writing when the file does not parse.
27
+ *
28
+ * `amp.permissions` is a flat top-level array of `{ tool, action, to }`. Amp
29
+ * also ships `amp permissions add <action> <tool> --to <program>` (with
25
30
  * `-w/--workspace` for project scope); the equivalent registration is:
26
31
  *
27
32
  * amp permissions add delegate '*' --to ory-amp-permission
28
33
  *
29
- * This setup writes the same entry into settings.json directly so the flow
34
+ * This setup writes the same entry into the settings file directly so the flow
30
35
  * works without shelling out. In-process plugins are discovered as direct
31
36
  * `*.ts` files under `.amp/plugins/` (project) or `~/.config/amp/plugins/`
32
37
  * (system), executed by Bun's TypeScript runtime.
@@ -65,11 +70,16 @@ var __importStar = (this && this.__importStar) || (function () {
65
70
  };
66
71
  })();
67
72
  Object.defineProperty(exports, "__esModule", { value: true });
73
+ exports.parseProjectDir = parseProjectDir;
74
+ exports.printInstallPlan = printInstallPlan;
75
+ exports.install = install;
76
+ exports.uninstall = uninstall;
68
77
  const fs = __importStar(require("node:fs"));
69
- const os = __importStar(require("node:os"));
70
78
  const path = __importStar(require("node:path"));
71
- const argus_1 = require("@ory/argus");
79
+ const cli_1 = require("@ory/argus/cli");
80
+ const install_1 = require("@ory/argus/install");
72
81
  const assets_js_1 = require("./assets.js");
82
+ const delegate_config_js_1 = require("../delegate-config.js");
73
83
  const PACKAGE_NAME = "@ory/amp";
74
84
  const PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
75
85
  /** Direct *.ts loader Amp's Bun runtime discovers under .amp/plugins/. */
@@ -83,7 +93,7 @@ const PLUGIN_FILE = "ory.ts";
83
93
  * module by absolute path).
84
94
  */
85
95
  function wireAmpRuntime(args) {
86
- return (0, argus_1.wireRuntime)({
96
+ return (0, install_1.wireRuntime)({
87
97
  harness: "amp",
88
98
  packageName: PACKAGE_NAME,
89
99
  packageRoot: PACKAGE_ROOT,
@@ -92,12 +102,10 @@ function wireAmpRuntime(args) {
92
102
  entryRelPath: path.join("dist", "permission.js"),
93
103
  });
94
104
  }
95
- function getSettingsPath(_args) {
96
- // Verified: Amp's default settings file is the user-global
97
- // ~/.config/amp/settings.json (the `--settings-file` default). Amp's own
98
- // permission entries are global by default; `-w/--workspace` would scope
99
- // them to the project. We follow the verified default.
100
- return path.join(os.homedir(), ".config", "amp", "settings.json");
105
+ /** `--project-dir <path>`, defaulting to the current directory. */
106
+ function parseProjectDir(args) {
107
+ const idx = args.indexOf("--project-dir");
108
+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : process.cwd();
101
109
  }
102
110
  /**
103
111
  * The `amp.permissions` delegate entry that routes every tool ("*") through
@@ -113,31 +121,25 @@ function getSettingsPath(_args) {
113
121
  function delegateEntry(to) {
114
122
  return { tool: "*", action: "delegate", to };
115
123
  }
116
- function isOryDelegate(entry) {
117
- if (typeof entry !== "object" || entry === null)
118
- return false;
119
- const rec = entry;
120
- if (rec.action !== "delegate")
121
- return false;
122
- const to = typeof rec.to === "string" ? rec.to : "";
123
- // Match the shim we write now and the bare bin name earlier releases wrote,
124
- // so an install replaces a stale entry instead of leaving both in place.
125
- return to === "ory-amp-permission" || /ory-hook-amp\.(js|cjs|mjs)$/.test(to);
126
- }
127
124
  function mergePermissions(existing, to) {
128
125
  const merged = { ...existing };
129
126
  const perms = (Array.isArray(merged["amp.permissions"])
130
127
  ? merged["amp.permissions"]
131
- : []).filter((e) => !isOryDelegate(e));
128
+ : []).filter((e) => !(0, delegate_config_js_1.isOryDelegateEntry)(e));
132
129
  perms.push(delegateEntry(to));
133
130
  merged["amp.permissions"] = perms;
134
131
  return merged;
135
132
  }
133
+ /**
134
+ * Drop the Ory rule and nothing else. The key goes with its last rule: Amp
135
+ * loads its permission rules whenever `amp.permissions` is present, even
136
+ * empty, so leaving `[]` behind would change how Amp behaves.
137
+ */
136
138
  function removePermissions(existing) {
137
139
  const merged = { ...existing };
138
140
  const perms = (Array.isArray(merged["amp.permissions"])
139
141
  ? merged["amp.permissions"]
140
- : []).filter((e) => !isOryDelegate(e));
142
+ : []).filter((e) => !(0, delegate_config_js_1.isOryDelegateEntry)(e));
141
143
  if (perms.length === 0) {
142
144
  delete merged["amp.permissions"];
143
145
  }
@@ -159,46 +161,29 @@ function pluginLoaderSource(runtime) {
159
161
  `// Re-exports the Ory in-process plugin for Amp's .amp/plugins/ loader.\n` +
160
162
  `export { default } from ${JSON.stringify(entry)};\n`);
161
163
  }
162
- function getPluginFile(args) {
163
- return path.join(args.projectDir, ".amp", "plugins", PLUGIN_FILE);
164
+ function getPluginFile(projectDir) {
165
+ return path.join(projectDir, ".amp", "plugins", PLUGIN_FILE);
164
166
  }
165
- function main() {
166
- if (process.argv.includes("--help") || process.argv.includes("-h")) {
167
- (0, argus_1.printSetupHelp)("ory-amp-setup", "Amp");
168
- process.exit(0);
169
- }
170
- const args = (0, argus_1.parseSetupArgs)();
171
- if (args.print) {
172
- // Nothing is resolved or written on a --print run.
173
- console.log(JSON.stringify({ "amp.permissions": [delegateEntry("<resolved runtime shim>")] }, null, 2));
174
- return;
175
- }
176
- const settingsPath = getSettingsPath(args);
177
- const pluginFile = getPluginFile(args);
178
- const skillsDir = path.join(args.projectDir, ".agents", "skills");
179
- const existing = (0, argus_1.readJsonFile)(settingsPath);
180
- if (args.uninstall) {
181
- if (fs.existsSync(settingsPath)) {
182
- const updated = removePermissions(existing);
183
- (0, argus_1.writeJsonFile)(settingsPath, updated);
184
- console.log(`Removed Ory permission delegate from ${settingsPath}`);
185
- }
186
- else {
187
- console.log("No Amp settings file found. Nothing to remove from settings.");
188
- }
189
- if (fs.existsSync(pluginFile)) {
190
- fs.rmSync(pluginFile, { force: true });
191
- console.log(`Removed Ory in-process plugin from ${pluginFile}`);
192
- }
193
- (0, assets_js_1.uninstallAmpOryAssets)(args.projectDir);
194
- console.log(`Removed Ory skills from ${skillsDir}`);
195
- (0, argus_1.removeRuntimeWiring)("amp");
196
- for (const pruned of (0, argus_1.pruneRuntimeStores)()) {
197
- console.log(` Removed runtime: ${pruned}`);
198
- }
199
- return;
200
- }
201
- const runtime = wireAmpRuntime(process.argv.slice(2));
167
+ function hasOryDelegate(settings) {
168
+ const rules = settings["amp.permissions"];
169
+ return Array.isArray(rules) && rules.some(delegate_config_js_1.isOryDelegateEntry);
170
+ }
171
+ /** Describe the settings entry `install` writes. Resolves and writes nothing. */
172
+ function printInstallPlan() {
173
+ console.log(JSON.stringify({ "amp.permissions": [delegateEntry("<resolved runtime shim>")] }, null, 2));
174
+ }
175
+ /**
176
+ * Register the delegate, write the plugin loader, and install the skills.
177
+ * Throws `ConfigParseError` before changing anything when Amp's settings file
178
+ * does not parse.
179
+ */
180
+ function install(args) {
181
+ const projectDir = parseProjectDir(args);
182
+ const settingsPath = (0, delegate_config_js_1.ampSettingsPath)();
183
+ const pluginFile = getPluginFile(projectDir);
184
+ const skillsDir = path.join(projectDir, ".agents", "skills");
185
+ const existing = (0, install_1.readJsonFile)(settingsPath);
186
+ const runtime = wireAmpRuntime(args);
202
187
  console.log(runtime.target.kind === "linked"
203
188
  ? `Runtime: linked to ${runtime.target.packageDir} (dev)`
204
189
  : `Runtime: ${runtime.target.packageName}@${runtime.target.version} in ${runtime.target.storeDir}`);
@@ -206,32 +191,77 @@ function main() {
206
191
  console.log(` Removed stale runtime: ${pruned}`);
207
192
  }
208
193
  // (a) Register the permission delegate (blocking gate).
209
- const merged = mergePermissions(existing, runtime.hookShim);
210
- (0, argus_1.writeJsonFile)(settingsPath, merged);
194
+ (0, install_1.writeJsonFile)(settingsPath, mergePermissions(existing, runtime.hookShim));
211
195
  // (b) Write the in-process plugin loader (auth + activity auditing).
212
196
  fs.mkdirSync(path.dirname(pluginFile), { recursive: true });
213
197
  fs.writeFileSync(pluginFile, pluginLoaderSource(runtime));
214
198
  // (c) Materialize the Ory skill catalog.
215
- (0, assets_js_1.installAmpOryAssets)(args.projectDir);
199
+ (0, assets_js_1.installAmpOryAssets)(projectDir);
216
200
  console.log(`Ory permission delegate registered in ${settingsPath}`);
217
201
  console.log(` Delegate: ${runtime.hookShim} (tool: "*", action: delegate)`);
218
202
  console.log(`Ory in-process plugin written to ${pluginFile}`);
219
203
  console.log(`Ory skills installed under ${skillsDir}`);
220
- (0, argus_1.printNextSteps)("Amp", "npx -y -p @ory/amp ory-amp-setup --uninstall", {
204
+ (0, install_1.printNextSteps)("Amp", "npx -y -p @ory/amp ory-amp-setup --uninstall", {
221
205
  binName: "ory-amp",
222
206
  harness: "amp",
223
207
  });
224
208
  }
225
- main();
226
- // When invoked directly as the `-setup` bin with `--uninstall`, also clear
227
- // stored Ory credentials. When required by the plugin's main CLI, that
228
- // command owns the purge, so the `require.main` guard prevents a double run.
229
- if (require.main === module && process.argv.includes("--uninstall")) {
230
- (0, argus_1.clearCredentialsForUninstall)({
231
- harness: "amp",
232
- purge: process.argv.includes("--purge"),
233
- }).then(() => process.exit(0), (err) => {
234
- console.error(err.message ?? err);
209
+ /**
210
+ * Remove the Ory delegate rule, the plugin loader, and the skills. Throws
211
+ * `ConfigParseError` before changing anything when Amp's settings file does
212
+ * not parse.
213
+ */
214
+ function uninstall(args) {
215
+ const projectDir = parseProjectDir(args);
216
+ const settingsPath = (0, delegate_config_js_1.ampSettingsPath)();
217
+ const pluginFile = getPluginFile(projectDir);
218
+ const skillsDir = path.join(projectDir, ".agents", "skills");
219
+ const existing = (0, install_1.readJsonFile)(settingsPath);
220
+ if (hasOryDelegate(existing)) {
221
+ (0, install_1.writeJsonFile)(settingsPath, removePermissions(existing));
222
+ console.log(`Removed Ory permission delegate from ${settingsPath}`);
223
+ }
224
+ else {
225
+ console.log(`No Ory permission delegate in ${settingsPath}. Settings left unchanged.`);
226
+ }
227
+ if (fs.existsSync(pluginFile)) {
228
+ fs.rmSync(pluginFile, { force: true });
229
+ console.log(`Removed Ory in-process plugin from ${pluginFile}`);
230
+ }
231
+ (0, assets_js_1.uninstallAmpOryAssets)(projectDir);
232
+ console.log(`Removed Ory skills from ${skillsDir}`);
233
+ (0, install_1.removeRuntimeWiring)("amp");
234
+ for (const pruned of (0, install_1.pruneRuntimeStores)()) {
235
+ console.log(` Removed runtime: ${pruned}`);
236
+ }
237
+ }
238
+ // --- Standalone binary entry point (ory-amp-setup) ---
239
+ if (require.main === module) {
240
+ const args = process.argv.slice(2);
241
+ if (args.includes("--help") || args.includes("-h")) {
242
+ (0, install_1.printSetupHelp)("ory-amp-setup", "Amp");
243
+ process.exit(0);
244
+ }
245
+ try {
246
+ if (args.includes("--print"))
247
+ printInstallPlan();
248
+ else if (args.includes("--uninstall"))
249
+ uninstall(args);
250
+ else
251
+ install(args);
252
+ }
253
+ catch (err) {
254
+ if (!(err instanceof install_1.ConfigParseError))
255
+ throw err;
256
+ console.error(err.message);
235
257
  process.exit(1);
236
- });
258
+ }
259
+ // The main CLI clears stored credentials itself on `uninstall`; this bin has
260
+ // to do it here.
261
+ if (args.includes("--uninstall") && !args.includes("--print")) {
262
+ (0, cli_1.clearCredentialsForUninstall)({ harness: "amp", purge: args.includes("--purge") }).then(() => process.exit(0), (err) => {
263
+ console.error(err.message ?? err);
264
+ process.exit(1);
265
+ });
266
+ }
237
267
  }