@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 +19 -5
- package/dist/cli/assets.js +8 -18
- package/dist/cli/main.js +40 -113
- package/dist/cli/setup.d.ts +26 -6
- package/dist/cli/setup.js +111 -81
- package/dist/delegate-config.d.ts +59 -0
- package/dist/delegate-config.js +234 -0
- package/dist/permission.d.ts +27 -5
- package/dist/permission.js +48 -15
- package/dist/plugin.d.ts +8 -0
- package/dist/plugin.js +50 -4
- package/dist/types.d.ts +32 -22
- package/dist/types.js +13 -11
- package/package.json +2 -2
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared knowledge of the Ory permission delegate entry in Amp's settings.
|
|
3
|
+
*
|
|
4
|
+
* The setup CLI writes the entry, and a caller that wants the in-process
|
|
5
|
+
* `tool.call` handler to skip calls the delegate will check can pass
|
|
6
|
+
* {@link oryDelegateCoversTool} to the plugin. This module is safe to load at
|
|
7
|
+
* tool-call time: it imports nothing from the install or CLI entry points.
|
|
8
|
+
*
|
|
9
|
+
* Read from the installed `amp` build (0.0.1793462430): `amp.permissions` is a
|
|
10
|
+
* flat array of `{ tool, action, to? }` rules. Workspace rules are evaluated
|
|
11
|
+
* before user rules and the first match wins. A `reject` rule ends the call
|
|
12
|
+
* without running the tool; `allow`, `ask`, and another program's `delegate`
|
|
13
|
+
* let a call skip every later rule, including ours.
|
|
14
|
+
*/
|
|
15
|
+
type Env = Record<string, string | undefined>;
|
|
16
|
+
/** Amp's user config directory: `$XDG_CONFIG_HOME/amp`, else `~/.config/amp`. */
|
|
17
|
+
export declare function ampConfigDir(env?: Env): string;
|
|
18
|
+
/**
|
|
19
|
+
* The user settings file Amp reads, resolved the way the installed `amp`
|
|
20
|
+
* build (0.0.1793462430) resolves it:
|
|
21
|
+
*
|
|
22
|
+
* 1. `AMP_SETTINGS_FILE`, when set, is used as given. It is the default of
|
|
23
|
+
* Amp's `--settings-file` flag; a path passed only on Amp's command line is
|
|
24
|
+
* not visible here.
|
|
25
|
+
* 2. Otherwise `settings.json` in {@link ampConfigDir}. It wins when both
|
|
26
|
+
* files exist.
|
|
27
|
+
* 3. `settings.jsonc` beside it is read only when `settings.json` is absent.
|
|
28
|
+
*
|
|
29
|
+
* Amp parses either file as JSONC (comments and trailing commas).
|
|
30
|
+
*/
|
|
31
|
+
export declare function ampSettingsPath(env?: Env): string;
|
|
32
|
+
/**
|
|
33
|
+
* The workspace settings file Amp reads: the nearest `.amp/settings.json` or
|
|
34
|
+
* `.amp/settings.jsonc` (in that order per directory), searched upward from
|
|
35
|
+
* `cwd` to the Git repository root, or only `cwd` outside a repository. When
|
|
36
|
+
* none exists, the path `amp permissions add -w` would create.
|
|
37
|
+
*/
|
|
38
|
+
export declare function ampWorkspaceSettingsPath(cwd?: string): string;
|
|
39
|
+
/** Whether a permission rule is the Ory delegate (current shim or legacy bin). */
|
|
40
|
+
export declare function isOryDelegateEntry(entry: unknown): boolean;
|
|
41
|
+
export interface DelegateCoverageOptions {
|
|
42
|
+
userSettingsFile?: string;
|
|
43
|
+
workspaceSettingsFile?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether Amp will run the Ory delegate for `toolName`, so the in-process
|
|
47
|
+
* gate can skip the call instead of checking it a second time.
|
|
48
|
+
*
|
|
49
|
+
* True only when the user settings register the Ory delegate and no earlier
|
|
50
|
+
* user rule, and no workspace rule, can let this tool run first. Anything
|
|
51
|
+
* unreadable or ambiguous returns false, so the in-process gate stays on: a
|
|
52
|
+
* duplicate check is preferable to an unchecked call. Settings passed only
|
|
53
|
+
* with Amp's `--settings-file` flag are not visible here; those installs keep
|
|
54
|
+
* the in-process gate. Amp also skips every permission rule while its
|
|
55
|
+
* Permissions switch is off (`amp.dangerouslyAllowAll`, or the session
|
|
56
|
+
* toggle), which this function cannot see; a caller must not rely on it then.
|
|
57
|
+
*/
|
|
58
|
+
export declare function oryDelegateCoversTool(toolName: string, opts?: DelegateCoverageOptions): boolean;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Shared knowledge of the Ory permission delegate entry in Amp's settings.
|
|
4
|
+
*
|
|
5
|
+
* The setup CLI writes the entry, and a caller that wants the in-process
|
|
6
|
+
* `tool.call` handler to skip calls the delegate will check can pass
|
|
7
|
+
* {@link oryDelegateCoversTool} to the plugin. This module is safe to load at
|
|
8
|
+
* tool-call time: it imports nothing from the install or CLI entry points.
|
|
9
|
+
*
|
|
10
|
+
* Read from the installed `amp` build (0.0.1793462430): `amp.permissions` is a
|
|
11
|
+
* flat array of `{ tool, action, to? }` rules. Workspace rules are evaluated
|
|
12
|
+
* before user rules and the first match wins. A `reject` rule ends the call
|
|
13
|
+
* without running the tool; `allow`, `ask`, and another program's `delegate`
|
|
14
|
+
* let a call skip every later rule, including ours.
|
|
15
|
+
*/
|
|
16
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
17
|
+
if (k2 === undefined) k2 = k;
|
|
18
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
19
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
20
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
21
|
+
}
|
|
22
|
+
Object.defineProperty(o, k2, desc);
|
|
23
|
+
}) : (function(o, m, k, k2) {
|
|
24
|
+
if (k2 === undefined) k2 = k;
|
|
25
|
+
o[k2] = m[k];
|
|
26
|
+
}));
|
|
27
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
28
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
29
|
+
}) : function(o, v) {
|
|
30
|
+
o["default"] = v;
|
|
31
|
+
});
|
|
32
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
33
|
+
var ownKeys = function(o) {
|
|
34
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
35
|
+
var ar = [];
|
|
36
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
37
|
+
return ar;
|
|
38
|
+
};
|
|
39
|
+
return ownKeys(o);
|
|
40
|
+
};
|
|
41
|
+
return function (mod) {
|
|
42
|
+
if (mod && mod.__esModule) return mod;
|
|
43
|
+
var result = {};
|
|
44
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
45
|
+
__setModuleDefault(result, mod);
|
|
46
|
+
return result;
|
|
47
|
+
};
|
|
48
|
+
})();
|
|
49
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
50
|
+
exports.ampConfigDir = ampConfigDir;
|
|
51
|
+
exports.ampSettingsPath = ampSettingsPath;
|
|
52
|
+
exports.ampWorkspaceSettingsPath = ampWorkspaceSettingsPath;
|
|
53
|
+
exports.isOryDelegateEntry = isOryDelegateEntry;
|
|
54
|
+
exports.oryDelegateCoversTool = oryDelegateCoversTool;
|
|
55
|
+
const fs = __importStar(require("node:fs"));
|
|
56
|
+
const os = __importStar(require("node:os"));
|
|
57
|
+
const path = __importStar(require("node:path"));
|
|
58
|
+
/** Bare bin name earlier releases wrote as the delegate target. */
|
|
59
|
+
const LEGACY_DELEGATE_BIN = "ory-amp-permission";
|
|
60
|
+
function nonEmpty(value) {
|
|
61
|
+
return value !== undefined && value.trim() !== "" ? value : undefined;
|
|
62
|
+
}
|
|
63
|
+
/** Amp's user config directory: `$XDG_CONFIG_HOME/amp`, else `~/.config/amp`. */
|
|
64
|
+
function ampConfigDir(env = process.env) {
|
|
65
|
+
return path.join(nonEmpty(env.XDG_CONFIG_HOME) ?? path.join(os.homedir(), ".config"), "amp");
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The user settings file Amp reads, resolved the way the installed `amp`
|
|
69
|
+
* build (0.0.1793462430) resolves it:
|
|
70
|
+
*
|
|
71
|
+
* 1. `AMP_SETTINGS_FILE`, when set, is used as given. It is the default of
|
|
72
|
+
* Amp's `--settings-file` flag; a path passed only on Amp's command line is
|
|
73
|
+
* not visible here.
|
|
74
|
+
* 2. Otherwise `settings.json` in {@link ampConfigDir}. It wins when both
|
|
75
|
+
* files exist.
|
|
76
|
+
* 3. `settings.jsonc` beside it is read only when `settings.json` is absent.
|
|
77
|
+
*
|
|
78
|
+
* Amp parses either file as JSONC (comments and trailing commas).
|
|
79
|
+
*/
|
|
80
|
+
function ampSettingsPath(env = process.env) {
|
|
81
|
+
const override = nonEmpty(env.AMP_SETTINGS_FILE);
|
|
82
|
+
if (override)
|
|
83
|
+
return path.resolve(override);
|
|
84
|
+
const json = path.join(ampConfigDir(env), "settings.json");
|
|
85
|
+
if (fs.existsSync(json))
|
|
86
|
+
return json;
|
|
87
|
+
const jsonc = path.join(ampConfigDir(env), "settings.jsonc");
|
|
88
|
+
return fs.existsSync(jsonc) ? jsonc : json;
|
|
89
|
+
}
|
|
90
|
+
function gitRoot(start) {
|
|
91
|
+
let dir = path.resolve(start);
|
|
92
|
+
for (;;) {
|
|
93
|
+
if (fs.existsSync(path.join(dir, ".git")))
|
|
94
|
+
return dir;
|
|
95
|
+
const parent = path.dirname(dir);
|
|
96
|
+
if (parent === dir)
|
|
97
|
+
return undefined;
|
|
98
|
+
dir = parent;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The workspace settings file Amp reads: the nearest `.amp/settings.json` or
|
|
103
|
+
* `.amp/settings.jsonc` (in that order per directory), searched upward from
|
|
104
|
+
* `cwd` to the Git repository root, or only `cwd` outside a repository. When
|
|
105
|
+
* none exists, the path `amp permissions add -w` would create.
|
|
106
|
+
*/
|
|
107
|
+
function ampWorkspaceSettingsPath(cwd = process.cwd()) {
|
|
108
|
+
const start = path.resolve(cwd);
|
|
109
|
+
const root = gitRoot(start) ?? start;
|
|
110
|
+
let dir = start;
|
|
111
|
+
for (;;) {
|
|
112
|
+
for (const name of ["settings.json", "settings.jsonc"]) {
|
|
113
|
+
const candidate = path.join(dir, ".amp", name);
|
|
114
|
+
if (fs.existsSync(candidate))
|
|
115
|
+
return candidate;
|
|
116
|
+
}
|
|
117
|
+
const parent = path.dirname(dir);
|
|
118
|
+
if (dir === root || parent === dir)
|
|
119
|
+
break;
|
|
120
|
+
dir = parent;
|
|
121
|
+
}
|
|
122
|
+
return path.join(root, ".amp", "settings.json");
|
|
123
|
+
}
|
|
124
|
+
/** Whether a permission rule is the Ory delegate (current shim or legacy bin). */
|
|
125
|
+
function isOryDelegateEntry(entry) {
|
|
126
|
+
if (typeof entry !== "object" || entry === null)
|
|
127
|
+
return false;
|
|
128
|
+
const rec = entry;
|
|
129
|
+
if (rec.action !== "delegate")
|
|
130
|
+
return false;
|
|
131
|
+
const to = typeof rec.to === "string" ? rec.to : "";
|
|
132
|
+
return to === LEGACY_DELEGATE_BIN || /ory-hook-amp\.(js|cjs|mjs)$/.test(to);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Reduce JSONC to JSON: drop `//` and block comments and trailing commas,
|
|
136
|
+
* leaving string contents untouched. Amp reads its settings as JSONC, so a
|
|
137
|
+
* strict parse would call a commented file unreadable.
|
|
138
|
+
*/
|
|
139
|
+
function stripJsonc(text) {
|
|
140
|
+
let out = "";
|
|
141
|
+
let i = 0;
|
|
142
|
+
while (i < text.length) {
|
|
143
|
+
const ch = text[i];
|
|
144
|
+
if (ch === '"') {
|
|
145
|
+
const start = i++;
|
|
146
|
+
while (i < text.length && text[i] !== '"')
|
|
147
|
+
i += text[i] === "\\" ? 2 : 1;
|
|
148
|
+
out += text.slice(start, ++i);
|
|
149
|
+
}
|
|
150
|
+
else if (ch === "/" && text[i + 1] === "/") {
|
|
151
|
+
while (i < text.length && text[i] !== "\n")
|
|
152
|
+
i++;
|
|
153
|
+
}
|
|
154
|
+
else if (ch === "/" && text[i + 1] === "*") {
|
|
155
|
+
const end = text.indexOf("*/", i + 2);
|
|
156
|
+
i = end < 0 ? text.length : end + 2;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
if (ch === "}" || ch === "]")
|
|
160
|
+
out = out.replace(/,(\s*)$/, "$1");
|
|
161
|
+
out += ch;
|
|
162
|
+
i++;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
function readPermissionRules(file) {
|
|
168
|
+
let raw;
|
|
169
|
+
try {
|
|
170
|
+
raw = fs.readFileSync(file, "utf-8");
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
if (raw.trim() === "")
|
|
176
|
+
return [];
|
|
177
|
+
try {
|
|
178
|
+
const parsed = JSON.parse(stripJsonc(raw));
|
|
179
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
180
|
+
return undefined;
|
|
181
|
+
const rules = parsed["amp.permissions"];
|
|
182
|
+
return Array.isArray(rules) ? rules : [];
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Amp tool patterns are globs (`*`, `?`); anything unparseable matches. */
|
|
189
|
+
function toolPatternMatches(pattern, toolName) {
|
|
190
|
+
if (typeof pattern !== "string" || pattern === "")
|
|
191
|
+
return true;
|
|
192
|
+
const source = pattern
|
|
193
|
+
.split("")
|
|
194
|
+
.map((ch) => (ch === "*" ? ".*" : ch === "?" ? "." : ch.replace(/[\\^$.|+()[\]{}]/g, "\\$&")))
|
|
195
|
+
.join("");
|
|
196
|
+
return new RegExp(`^${source}$`).test(toolName);
|
|
197
|
+
}
|
|
198
|
+
/** A rule that ends evaluation without reaching later rules and runs the tool. */
|
|
199
|
+
function bypassesLaterRules(rule, toolName) {
|
|
200
|
+
return rule.action !== "reject" && toolPatternMatches(rule.tool, toolName);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Whether Amp will run the Ory delegate for `toolName`, so the in-process
|
|
204
|
+
* gate can skip the call instead of checking it a second time.
|
|
205
|
+
*
|
|
206
|
+
* True only when the user settings register the Ory delegate and no earlier
|
|
207
|
+
* user rule, and no workspace rule, can let this tool run first. Anything
|
|
208
|
+
* unreadable or ambiguous returns false, so the in-process gate stays on: a
|
|
209
|
+
* duplicate check is preferable to an unchecked call. Settings passed only
|
|
210
|
+
* with Amp's `--settings-file` flag are not visible here; those installs keep
|
|
211
|
+
* the in-process gate. Amp also skips every permission rule while its
|
|
212
|
+
* Permissions switch is off (`amp.dangerouslyAllowAll`, or the session
|
|
213
|
+
* toggle), which this function cannot see; a caller must not rely on it then.
|
|
214
|
+
*/
|
|
215
|
+
function oryDelegateCoversTool(toolName, opts = {}) {
|
|
216
|
+
const userRules = readPermissionRules(opts.userSettingsFile ?? ampSettingsPath());
|
|
217
|
+
if (!userRules)
|
|
218
|
+
return false;
|
|
219
|
+
const index = userRules.findIndex(isOryDelegateEntry);
|
|
220
|
+
if (index < 0)
|
|
221
|
+
return false;
|
|
222
|
+
if (userRules.slice(0, index).some((rule) => bypassesLaterRules(rule, toolName)))
|
|
223
|
+
return false;
|
|
224
|
+
const workspaceFile = opts.workspaceSettingsFile ?? ampWorkspaceSettingsPath();
|
|
225
|
+
if (fs.existsSync(workspaceFile)) {
|
|
226
|
+
const workspaceRules = readPermissionRules(workspaceFile);
|
|
227
|
+
if (!workspaceRules)
|
|
228
|
+
return false;
|
|
229
|
+
if (workspaceRules.some((rule) => !isOryDelegateEntry(rule) && bypassesLaterRules(rule, toolName))) {
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return true;
|
|
234
|
+
}
|
package/dist/permission.d.ts
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Amp's `amp.permissions` config can route a tool to
|
|
6
6
|
* `{ action: "delegate", to: "ory-amp-permission" }`. Amp then runs this
|
|
7
|
-
* program as a subprocess for each matching tool call, passing the tool
|
|
8
|
-
* parameters as JSON on stdin
|
|
7
|
+
* program as a subprocess for each matching tool call, passing ONLY the tool
|
|
8
|
+
* parameters as JSON on stdin (for example `{"cmd":"ls -la"}`), exporting the
|
|
9
|
+
* tool name as `AGENT_TOOL_NAME` and the thread as `AMP_THREAD_ID`, and
|
|
10
|
+
* reading the decision from the exit code:
|
|
9
11
|
*
|
|
10
12
|
* exit 0 = allow
|
|
11
13
|
* exit 1 = ask the user (RESERVED — not produced by this version)
|
|
@@ -39,15 +41,35 @@ export interface DelegateDecision {
|
|
|
39
41
|
}
|
|
40
42
|
/** Resolve the check deadline, overridable via ORY_AMP_CHECK_TIMEOUT_MS. */
|
|
41
43
|
export declare function resolveCheckTimeoutMs(): number;
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Amp's delegate contract (verified with `amp permissions test` against the
|
|
46
|
+
* installed binary): stdin carries ONLY the tool parameters, for example
|
|
47
|
+
* `{"cmd":"ls -la"}` for Bash, and the tool name and thread arrive as the
|
|
48
|
+
* `AGENT_TOOL_NAME` and `AMP_THREAD_ID` environment variables.
|
|
49
|
+
*/
|
|
50
|
+
export interface DelegateEnv {
|
|
51
|
+
AGENT_TOOL_NAME?: string;
|
|
52
|
+
AMP_THREAD_ID?: string;
|
|
53
|
+
[key: string]: string | undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the tool name: `AGENT_TOOL_NAME` when Amp set it, otherwise the
|
|
57
|
+
* name fields an in-process caller or an older payload put on the object.
|
|
58
|
+
*/
|
|
59
|
+
export declare function extractToolName(input: AmpDelegateInput, env?: DelegateEnv): string;
|
|
44
60
|
/**
|
|
45
61
|
* Core decision logic, factored out so tests can call it directly without
|
|
46
62
|
* spawning a subprocess or hitting `process.exit`. Resolves to the exit
|
|
47
63
|
* code (and stderr reason) Amp expects. Always fails open: any thrown
|
|
48
64
|
* error resolves to ALLOW.
|
|
65
|
+
*
|
|
66
|
+
* `env` carries Amp's delegate variables; the delegate entry point passes
|
|
67
|
+
* `process.env`, and in-process callers omit it and pass the tool fields on
|
|
68
|
+
* `input`. This function never writes to stdout or stderr itself, because it
|
|
69
|
+
* also runs inside Amp's process: diagnostics go to the logger, and only the
|
|
70
|
+
* delegate entry point writes the rejection reason to stderr.
|
|
49
71
|
*/
|
|
50
|
-
export declare function decideToolPermission(input: AmpDelegateInput, client: OryAgentClient): Promise<DelegateDecision>;
|
|
72
|
+
export declare function decideToolPermission(input: AmpDelegateInput, client: OryAgentClient, env?: DelegateEnv): Promise<DelegateDecision>;
|
|
51
73
|
/**
|
|
52
74
|
* The stdin→exit-code delegate pipeline.
|
|
53
75
|
*
|
package/dist/permission.js
CHANGED
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Amp's `amp.permissions` config can route a tool to
|
|
7
7
|
* `{ action: "delegate", to: "ory-amp-permission" }`. Amp then runs this
|
|
8
|
-
* program as a subprocess for each matching tool call, passing the tool
|
|
9
|
-
* parameters as JSON on stdin
|
|
8
|
+
* program as a subprocess for each matching tool call, passing ONLY the tool
|
|
9
|
+
* parameters as JSON on stdin (for example `{"cmd":"ls -la"}`), exporting the
|
|
10
|
+
* tool name as `AGENT_TOOL_NAME` and the thread as `AMP_THREAD_ID`, and
|
|
11
|
+
* reading the decision from the exit code:
|
|
10
12
|
*
|
|
11
13
|
* exit 0 = allow
|
|
12
14
|
* exit 1 = ask the user (RESERVED — not produced by this version)
|
|
@@ -85,23 +87,51 @@ async function raceCheckDeadline(work, timeoutMs) {
|
|
|
85
87
|
clearTimeout(timer);
|
|
86
88
|
}
|
|
87
89
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return input.tool ?? input.toolName ?? input.name ?? "unknown";
|
|
90
|
+
function nonEmpty(value) {
|
|
91
|
+
return typeof value === "string" && value.trim() !== "" ? value : undefined;
|
|
91
92
|
}
|
|
92
|
-
/**
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Resolve the tool name: `AGENT_TOOL_NAME` when Amp set it, otherwise the
|
|
95
|
+
* name fields an in-process caller or an older payload put on the object.
|
|
96
|
+
*/
|
|
97
|
+
function extractToolName(input, env = {}) {
|
|
98
|
+
return (nonEmpty(env.AGENT_TOOL_NAME) ??
|
|
99
|
+
nonEmpty(input.tool) ??
|
|
100
|
+
nonEmpty(input.toolName) ??
|
|
101
|
+
nonEmpty(input.name) ??
|
|
102
|
+
"unknown");
|
|
103
|
+
}
|
|
104
|
+
/** Resolve the thread id: `AMP_THREAD_ID`, then payload fields as a fallback. */
|
|
105
|
+
function extractSessionId(input, env) {
|
|
106
|
+
return (nonEmpty(env.AMP_THREAD_ID) ??
|
|
107
|
+
nonEmpty(input.threadID) ??
|
|
108
|
+
nonEmpty(input.sessionID) ??
|
|
109
|
+
nonEmpty(input.session_id));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Resolve the tool arguments. Under Amp's env contract the whole stdin object
|
|
113
|
+
* is the parameters; the wrapped fields apply only to the fallback shape.
|
|
114
|
+
*/
|
|
115
|
+
function extractToolArgs(input, env) {
|
|
116
|
+
if (nonEmpty(env.AGENT_TOOL_NAME))
|
|
117
|
+
return input;
|
|
118
|
+
return input.input ?? input.params ?? input.arguments ?? input.args;
|
|
95
119
|
}
|
|
96
120
|
/**
|
|
97
121
|
* Core decision logic, factored out so tests can call it directly without
|
|
98
122
|
* spawning a subprocess or hitting `process.exit`. Resolves to the exit
|
|
99
123
|
* code (and stderr reason) Amp expects. Always fails open: any thrown
|
|
100
124
|
* error resolves to ALLOW.
|
|
125
|
+
*
|
|
126
|
+
* `env` carries Amp's delegate variables; the delegate entry point passes
|
|
127
|
+
* `process.env`, and in-process callers omit it and pass the tool fields on
|
|
128
|
+
* `input`. This function never writes to stdout or stderr itself, because it
|
|
129
|
+
* also runs inside Amp's process: diagnostics go to the logger, and only the
|
|
130
|
+
* delegate entry point writes the rejection reason to stderr.
|
|
101
131
|
*/
|
|
102
|
-
async function decideToolPermission(input, client) {
|
|
103
|
-
const toolName = extractToolName(input);
|
|
104
|
-
const sessionId = extractSessionId(input);
|
|
132
|
+
async function decideToolPermission(input, client, env = {}) {
|
|
133
|
+
const toolName = extractToolName(input, env);
|
|
134
|
+
const sessionId = extractSessionId(input, env);
|
|
105
135
|
return (0, argus_1.withHookContext)(client, { sessionId }, async () => {
|
|
106
136
|
client.logger.info("delegate.received", { toolName, sessionId });
|
|
107
137
|
try {
|
|
@@ -111,7 +141,7 @@ async function decideToolPermission(input, client) {
|
|
|
111
141
|
const raced = await raceCheckDeadline((0, argus_1.gate)(client, {
|
|
112
142
|
harness: "amp",
|
|
113
143
|
toolName,
|
|
114
|
-
toolArgs: input
|
|
144
|
+
toolArgs: extractToolArgs(input, env),
|
|
115
145
|
subjectFallback: sessionId ? `session:${sessionId}` : undefined,
|
|
116
146
|
canBlock: true,
|
|
117
147
|
// Amp names MCP tools `mcp__<server>__<tool>` (ampcode.com/docs/plugin-api).
|
|
@@ -119,7 +149,6 @@ async function decideToolPermission(input, client) {
|
|
|
119
149
|
mcpTool: (0, argus_1.parseMcpToolName)(toolName) ?? undefined,
|
|
120
150
|
}), timeoutMs);
|
|
121
151
|
if (raced === CHECK_TIMED_OUT) {
|
|
122
|
-
process.stderr.write(`[ory-agent] permission check for "${toolName}" timed out after ${timeoutMs}ms; blocking because posture is unknown\n`);
|
|
123
152
|
client.logger.warn("delegate.check_timeout", { toolName, timeoutMs });
|
|
124
153
|
return { exitCode: types_js_1.AMP_DELEGATE_EXIT.REJECT, reason: "Ory permission check timed out; retry when Agent Security is available." };
|
|
125
154
|
}
|
|
@@ -193,14 +222,18 @@ async function main() {
|
|
|
193
222
|
const raw = await readStdin();
|
|
194
223
|
let input;
|
|
195
224
|
try {
|
|
196
|
-
|
|
225
|
+
const parsed = raw.trim() ? JSON.parse(raw) : {};
|
|
226
|
+
// Amp sends the tool parameters object; anything else carries no arguments.
|
|
227
|
+
input = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
|
|
228
|
+
? parsed
|
|
229
|
+
: {};
|
|
197
230
|
}
|
|
198
231
|
catch {
|
|
199
232
|
// Parse failure — fail open (allow) rather than wedging the agent.
|
|
200
233
|
client.logger.error("delegate.stdin.parse_failed", { raw: raw.slice(0, 200) });
|
|
201
234
|
process.exit(types_js_1.AMP_DELEGATE_EXIT.ALLOW);
|
|
202
235
|
}
|
|
203
|
-
const { exitCode, reason } = await decideToolPermission(input, client);
|
|
236
|
+
const { exitCode, reason } = await decideToolPermission(input, client, process.env);
|
|
204
237
|
if (exitCode === types_js_1.AMP_DELEGATE_EXIT.REJECT && reason) {
|
|
205
238
|
// stderr is forwarded to the model as the rejection reason.
|
|
206
239
|
process.stderr.write(reason + "\n");
|
package/dist/plugin.d.ts
CHANGED
|
@@ -3,6 +3,14 @@ import type { AmpPlugin } from "./types.js";
|
|
|
3
3
|
export interface CreateOryPluginDeps {
|
|
4
4
|
userLogin?: typeof ensureUserAuthenticated;
|
|
5
5
|
agentGate?: typeof ensureAgentIdentity;
|
|
6
|
+
/**
|
|
7
|
+
* Whether Amp will run the Ory permission delegate for a tool, letting the
|
|
8
|
+
* in-process check be skipped. Defaults to `() => false`: Amp's plugin API has
|
|
9
|
+
* no "no decision" result, and it is unverified whether a plugin `allow`
|
|
10
|
+
* still lets the delegate run, so the in-process check always runs unless a
|
|
11
|
+
* caller opts in.
|
|
12
|
+
*/
|
|
13
|
+
delegateCoversTool?: (toolName: string) => boolean;
|
|
6
14
|
}
|
|
7
15
|
export declare function createOryPlugin(clientOrConfig?: OryAgentClient | {
|
|
8
16
|
projectUrl: string;
|
package/dist/plugin.js
CHANGED
|
@@ -4,6 +4,8 @@ exports.createOryPlugin = createOryPlugin;
|
|
|
4
4
|
const argus_1 = require("@ory/argus");
|
|
5
5
|
const permission_js_1 = require("./permission.js");
|
|
6
6
|
const HARNESS = "amp";
|
|
7
|
+
/** User login outcomes that leave the session without a signed-in user. */
|
|
8
|
+
const INCOMPLETE_SIGN_IN_MODES = new Set(["declined", "error"]);
|
|
7
9
|
function createOryPlugin(clientOrConfig, deps = {}) {
|
|
8
10
|
return (api) => {
|
|
9
11
|
const client = clientOrConfig instanceof argus_1.OryAgentClient
|
|
@@ -12,24 +14,68 @@ function createOryPlugin(clientOrConfig, deps = {}) {
|
|
|
12
14
|
? new argus_1.OryAgentClient({ ...clientOrConfig, harness: HARNESS })
|
|
13
15
|
: argus_1.OryAgentClient.fromEnv(HARNESS);
|
|
14
16
|
api.on("session.start", createSessionStartHandler(client, deps));
|
|
15
|
-
api.on("tool.call", createToolCallHandler(client));
|
|
17
|
+
api.on("tool.call", createToolCallHandler(client, deps.delegateCoversTool ?? (() => false)));
|
|
16
18
|
api.on("tool.result", createToolResultHandler(client));
|
|
17
19
|
};
|
|
18
20
|
}
|
|
19
21
|
function createSessionStartHandler(client, deps) {
|
|
20
|
-
return (event,
|
|
22
|
+
return (event, ctx) => (0, argus_1.withHookContext)(client, { sessionId: event.thread?.id }, async () => {
|
|
21
23
|
const sessionId = event.thread?.id;
|
|
22
24
|
client.logger.info("lifecycle.session_start", { sessionId });
|
|
23
|
-
await (0, argus_1.sessionStart)(client, {
|
|
25
|
+
const result = await (0, argus_1.sessionStart)(client, {
|
|
24
26
|
harness: HARNESS,
|
|
25
27
|
binName: "ory-amp",
|
|
26
28
|
userLogin: deps.userLogin,
|
|
27
29
|
agentGate: deps.agentGate,
|
|
28
30
|
});
|
|
31
|
+
if (INCOMPLETE_SIGN_IN_MODES.has(result.userMode)) {
|
|
32
|
+
notifySignInIncomplete(client, ctx, result.userReason);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Tell the user that sign-in did not complete, through Amp's `ctx.ui.notify`.
|
|
38
|
+
* Advisory only: a missing, throwing, or rejecting notifier is logged and the
|
|
39
|
+
* session continues, and the notice is not awaited so it cannot delay startup.
|
|
40
|
+
*/
|
|
41
|
+
function notifySignInIncomplete(client, ctx, reason) {
|
|
42
|
+
const message = `Ory sign-in did not complete: ${reason.replace(/[.\s]+$/, "")}. Tool calls may be denied this session.`;
|
|
43
|
+
const notify = ctx?.ui?.notify;
|
|
44
|
+
if (typeof notify !== "function") {
|
|
45
|
+
client.logger.warn("session_start.notify_unavailable", { message });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const onError = (err) => client.logger.warn("session_start.notify_failed", {
|
|
49
|
+
message: err instanceof Error ? err.message : String(err),
|
|
29
50
|
});
|
|
51
|
+
try {
|
|
52
|
+
const pending = notify.call(ctx?.ui, message);
|
|
53
|
+
if (pending && typeof pending.catch === "function") {
|
|
54
|
+
pending.catch(onError);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
onError(err);
|
|
59
|
+
}
|
|
30
60
|
}
|
|
31
|
-
|
|
61
|
+
/**
|
|
62
|
+
* In-process gate. By default it checks every call, even when the global Ory
|
|
63
|
+
* delegate will also check it: a call checked twice costs one extra request,
|
|
64
|
+
* while a call checked by neither would be an enforcement gap. A caller that
|
|
65
|
+
* has confirmed the delegate runs after a plugin `allow` can pass
|
|
66
|
+
* `delegateCoversTool` to skip the duplicate check.
|
|
67
|
+
*/
|
|
68
|
+
function createToolCallHandler(client, delegateCoversTool) {
|
|
32
69
|
return async (event) => {
|
|
70
|
+
let covered = false;
|
|
71
|
+
try {
|
|
72
|
+
covered = delegateCoversTool(event.tool);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
covered = false;
|
|
76
|
+
}
|
|
77
|
+
if (covered)
|
|
78
|
+
return { action: "allow" };
|
|
33
79
|
const decision = await (0, permission_js_1.decideToolPermission)({ tool: event.tool, input: event.input, threadID: event.thread.id }, client);
|
|
34
80
|
return decision.exitCode >= 2
|
|
35
81
|
? { action: "reject-and-continue", message: decision.reason ?? "Tool denied by Ory" }
|
package/dist/types.d.ts
CHANGED
|
@@ -7,31 +7,34 @@
|
|
|
7
7
|
*
|
|
8
8
|
* 1. Permission delegate helper (PRIMARY, blocking) — a standalone
|
|
9
9
|
* program named in `amp.permissions` as `{ tool, action: "delegate",
|
|
10
|
-
* to: "<program>" }`. Amp invokes it as a subprocess, passing the
|
|
11
|
-
* parameters as JSON on stdin
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
10
|
+
* to: "<program>" }`. Amp invokes it as a subprocess, passing ONLY the
|
|
11
|
+
* tool parameters as JSON on stdin and the tool name and thread as the
|
|
12
|
+
* `AGENT_TOOL_NAME` and `AMP_THREAD_ID` environment variables. The
|
|
13
|
+
* program decides by exit code: 0 = allow, 1 = ask the user, ≥2 = reject
|
|
14
|
+
* (stderr → model reason). A 10-second delegate timeout applies (a
|
|
15
|
+
* timed-out delegate is treated as a reject). See `AmpDelegateInput`.
|
|
15
16
|
*
|
|
16
|
-
* 2. In-process plugin (SECONDARY
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
17
|
+
* 2. In-process plugin (SECONDARY) — a default-exported factory placed
|
|
18
|
+
* under `.amp/plugins/*.ts` that receives a `PluginAPI` (the
|
|
19
|
+
* `@ampcode/plugin` contract). Runs under Bun's TypeScript runtime and
|
|
20
|
+
* owns advisory session-start auth, the sign-in notice, and post-tool
|
|
21
|
+
* activity. Its `tool.call` handler gates only the calls the delegate
|
|
22
|
+
* will not see (delegate not registered, or an earlier rule matches the
|
|
23
|
+
* tool first), so each call is checked once.
|
|
22
24
|
*
|
|
23
25
|
* We model the `@ampcode/plugin` API surface locally (the plugin package
|
|
24
26
|
* takes no harness SDK dependency — see AGENTS.md). The shapes mirror the
|
|
25
27
|
* binary's `PluginEventMap` / `PluginEventContext` exactly.
|
|
26
28
|
*/
|
|
27
29
|
/**
|
|
28
|
-
* JSON
|
|
30
|
+
* JSON object the delegate decides on.
|
|
29
31
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
32
|
+
* Under Amp's delegate contract this is the tool parameters themselves
|
|
33
|
+
* (for example `{"cmd":"ls -la"}`), and the tool name and thread come from
|
|
34
|
+
* `AGENT_TOOL_NAME` and `AMP_THREAD_ID`. The named fields below are read only
|
|
35
|
+
* when `AGENT_TOOL_NAME` is absent: the in-process `tool.call` handler passes
|
|
36
|
+
* them, and they keep older payload shapes working. A missing tool name
|
|
37
|
+
* resolves to "unknown".
|
|
35
38
|
*/
|
|
36
39
|
export interface AmpDelegateInput {
|
|
37
40
|
/** Tool being invoked (canonical: `tool`). */
|
|
@@ -73,9 +76,10 @@ export interface AmpThreadRef {
|
|
|
73
76
|
}
|
|
74
77
|
/**
|
|
75
78
|
* The result an in-process `tool.call` handler can return to influence a
|
|
76
|
-
* tool invocation.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
+
* tool invocation. The plugin returns `reject-and-continue` only for calls it
|
|
80
|
+
* gates itself, which are the calls the delegate will not see; otherwise it
|
|
81
|
+
* returns `allow` and leaves the decision to the delegate. The type is
|
|
82
|
+
* modeled in full to match `@ampcode/plugin`.
|
|
79
83
|
*/
|
|
80
84
|
export type AmpToolCallResult = {
|
|
81
85
|
action: "allow";
|
|
@@ -130,13 +134,19 @@ export interface AmpAgentEndEvent {
|
|
|
130
134
|
messages?: unknown[];
|
|
131
135
|
[key: string]: unknown;
|
|
132
136
|
}
|
|
137
|
+
/** Amp's UI helpers (`ctx.ui`); only `notify` is used by this plugin. */
|
|
138
|
+
export interface AmpPluginUi {
|
|
139
|
+
/** Show a notification to the user (ampcode.com/docs/plugin-api). */
|
|
140
|
+
notify?: (message: string) => Promise<void> | void;
|
|
141
|
+
[key: string]: unknown;
|
|
142
|
+
}
|
|
133
143
|
/**
|
|
134
144
|
* Context (`PluginEventContext`) passed as the SECOND argument to every
|
|
135
145
|
* handler. Carries Amp's UI helpers, a shell runner (`$`), etc. Modeled as
|
|
136
|
-
* an open object
|
|
137
|
-
* not depend on any specific context member.
|
|
146
|
+
* an open object; the plugin uses only `ui.notify`, and treats it as optional.
|
|
138
147
|
*/
|
|
139
148
|
export interface AmpPluginEventContext {
|
|
149
|
+
ui?: AmpPluginUi;
|
|
140
150
|
[key: string]: unknown;
|
|
141
151
|
}
|
|
142
152
|
/**
|