@ory/antigravity 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
@@ -14,9 +14,11 @@ One command installs two independent halves:
14
14
  ## What you'll need
15
15
 
16
16
  - [Google Antigravity](https://antigravity.google) installed (the `agy` CLI and/or the IDE)
17
+ <!-- BEGIN GENERATED requirements -->
17
18
  - Node.js **22 or newer**
18
19
  - [Docker](https://docs.docker.com/get-docker/) — only if you want to run Ory locally
19
20
  - macOS or Linux (Windows works via WSL2)
21
+ <!-- END GENERATED requirements -->
20
22
 
21
23
  ## Get started
22
24
 
@@ -88,9 +90,11 @@ Once you connect to Ory Agent Security, two more things happen automatically:
88
90
 
89
91
  If Ory is ever unreachable, the plugin gets out of the way and lets the agent keep working — so it can't lock you out.
90
92
 
91
- The plugin hooks into these Antigravity lifecycle events: `SessionStart` (check who's signed in), `PreToolUse` (authorize the tool), `PostToolUse` (record it), `Notification`, and `SessionEnd`.
93
+ The plugin hooks into these Antigravity lifecycle events: `SessionStart` (check who's signed in), `PreToolUse` (authorize the tool), `PostToolUse` (record it), and `Stop` (record the end of the run). Antigravity's hook payload doesn't name the event, so each registration in the generated `hooks.json` passes the event name to the hook as an argument. If you installed an earlier version, reinstall to regenerate `hooks.json`. Until then, tool calls are still checked: a payload with a tool call and no result is treated as `PreToolUse`, but sign-in and activity recording for the other events wait for the reinstall.
92
94
 
93
- > **A note on how Antigravity blocks.** Antigravity blocks a tool unless the plugin explicitly says "allow" — so a crash, timeout, or missing answer *blocks* the tool. That's the opposite of most harnesses. To keep Ory from ever getting in your way, the plugin **always allows on any internal or network error**, so a transient Ory outage never wedges your tools. Native tools are allowed unless an explicit block matches.
95
+ If browser sign-in is declined or fails when a session starts, the session still starts. Antigravity shows you a message that Ory sign-in didn't complete and that tool calls may be denied, and the agent is told to suggest a new session and sign-in if Ory denies a tool call.
96
+
97
+ > **A note on how Antigravity decides.** Antigravity expects an explicit `decision` from every `PreToolUse` hook. The plugin answers `"allow"` or `"deny"` with a reason, and keeps Ory from ever getting in your way: on any internal plugin error it still answers `"allow"`, so a plugin crash never wedges your tools. Native tools are allowed unless an explicit block matches.
94
98
 
95
99
  > **MCP tools (unverified).** Antigravity's hook payload for MCP calls is not documented. The plugin assumes they arrive as a `call_mcp_tool` tool whose arguments name the server and tool (`server_name` / `tool_name`, or the camel- and Pascal-case forms) and then checks `McpServer:<server>` and `McpTool:<server>:<tool>`. That shape has not been confirmed against a live Antigravity build. Any other MCP call shape — and a `call_mcp_tool` call without both names — is checked as an ordinary native tool, so MCP server and tool rules do not apply to it.
96
100
 
@@ -119,6 +123,7 @@ Then a denied tool is actually blocked and Antigravity shows why (the `deny_reas
119
123
 
120
124
  ## Connect to Ory Agent Security
121
125
 
126
+ <!-- BEGIN GENERATED connect -->
122
127
  Copy the connection details from the [Ory Console](https://console.ory.sh) under **Agent Security**:
123
128
 
124
129
  | Value | Flag | Environment variable |
@@ -142,6 +147,7 @@ npx -y -p @ory/antigravity ory-agy configure \
142
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.
143
148
 
144
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 -->
145
151
 
146
152
  ## Commands
147
153
 
@@ -160,14 +166,17 @@ All prefixed with `npx -y -p @ory/antigravity`.
160
166
 
161
167
  ## Troubleshooting
162
168
 
163
- - **`/ory:local-up` fails** — make sure Docker is running and ports `4000`, `4455`, and `16686` are free.
169
+ - **`/ory:local-up` fails** — <!-- BEGIN GENERATED local-stack-ports -->make sure Docker is running and ports `4000`, `4100`, and `4455` are free.<!-- END GENERATED local-stack-ports -->
164
170
  - **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.
165
171
  - **Running an older CLI than expected** — `npx -p @ory/antigravity` (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/antigravity ory-agy version`. To force the current release, clear the cache and reinstall: `rm -rf ~/.npm/_npx` then `npx -y -p @ory/antigravity ory-agy install`. Pinning an exact version (`@ory/antigravity@<version>`) also bypasses the cached copy.
166
- - **A tool was unexpectedly blocked** — because Antigravity blocks by default, first confirm the hook is answering: set `ORY_AGENT_DEBUG=true` and check the logs for hook errors. Then verify the user has `use` on the tool with `permissions`.
172
+ - **A tool was unexpectedly blocked** — first confirm the hook is answering: set `ORY_AGENT_DEBUG=true` and check the logs for hook errors. Then verify the user has `use` on the tool with `permissions`.
173
+ - **No sign-in prompt or missing activity** — open `hooks.json` and confirm each Ory hook command ends with its event name (for example `... PreToolUse`). A `hooks.json` written by an earlier version lacks it; reinstall with `npx -y -p @ory/antigravity ory-agy install`.
167
174
 
168
175
  ## Learn more
169
176
 
177
+ <!-- BEGIN GENERATED ory-links -->
170
178
  - [Ory documentation](https://www.ory.com/docs/) · [Ory Console](https://console.ory.sh) · [Ory Elements](https://github.com/ory/elements)
179
+ <!-- END GENERATED ory-links -->
171
180
  - [Google Antigravity](https://antigravity.google)
172
181
 
173
182
  ## License
@@ -10,14 +10,17 @@
10
10
  * skills/ Ory skill playbooks (SKILL.md trees)
11
11
  * commands/<ns>/ TOML slash commands
12
12
  *
13
- * Verified against `agy 1.0.13`: `agy plugin validate <dir>` accepts this
14
- * layout and reports `hooks`, `mcpServers`, `skills`, and `commands` as
15
- * recognized components.
13
+ * `agy plugin validate <dir>` (1.0.13 and 1.1.10) accepts this layout and
14
+ * reports `hooks`, `mcpServers`, `skills`, and `commands` as recognized
15
+ * components.
16
16
  *
17
- * hooks.json shape (verified): top-level rule id → event name → array of
18
- * `{ matcher, hooks: [{ type, command, timeout }] }`.
17
+ * hooks.json shape (https://antigravity.google/docs/hooks): top-level rule
18
+ * id → event name → handlers. `PreToolUse` / `PostToolUse` take
19
+ * `[{ matcher, hooks: [{ type, command, timeout }] }]`; `SessionStart`,
20
+ * `PreInvocation`, `PostInvocation`, and `Stop` take the handler list
21
+ * directly, `[{ type, command, timeout }]`.
19
22
  */
20
- import { type PreparedRuntime } from "@ory/argus";
23
+ import { type PreparedRuntime } from "@ory/argus/install";
21
24
  /** Plugin / rule / MCP-server id. */
22
25
  export declare const PLUGIN_NAME = "ory";
23
26
  /**
@@ -25,9 +28,10 @@ export declare const PLUGIN_NAME = "ory";
25
28
  * `agy plugin install` path in `main.ts` and the manual `.agents` fallback in
26
29
  * `setup.ts`) go through here so they wire the same runtime.
27
30
  *
28
- * Antigravity **fails closed**: a hook that crashes or answers with malformed
29
- * output blocks the tool. So the shim's runtime-missing path has to emit an
30
- * explicit allow, matching what the hook itself returns on every error path.
31
+ * `decision` is required on `PreToolUse`, so the shim's runtime-missing path
32
+ * emits an explicit allow, matching what the hook itself returns on its error
33
+ * paths. The shim cannot see the event, so the same answer goes to every
34
+ * event; `allow_tool` keeps older `agy` builds allowing too.
31
35
  */
32
36
  export declare function wireAntigravityRuntime(args: readonly string[]): PreparedRuntime;
33
37
  /**
@@ -11,12 +11,15 @@
11
11
  * skills/ Ory skill playbooks (SKILL.md trees)
12
12
  * commands/<ns>/ TOML slash commands
13
13
  *
14
- * Verified against `agy 1.0.13`: `agy plugin validate <dir>` accepts this
15
- * layout and reports `hooks`, `mcpServers`, `skills`, and `commands` as
16
- * recognized components.
14
+ * `agy plugin validate <dir>` (1.0.13 and 1.1.10) accepts this layout and
15
+ * reports `hooks`, `mcpServers`, `skills`, and `commands` as recognized
16
+ * components.
17
17
  *
18
- * hooks.json shape (verified): top-level rule id → event name → array of
19
- * `{ matcher, hooks: [{ type, command, timeout }] }`.
18
+ * hooks.json shape (https://antigravity.google/docs/hooks): top-level rule
19
+ * id → event name → handlers. `PreToolUse` / `PostToolUse` take
20
+ * `[{ matcher, hooks: [{ type, command, timeout }] }]`; `SessionStart`,
21
+ * `PreInvocation`, `PostInvocation`, and `Stop` take the handler list
22
+ * directly, `[{ type, command, timeout }]`.
20
23
  */
21
24
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
22
25
  if (k2 === undefined) k2 = k;
@@ -59,6 +62,7 @@ exports.uninstallAntigravityOryAssets = uninstallAntigravityOryAssets;
59
62
  const fs = __importStar(require("node:fs"));
60
63
  const path = __importStar(require("node:path"));
61
64
  const argus_1 = require("@ory/argus");
65
+ const install_1 = require("@ory/argus/install");
62
66
  const PACKAGE_NAME = "@ory/antigravity";
63
67
  /** Plugin / rule / MCP-server id. */
64
68
  exports.PLUGIN_NAME = "ory";
@@ -68,18 +72,19 @@ const PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
68
72
  * `agy plugin install` path in `main.ts` and the manual `.agents` fallback in
69
73
  * `setup.ts`) go through here so they wire the same runtime.
70
74
  *
71
- * Antigravity **fails closed**: a hook that crashes or answers with malformed
72
- * output blocks the tool. So the shim's runtime-missing path has to emit an
73
- * explicit allow, matching what the hook itself returns on every error path.
75
+ * `decision` is required on `PreToolUse`, so the shim's runtime-missing path
76
+ * emits an explicit allow, matching what the hook itself returns on its error
77
+ * paths. The shim cannot see the event, so the same answer goes to every
78
+ * event; `allow_tool` keeps older `agy` builds allowing too.
74
79
  */
75
80
  function wireAntigravityRuntime(args) {
76
- return (0, argus_1.wireRuntime)({
81
+ return (0, install_1.wireRuntime)({
77
82
  harness: "antigravity",
78
83
  packageName: PACKAGE_NAME,
79
84
  packageRoot: PACKAGE_ROOT,
80
85
  installCommand: "npx -y -p @ory/antigravity ory-agy install",
81
86
  args,
82
- fallbackStdout: JSON.stringify({ allow_tool: true }),
87
+ fallbackStdout: JSON.stringify({ decision: "allow", allow_tool: true }),
83
88
  });
84
89
  }
85
90
  const RENDER_OPTS = {
@@ -91,22 +96,21 @@ const RENDER_OPTS = {
91
96
  * namespace, so `commands/ory/local-up.toml` is exposed as `/ory:local-up`.
92
97
  */
93
98
  const CMD_SUBDIR = "ory";
94
- /** Read the plugin's own version, walking up from dist/cli to the root. */
95
- function readPackageVersion() {
96
- const pkgPath = path.resolve(__dirname, "..", "..", "package.json");
97
- const parsed = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
98
- if (!parsed.version)
99
- throw new Error(`Could not read version from ${pkgPath}`);
100
- return parsed.version;
101
- }
102
99
  /**
103
100
  * Render hooks.json. The command points at the runtime shim resolved at
104
- * install time, so no package resolution happens per tool call.
105
- * `matcher: ".*"` matches every tool name on the tool events.
101
+ * install time, so no package resolution happens per tool call. Antigravity's
102
+ * payload does not name the event, so each registration passes the event name
103
+ * as the command's first argument. `matcher: ".*"` matches every tool name on
104
+ * the tool events; the other events take a bare handler list.
106
105
  */
107
106
  function renderHooks(command) {
108
- const entry = (matcher, timeout) => [
109
- { matcher, hooks: [{ type: "command", command, timeout }] },
107
+ const handler = (event, timeout) => ({
108
+ type: "command",
109
+ command: `${command} ${event}`,
110
+ timeout,
111
+ });
112
+ const toolEntry = (event, timeout) => [
113
+ { matcher: ".*", hooks: [handler(event, timeout)] },
110
114
  ];
111
115
  // Antigravity's hook timeout is in SECONDS and it *validates* the value —
112
116
  // "timeout must be between 5 and 120 seconds". The previous 10000/5000 were
@@ -117,11 +121,10 @@ function renderHooks(command) {
117
121
  const toolSec = (0, argus_1.toolHookTimeout)("antigravity", "seconds");
118
122
  return {
119
123
  [exports.PLUGIN_NAME]: {
120
- SessionStart: entry(".*", sessionStartSec),
121
- SessionEnd: entry(".*", toolSec),
122
- PreToolUse: entry(".*", toolSec),
123
- PostToolUse: entry(".*", toolSec),
124
- Notification: entry(".*", toolSec),
124
+ SessionStart: [handler("SessionStart", sessionStartSec)],
125
+ PreToolUse: toolEntry("PreToolUse", toolSec),
126
+ PostToolUse: toolEntry("PostToolUse", toolSec),
127
+ Stop: [handler("Stop", toolSec)],
125
128
  },
126
129
  };
127
130
  }
@@ -178,22 +181,22 @@ function isOryManifest(manifest) {
178
181
  * path is used everywhere.)
179
182
  */
180
183
  function installAntigravityOryAssets(root, runtime) {
181
- const version = readPackageVersion();
184
+ const version = (0, install_1.requirePackageVersion)(PACKAGE_ROOT);
182
185
  fs.mkdirSync(root, { recursive: true });
183
186
  const skillsDir = path.join(root, "skills");
184
- (0, argus_1.removeSkillDirs)(skillsDir, argus_1.ORY_SKILL_NAMES);
185
- (0, argus_1.writeSkillTree)(skillsDir, (0, argus_1.renderOrySkills)("antigravity", RENDER_OPTS));
187
+ (0, install_1.removeSkillDirs)(skillsDir, install_1.ORY_SKILL_NAMES);
188
+ (0, install_1.writeSkillTree)(skillsDir, (0, install_1.renderOrySkills)("antigravity", RENDER_OPTS));
186
189
  const cmdDir = path.join(root, "commands", CMD_SUBDIR);
187
190
  fs.rmSync(cmdDir, { recursive: true, force: true });
188
191
  fs.mkdirSync(cmdDir, { recursive: true });
189
- for (const cmd of (0, argus_1.renderOryCommands)("antigravity", RENDER_OPTS)) {
190
- fs.writeFileSync(path.join(cmdDir, `${cmd.slug}.toml`), (0, argus_1.commandToToml)(cmd));
192
+ for (const cmd of (0, install_1.renderOryCommands)("antigravity", RENDER_OPTS)) {
193
+ fs.writeFileSync(path.join(cmdDir, `${cmd.slug}.toml`), (0, install_1.commandToToml)(cmd));
191
194
  }
192
195
  // hooks.json is keyed by rule id — replace only the "ory" rule and keep
193
196
  // any rules the user has defined alongside it.
194
197
  const hooksPath = path.join(root, "hooks.json");
195
198
  const hooks = readJsonObject(hooksPath) ?? {};
196
- hooks[exports.PLUGIN_NAME] = renderHooks((0, argus_1.requireHookCommand)(runtime))[exports.PLUGIN_NAME];
199
+ hooks[exports.PLUGIN_NAME] = renderHooks((0, install_1.requireHookCommand)(runtime))[exports.PLUGIN_NAME];
197
200
  writeJson(hooksPath, hooks);
198
201
  // mcp_config.json — replace only the Ory server entry under `mcpServers`,
199
202
  // preserving other servers and any unrelated top-level keys. Skipped when
@@ -219,16 +222,6 @@ function installAntigravityOryAssets(root, runtime) {
219
222
  console.warn(`Warning: ${manifestPath} exists and is not the Ory plugin manifest; leaving it untouched.`);
220
223
  }
221
224
  }
222
- function safeRmEmpty(dir) {
223
- try {
224
- if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {
225
- fs.rmdirSync(dir);
226
- }
227
- }
228
- catch {
229
- /* leave the dir if removal fails */
230
- }
231
- }
232
225
  /**
233
226
  * Remove every Ory skill, command, and bundle entry written under `root`.
234
227
  *
@@ -240,18 +233,18 @@ function safeRmEmpty(dir) {
240
233
  function uninstallAntigravityOryAssets(root) {
241
234
  const skillsDir = path.join(root, "skills");
242
235
  if (fs.existsSync(skillsDir)) {
243
- (0, argus_1.removeSkillDirs)(skillsDir, argus_1.ORY_SKILL_NAMES);
244
- safeRmEmpty(skillsDir);
236
+ (0, install_1.removeSkillDirs)(skillsDir, install_1.ORY_SKILL_NAMES);
237
+ (0, install_1.removeDirIfEmpty)(skillsDir);
245
238
  }
246
239
  const cmdDir = path.join(root, "commands", CMD_SUBDIR);
247
240
  if (fs.existsSync(cmdDir)) {
248
- for (const slug of argus_1.ORY_COMMAND_SLUGS) {
241
+ for (const slug of install_1.ORY_COMMAND_SLUGS) {
249
242
  const f = path.join(cmdDir, `${slug}.toml`);
250
243
  if (fs.existsSync(f))
251
244
  fs.unlinkSync(f);
252
245
  }
253
- safeRmEmpty(cmdDir);
254
- safeRmEmpty(path.join(root, "commands"));
246
+ (0, install_1.removeDirIfEmpty)(cmdDir);
247
+ (0, install_1.removeDirIfEmpty)(path.join(root, "commands"));
255
248
  }
256
249
  // hooks.json — drop only the Ory rule id.
257
250
  const hooksPath = path.join(root, "hooks.json");
package/dist/cli/main.js CHANGED
@@ -47,7 +47,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
47
47
  const path = __importStar(require("node:path"));
48
48
  const fs = __importStar(require("node:fs"));
49
49
  const node_child_process_1 = require("node:child_process");
50
- const argus_1 = require("@ory/argus");
50
+ const cli_1 = require("@ory/argus/cli");
51
51
  const assets_js_1 = require("./assets.js");
52
52
  /** Bundle dir handed to `agy plugin install`. */
53
53
  const BUNDLE_DIR = path.resolve(__dirname, "..", "..", "antigravity-plugin");
@@ -59,87 +59,6 @@ const SPAWN_VIA_SHELL = process.platform === "win32";
59
59
  function agyAvailable() {
60
60
  return ((0, node_child_process_1.spawnSync)(AGY, ["--version"], { stdio: "pipe", shell: SPAWN_VIA_SHELL }).status === 0);
61
61
  }
62
- function main() {
63
- const [command, ...args] = process.argv.slice(2);
64
- // `--help` after a matched subcommand: print usage, do nothing else.
65
- // Without this the switch below ignores the flag and `install --help`
66
- // performs a real install (#221).
67
- if ((0, argus_1.shouldPrintHelp)(command, args))
68
- return help();
69
- switch (command) {
70
- case "install":
71
- if (args.includes("--print")) {
72
- process.argv = ["node", "setup.js", ...args];
73
- require("./setup.js");
74
- break;
75
- }
76
- (0, argus_1.beginDeferNextSteps)();
77
- install(args);
78
- (0, argus_1.runPostInstall)("ory-agy", "antigravity", args).then(() => process.exit(0), (err) => {
79
- console.error(err.message ?? err);
80
- process.exit(1);
81
- });
82
- break;
83
- case "uninstall":
84
- const antigravityUninstalled = uninstall(args);
85
- (0, argus_1.clearCredentialsForUninstall)({
86
- harness: "antigravity",
87
- purge: args.includes("--purge"),
88
- }).then(() => process.exit(antigravityUninstalled ? 0 : 1), (err) => {
89
- console.error(err.message ?? err);
90
- process.exit(1);
91
- });
92
- break;
93
- case "configure":
94
- (0, argus_1.runConfigureCommand)("ory-agy", args);
95
- break;
96
- case "agent":
97
- (0, argus_1.runAgentCommand)("ory-agy", "antigravity", args).then((code) => process.exit(code), (err) => {
98
- console.error(err.message ?? err);
99
- process.exit(1);
100
- });
101
- break;
102
- case "permissions":
103
- (0, argus_1.runPermissionsCommand)("ory-agy", "antigravity", args).then((code) => process.exit(code), (err) => {
104
- console.error(err.message ?? err);
105
- process.exit(1);
106
- });
107
- break;
108
- case "setup":
109
- require("./setup.js");
110
- break;
111
- case "status":
112
- status().then(() => process.exit(0), (err) => {
113
- console.error(err.message ?? err);
114
- process.exit(1);
115
- });
116
- break;
117
- case "watch":
118
- (0, argus_1.runWatchCommand)("ory-agy", "antigravity", args).then((code) => process.exit(code), (err) => { console.error(err.message ?? err); process.exit(1); });
119
- break;
120
- case "local":
121
- (0, argus_1.runLocalCommand)("ory-agy", args).catch((err) => {
122
- console.error(err.message ?? err);
123
- process.exit(1);
124
- });
125
- break;
126
- case "version":
127
- case "--version":
128
- case "-v":
129
- process.exit((0, argus_1.runVersionCommand)("ory-agy", args, { packageRoot: PACKAGE_ROOT }));
130
- break;
131
- case "help":
132
- case "--help":
133
- case "-h":
134
- case undefined:
135
- help();
136
- break;
137
- default:
138
- console.error(`Unknown command: ${command}`);
139
- help();
140
- process.exit(1);
141
- }
142
- }
143
62
  function install(args) {
144
63
  // Resolve the runtime first: the bundle's hooks.json / mcp_config.json point
145
64
  // at the shims it writes.
@@ -164,7 +83,7 @@ function install(args) {
164
83
  console.log("");
165
84
  console.log("Ory plugin installed.");
166
85
  printQuickstart();
167
- (0, argus_1.printEnvHelp)("ory-agy");
86
+ (0, cli_1.printEnvHelp)("ory-agy");
168
87
  return;
169
88
  }
170
89
  console.error("");
@@ -204,7 +123,7 @@ function printQuickstart() {
204
123
  console.log(" 3. Set ORY_OAUTH2_CLIENT_ID so the per-session PKCE browser login can complete.");
205
124
  }
206
125
  async function status() {
207
- await (0, argus_1.runStatusCommand)("ory-agy", "antigravity", {
126
+ await (0, cli_1.runStatusCommand)("ory-agy", "antigravity", {
208
127
  title: "Google Antigravity",
209
128
  printPluginSection: () => {
210
129
  console.log("Plugin bundle:");
@@ -246,4 +165,16 @@ Examples:
246
165
  npx -y -p @ory/antigravity ory-agy uninstall # Remove plugin
247
166
  `);
248
167
  }
249
- main();
168
+ (0, cli_1.runHarnessCli)({
169
+ bin: "ory-agy",
170
+ harness: "antigravity",
171
+ packageRoot: PACKAGE_ROOT,
172
+ help,
173
+ install,
174
+ printInstallPlan: manualSetup,
175
+ uninstall,
176
+ setup: () => {
177
+ require("./setup.js");
178
+ },
179
+ status: () => status(),
180
+ });
package/dist/cli/setup.js CHANGED
@@ -50,17 +50,18 @@ var __importStar = (this && this.__importStar) || (function () {
50
50
  Object.defineProperty(exports, "__esModule", { value: true });
51
51
  const fs = __importStar(require("node:fs"));
52
52
  const path = __importStar(require("node:path"));
53
- const argus_1 = require("@ory/argus");
53
+ const cli_1 = require("@ory/argus/cli");
54
+ const install_1 = require("@ory/argus/install");
54
55
  const assets_js_1 = require("./assets.js");
55
56
  function getAgentsDir(args) {
56
57
  return path.join(args.projectDir, ".agents");
57
58
  }
58
59
  function main() {
59
60
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
60
- (0, argus_1.printSetupHelp)("ory-agy-setup", "Google Antigravity");
61
+ (0, install_1.printSetupHelp)("ory-agy-setup", "Google Antigravity");
61
62
  process.exit(0);
62
63
  }
63
- const args = (0, argus_1.parseSetupArgs)();
64
+ const args = (0, install_1.parseSetupArgs)();
64
65
  const agentsDir = getAgentsDir(args);
65
66
  if (args.print) {
66
67
  console.log(`Would write the Ory plugin bundle to ${agentsDir}:`);
@@ -75,22 +76,22 @@ function main() {
75
76
  else {
76
77
  console.log("No .agents directory found. Skipping manual bundle cleanup.");
77
78
  }
78
- (0, argus_1.removeRuntimeWiring)("antigravity");
79
- for (const pruned of (0, argus_1.pruneRuntimeStores)()) {
79
+ (0, install_1.removeRuntimeWiring)("antigravity");
80
+ for (const pruned of (0, install_1.pruneRuntimeStores)()) {
80
81
  console.log(` Removed runtime: ${pruned}`);
81
82
  }
82
83
  return;
83
84
  }
84
85
  (0, assets_js_1.installAntigravityOryAssets)(agentsDir, (0, assets_js_1.wireAntigravityRuntime)(process.argv.slice(2)));
85
86
  console.log(`Ory plugin bundle installed to ${agentsDir}`);
86
- (0, argus_1.printNextSteps)("Google Antigravity", "npx -y -p @ory/antigravity ory-agy-setup --uninstall", { binName: "ory-agy", harness: "antigravity" });
87
+ (0, install_1.printNextSteps)("Google Antigravity", "npx -y -p @ory/antigravity ory-agy-setup --uninstall", { binName: "ory-agy", harness: "antigravity" });
87
88
  }
88
89
  main();
89
90
  // When invoked directly as the `-setup` bin with `--uninstall`, also clear
90
91
  // stored Ory credentials. When required by the plugin's main CLI, that
91
92
  // command owns the purge, so the `require.main` guard prevents a double run.
92
93
  if (require.main === module && process.argv.includes("--uninstall")) {
93
- (0, argus_1.clearCredentialsForUninstall)({
94
+ (0, cli_1.clearCredentialsForUninstall)({
94
95
  harness: "antigravity",
95
96
  purge: process.argv.includes("--purge"),
96
97
  }).then(() => process.exit(0), (err) => {
@@ -1,16 +1,51 @@
1
1
  import { OryAgentClient, ensureUserAuthenticated, ensureAgentIdentity } from "@ory/argus";
2
- import type { AntigravityHookInput, AntigravityHookOutput } from "./types.js";
2
+ import { type AntigravityHookEvent, type AntigravityHookInput, type AntigravityHookOutput, type AntigravityInjectedStep } from "./types.js";
3
+ /**
4
+ * Explicit allow. `decision` is required on `PreToolUse`; `allow_tool` is the
5
+ * older spelling for earlier `agy` builds.
6
+ */
7
+ export declare const ALLOW: AntigravityHookOutput;
3
8
  export interface HandleHookEventDeps {
4
9
  /** Test injection point for the user login flow. */
5
10
  userLogin?: typeof ensureUserAuthenticated;
6
11
  /** Test injection point for the agent identity gate. */
7
12
  agentGate?: typeof ensureAgentIdentity;
8
13
  }
14
+ export interface HandleHookEventOptions extends HandleHookEventDeps {
15
+ /**
16
+ * Event name from the hook command's argument. Antigravity's payload does
17
+ * not name the event, so the generated hooks.json passes it as argv.
18
+ */
19
+ event?: string;
20
+ }
21
+ /** Payload fields the handlers use, read from any accepted payload shape. */
22
+ interface NormalizedInput {
23
+ event: AntigravityHookEvent | string | undefined;
24
+ sessionId: string | undefined;
25
+ modelName?: string;
26
+ source?: string;
27
+ toolName?: string;
28
+ toolArgs?: Record<string, unknown>;
29
+ toolError?: unknown;
30
+ toolResult?: unknown;
31
+ stopReason?: string;
32
+ }
33
+ /**
34
+ * Resolve the event and the fields the handlers need. Accepts the documented
35
+ * flat camelCase payload, the protobuf-style `common` + `*HookArgs` wrapper,
36
+ * and the snake_case payload of older `agy` builds.
37
+ */
38
+ export declare function normalizeInput(input: AntigravityHookInput, argvEvent?: string): NormalizedInput;
39
+ /**
40
+ * Route an Antigravity hook event. The event comes from the hook command's
41
+ * argument (`options.event`), falling back to the payload for older installs.
42
+ */
43
+ export declare const handleHookEvent: ((input: AntigravityHookInput, client: OryAgentClient, options?: HandleHookEventOptions) => Promise<AntigravityHookOutput>) & {
44
+ events: readonly string[];
45
+ };
9
46
  /**
10
- * Route an Antigravity hook event to the appropriate Ory integration.
11
- *
12
- * Note: on `PreToolUse` the returned output ALWAYS sets `allow_tool`
13
- * explicitly — Antigravity blocks the tool otherwise. All other events
14
- * return `ALLOW` (harmless) or an empty/system-message output.
47
+ * Steps telling the user and the model that sign-in did not complete. The
48
+ * session still starts; enforcement happens at tool-call time.
15
49
  */
16
- export declare function handleHookEvent(input: AntigravityHookInput, client: OryAgentClient, deps?: HandleHookEventDeps): Promise<AntigravityHookOutput>;
50
+ export declare function signInFailureSteps(reason: string): AntigravityInjectedStep[];
51
+ export {};
package/dist/handlers.js CHANGED
@@ -1,131 +1,200 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleHookEvent = handleHookEvent;
3
+ exports.handleHookEvent = exports.ALLOW = void 0;
4
+ exports.normalizeInput = normalizeInput;
5
+ exports.signInFailureSteps = signInFailureSteps;
4
6
  const argus_1 = require("@ory/argus");
7
+ const types_js_1 = require("./types.js");
5
8
  const HARNESS = "antigravity";
6
- /** Allow a tool through (fail-closed harness ⇒ always be explicit). */
7
- const ALLOW = { allow_tool: true };
8
9
  /**
9
- * Route an Antigravity hook event to the appropriate Ory integration.
10
- *
11
- * Note: on `PreToolUse` the returned output ALWAYS sets `allow_tool`
12
- * explicitly — Antigravity blocks the tool otherwise. All other events
13
- * return `ALLOW` (harmless) or an empty/system-message output.
10
+ * Explicit allow. `decision` is required on `PreToolUse`; `allow_tool` is the
11
+ * older spelling for earlier `agy` builds.
14
12
  */
15
- async function handleHookEvent(input, client, deps = {}) {
16
- const event = input.hook_event_name;
17
- client.logger.debug("hook.received", {
13
+ exports.ALLOW = { decision: "allow", allow_tool: true };
14
+ const ONEOF_EVENTS = [
15
+ ["sessionStartHookArgs", "SessionStart"],
16
+ ["preToolHookArgs", "PreToolUse"],
17
+ ["postToolHookArgs", "PostToolUse"],
18
+ ["preInvocationHookArgs", "PreInvocation"],
19
+ ["postInvocationHookArgs", "PostInvocation"],
20
+ ["stopHookArgs", "Stop"],
21
+ ];
22
+ function asRecord(value) {
23
+ return value && typeof value === "object" && !Array.isArray(value)
24
+ ? value
25
+ : undefined;
26
+ }
27
+ function asString(value) {
28
+ return typeof value === "string" && value !== "" ? value : undefined;
29
+ }
30
+ /**
31
+ * Resolve the event and the fields the handlers need. Accepts the documented
32
+ * flat camelCase payload, the protobuf-style `common` + `*HookArgs` wrapper,
33
+ * and the snake_case payload of older `agy` builds.
34
+ */
35
+ function normalizeInput(input, argvEvent) {
36
+ const common = asRecord(input.common) ?? {};
37
+ const oneof = ONEOF_EVENTS.find(([key]) => asRecord(input[key]) !== undefined);
38
+ const args = (oneof ? asRecord(input[oneof[0]]) : undefined) ?? {};
39
+ const pick = (key) => input[key] ?? args[key] ?? common[key];
40
+ const toolCall = asRecord(pick("toolCall"));
41
+ const error = asString(pick("error"));
42
+ const result = pick("result");
43
+ // A hooks.json written before the event argument existed gives no event
44
+ // name, and the flat payload has no event field. A tool call with no result
45
+ // or error can only be PreToolUse, so gate it rather than let it through.
46
+ const inferredEvent = toolCall && result === undefined && error === undefined ? "PreToolUse" : undefined;
47
+ const event = asString(argvEvent) ?? asString(input.hook_event_name) ?? oneof?.[1] ?? inferredEvent;
48
+ const legacyError = input.tool_error !== undefined && input.tool_error !== null && input.tool_error !== ""
49
+ ? input.tool_error
50
+ : undefined;
51
+ return {
18
52
  event,
19
- sessionId: input.session_id,
20
- toolName: input.tool_name,
21
- });
22
- return (0, argus_1.withHookContext)(client, { sessionId: input.session_id }, async () => {
23
- switch (event) {
24
- case "SessionStart":
25
- return await handleSessionStart(input, client, deps);
26
- case "PreToolUse":
27
- return await handlePreToolUse(input, client);
28
- case "PostToolUse":
29
- return await handlePostToolUse(input, client);
30
- case "Notification":
31
- return handleNotification(input, client);
32
- case "Stop":
33
- case "SessionEnd":
34
- return handleSessionEnd(input, client);
35
- default:
36
- client.logger.debug("hook.passthrough", { event });
37
- client.logger.activity("hook.passthrough", "skipped", {
38
- attributes: { event },
39
- });
40
- return ALLOW;
41
- }
42
- });
53
+ sessionId: asString(pick("conversationId")) ?? asString(input.session_id),
54
+ modelName: asString(pick("modelName")) ?? asString(input.model),
55
+ source: asString(input.source),
56
+ toolName: asString(toolCall?.name) ?? asString(input.tool_name),
57
+ toolArgs: asRecord(toolCall?.args) ?? asRecord(input.tool_input),
58
+ toolError: error ?? legacyError,
59
+ toolResult: result ?? input.tool_response,
60
+ stopReason: asString(pick("terminationReason")) ?? asString(input.reason),
61
+ };
43
62
  }
63
+ /**
64
+ * Route an Antigravity hook event to the appropriate Ory integration.
65
+ *
66
+ * `PreToolUse` always answers with an explicit `decision`. Documented
67
+ * non-tool events answer `{}` (or `injectSteps` on SessionStart). Unknown
68
+ * events answer `ALLOW` so a misrouted tool call is never left without a
69
+ * decision.
70
+ */
71
+ const dispatchNormalized = (0, argus_1.createHookDispatcher)({
72
+ harness: HARNESS,
73
+ event: (input) => input.event,
74
+ sessionId: (input) => input.sessionId,
75
+ log: (input) => ({ sessionId: input.sessionId, toolName: input.toolName }),
76
+ routes: {
77
+ SessionStart: (input, client, options) => handleSessionStart(input, client, options),
78
+ PreToolUse: (input, client) => handlePreToolUse(input, client),
79
+ PostToolUse: (input, client) => handlePostToolUse(input, client),
80
+ Stop: (input, client) => handleStop(input, client),
81
+ },
82
+ // A documented non-tool event answers `{}`. An unknown one may be a tool
83
+ // call, so it gets an explicit allow.
84
+ passthrough: (input) => ((0, types_js_1.isAntigravityHookEvent)(input.event) ? {} : exports.ALLOW),
85
+ });
86
+ /**
87
+ * Route an Antigravity hook event. The event comes from the hook command's
88
+ * argument (`options.event`), falling back to the payload for older installs.
89
+ */
90
+ exports.handleHookEvent = Object.assign((input, client, options = {}) => dispatchNormalized(normalizeInput(input, options.event), client, options), { events: dispatchNormalized.events });
44
91
  // ─── SessionStart ───────────────────────────────────────────────────
92
+ /** Strip trailing periods and whitespace so the reason reads inside a sentence. */
93
+ function trimReason(reason) {
94
+ return reason.replace(/[.\s]+$/, "") || "unknown error";
95
+ }
96
+ /**
97
+ * Steps telling the user and the model that sign-in did not complete. The
98
+ * session still starts; enforcement happens at tool-call time.
99
+ */
100
+ function signInFailureSteps(reason) {
101
+ const r = trimReason(reason);
102
+ return [
103
+ {
104
+ errorMessage: {
105
+ userMessage: `Ory sign-in did not complete: ${r}. Tool calls may be denied this session.`,
106
+ },
107
+ },
108
+ {
109
+ systemMessage: {
110
+ systemMessage: `Ory Agent Security sign-in did not complete for this session (${r}). ` +
111
+ "If Ory denies a tool call, tell the user that starting a new session and signing in may resolve it. " +
112
+ "Do not retry the denied call.",
113
+ },
114
+ },
115
+ ];
116
+ }
45
117
  async function handleSessionStart(input, client, deps) {
46
118
  client.logger.info("lifecycle.session_start", {
47
- sessionId: input.session_id,
48
- model: input.model,
119
+ sessionId: input.sessionId,
120
+ model: input.modelName,
49
121
  source: input.source,
50
122
  });
51
- await (0, argus_1.sessionStart)(client, {
123
+ const result = await (0, argus_1.sessionStart)(client, {
52
124
  binName: "ory-agy",
53
125
  harness: HARNESS,
126
+ sessionId: input.sessionId,
54
127
  userLogin: deps.userLogin,
55
128
  agentGate: deps.agentGate,
56
- activityAttributes: { model: input.model, source: input.source },
129
+ activityAttributes: { model: input.modelName, source: input.source },
57
130
  });
131
+ if (result.userMode === "declined" || result.userMode === "error") {
132
+ return { injectSteps: signInFailureSteps(result.userReason) };
133
+ }
58
134
  return {};
59
135
  }
60
136
  // ─── PreToolUse ─────────────────────────────────────────────────────
61
137
  async function handlePreToolUse(input, client) {
62
- const toolName = input.tool_name ?? "unknown";
138
+ const toolName = input.toolName ?? "unknown";
63
139
  client.logger.info("lifecycle.pre_tool_use", {
64
- sessionId: input.session_id,
140
+ sessionId: input.sessionId,
65
141
  toolName,
66
- toolInput: input.tool_input,
142
+ toolInput: input.toolArgs,
67
143
  });
68
144
  const result = await (0, argus_1.gate)(client, {
69
145
  harness: HARNESS,
70
146
  toolName,
71
- toolArgs: input.tool_input,
72
- mcpTool: toolName === "call_mcp_tool" ? ((0, argus_1.parseMcpToolArgs)(input.tool_input) ?? undefined) : undefined,
73
- subjectFallback: `session:${input.session_id}`,
147
+ toolArgs: input.toolArgs,
148
+ mcpTool: toolName === "call_mcp_tool" ? ((0, argus_1.parseMcpToolArgs)(input.toolArgs) ?? undefined) : undefined,
149
+ subjectFallback: `session:${input.sessionId}`,
74
150
  });
75
151
  if (result.blocked) {
76
152
  return {
153
+ decision: "deny",
154
+ reason: result.denialMessage,
77
155
  allow_tool: false,
78
156
  deny_reason: result.denialMessage,
79
157
  };
80
158
  }
81
- return ALLOW;
159
+ return exports.ALLOW;
82
160
  }
83
161
  // ─── PostToolUse ────────────────────────────────────────────────────
84
- async function handlePostToolUse(input, client) {
85
- const toolName = input.tool_name ?? "unknown";
162
+ function handlePostToolUse(input, client) {
163
+ const toolName = input.toolName ?? "unknown";
86
164
  client.logger.info("lifecycle.post_tool_use", {
87
- sessionId: input.session_id,
165
+ sessionId: input.sessionId,
88
166
  toolName,
89
167
  });
90
- const failed = input.tool_error !== undefined && input.tool_error !== null;
91
- if (failed) {
92
- client.logger.debug("lifecycle.post_tool_use.error", { error: input.tool_error });
168
+ if (input.toolError !== undefined) {
169
+ client.logger.debug("lifecycle.post_tool_use.error", { error: input.toolError });
93
170
  (0, argus_1.fail)(client, {
94
171
  toolName,
95
- input: input.tool_input,
96
- error: input.tool_error,
172
+ input: input.toolArgs,
173
+ error: input.toolError,
97
174
  });
98
175
  return {};
99
176
  }
100
177
  (0, argus_1.complete)(client, {
101
178
  toolName,
102
- input: input.tool_input,
103
- output: input.tool_response,
179
+ input: input.toolArgs,
180
+ output: input.toolResult,
104
181
  });
105
182
  return {};
106
183
  }
107
- // PreInvocation / PostInvocation bracket each agent turn (not user
108
- // prompts). We don't model them specially — they fall through to the
109
- // default `hook.passthrough` activity event in handleHookEvent.
110
- // ─── Notification ───────────────────────────────────────────────────
111
- function handleNotification(input, client) {
112
- client.logger.info("lifecycle.notification", {
113
- sessionId: input.session_id,
114
- messageLen: input.message?.length,
115
- });
116
- client.logger.activity("user.interaction", "ok", {
117
- attributes: { harness: HARNESS, kind: "notification" },
118
- });
119
- return {};
120
- }
121
- // ─── Stop / SessionEnd ──────────────────────────────────────────────
122
- function handleSessionEnd(input, client) {
184
+ // PreInvocation / PostInvocation bracket each model call. They fall through
185
+ // to the default `hook.passthrough` activity event in handleHookEvent.
186
+ // ─── Stop ───────────────────────────────────────────────────────────
187
+ /**
188
+ * The execution loop ended. Answer `{}`: any `decision` other than
189
+ * `"continue"` lets the stop proceed.
190
+ */
191
+ function handleStop(input, client) {
123
192
  client.logger.info("lifecycle.session_end", {
124
- sessionId: input.session_id,
125
- reason: input.reason,
193
+ sessionId: input.sessionId,
194
+ reason: input.stopReason,
126
195
  });
127
196
  client.logger.activity("session.end", "ok", {
128
- attributes: { reason: input.reason },
197
+ attributes: { reason: input.stopReason },
129
198
  });
130
199
  return {};
131
200
  }
package/dist/hook.d.ts CHANGED
@@ -3,16 +3,16 @@
3
3
  * Google Antigravity hook entry point.
4
4
  *
5
5
  * Antigravity invokes this script as a subprocess for each hook event.
6
+ * Argv: the event name (`<hook command> PreToolUse`), written into
7
+ * hooks.json at install time; the payload does not name it.
6
8
  * Input: JSON on stdin.
7
- * Output: JSON on stdout.
9
+ * Output: one JSON document on stdout. Diagnostics go to stderr.
8
10
  *
9
- * FAIL-CLOSED CONTRACT (the reason this differs from every other plugin):
10
- * on a `PreToolUse` event, Antigravity blocks the tool unless the hook
11
- * returns `{"allow_tool": true}`. A crash, a timeout, malformed output, or
12
- * a non-zero exit are all treated as "block". To preserve this repo's
13
- * fail-open guarantee, EVERY error path here emits `{"allow_tool": true}`
14
- * and exits 0 — a transient Ory/network failure must never wedge the
15
- * user's tools. Emitting `allow_tool` on non-tool events is harmless
16
- * (the harness ignores it), so the safe default works for all events.
11
+ * `decision` is required on `PreToolUse`, and the docs do not say how
12
+ * Antigravity treats a hook that crashes or prints no decision. So every
13
+ * error path here still prints an explicit allow for `PreToolUse` (`{}` for
14
+ * other events) and exits 0: a crash in the plugin itself must never
15
+ * wedge the user's tools. Permission denials and enforce-mode failures are
16
+ * decided by the core gate, not here.
17
17
  */
18
18
  export {};
package/dist/hook.js CHANGED
@@ -4,104 +4,37 @@
4
4
  * Google Antigravity hook entry point.
5
5
  *
6
6
  * Antigravity invokes this script as a subprocess for each hook event.
7
+ * Argv: the event name (`<hook command> PreToolUse`), written into
8
+ * hooks.json at install time; the payload does not name it.
7
9
  * Input: JSON on stdin.
8
- * Output: JSON on stdout.
10
+ * Output: one JSON document on stdout. Diagnostics go to stderr.
9
11
  *
10
- * FAIL-CLOSED CONTRACT (the reason this differs from every other plugin):
11
- * on a `PreToolUse` event, Antigravity blocks the tool unless the hook
12
- * returns `{"allow_tool": true}`. A crash, a timeout, malformed output, or
13
- * a non-zero exit are all treated as "block". To preserve this repo's
14
- * fail-open guarantee, EVERY error path here emits `{"allow_tool": true}`
15
- * and exits 0 — a transient Ory/network failure must never wedge the
16
- * user's tools. Emitting `allow_tool` on non-tool events is harmless
17
- * (the harness ignores it), so the safe default works for all events.
12
+ * `decision` is required on `PreToolUse`, and the docs do not say how
13
+ * Antigravity treats a hook that crashes or prints no decision. So every
14
+ * error path here still prints an explicit allow for `PreToolUse` (`{}` for
15
+ * other events) and exits 0: a crash in the plugin itself must never
16
+ * wedge the user's tools. Permission denials and enforce-mode failures are
17
+ * decided by the core gate, not here.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  const argus_1 = require("@ory/argus");
21
- const emit_js_1 = require("./emit.js");
22
21
  const handlers_js_1 = require("./handlers.js");
23
- /** The fail-open response: explicitly allow, so a crash never blocks. */
24
- const FAIL_OPEN = { allow_tool: true };
25
- const EVENT_FLUSH_TIMEOUT_MS = 750;
26
- let client;
27
- async function flushEvents() {
28
- try {
29
- await client?.flushEvents(EVENT_FLUSH_TIMEOUT_MS);
30
- }
31
- catch {
32
- // The hook decision must not depend on activity delivery.
33
- }
34
- }
35
- /**
36
- * Single write-once gate shared by every exit path (normal, parse
37
- * failure, and the top-level catch). Because Antigravity fails closed on
38
- * malformed stdout, a double write (two concatenated JSON documents)
39
- * would BLOCK the tool.
40
- */
41
- const emit = (0, emit_js_1.createEmitOnce)();
42
22
  /**
43
- * Read all of stdin as a string. Uses event listeners (not `for await`)
44
- * with an idle timer so we don't hang if the parent never sends EOF.
23
+ * Error-path response. `PreToolUse` (or an unknown event, which may be one)
24
+ * gets an explicit allow; other events get `{}` so no field lands on an
25
+ * output schema that does not declare it.
45
26
  */
46
- function readStdin() {
47
- return new Promise((resolve, reject) => {
48
- const chunks = [];
49
- let resolved = false;
50
- let idleTimer;
51
- function done() {
52
- if (!resolved) {
53
- resolved = true;
54
- resolve(Buffer.concat(chunks).toString("utf-8"));
55
- }
56
- }
57
- process.stdin.on("data", (chunk) => {
58
- chunks.push(chunk);
59
- clearTimeout(idleTimer);
60
- idleTimer = setTimeout(done, 100);
61
- });
62
- process.stdin.on("end", done);
63
- process.stdin.on("error", (err) => {
64
- if (!resolved) {
65
- resolved = true;
66
- reject(err);
67
- }
68
- });
69
- });
70
- }
71
- async function main() {
72
- client = argus_1.OryAgentClient.fromEnv("antigravity");
73
- const raw = await readStdin();
74
- let input;
75
- try {
76
- input = JSON.parse(raw);
77
- }
78
- catch {
79
- client.logger.error("hook.stdin.parse_failed", { raw: raw.slice(0, 200) });
80
- // Can't tell the event; allow to avoid wedging a PreToolUse call.
81
- emit(FAIL_OPEN);
82
- process.exit(0);
83
- }
84
- let output;
85
- try {
86
- output = await (0, handlers_js_1.handleHookEvent)(input, client);
87
- }
88
- catch (err) {
89
- client.logger.error("hook.handler.error", {
90
- event: input.hook_event_name,
91
- message: err instanceof Error ? err.message : String(err),
92
- });
93
- output = FAIL_OPEN;
94
- }
95
- emit(output);
96
- await flushEvents();
97
- process.exit(0);
27
+ function failOpen(event) {
28
+ return event === undefined || event === "PreToolUse" ? handlers_js_1.ALLOW : {};
98
29
  }
99
- main().catch(async (err) => {
100
- // Last-resort guard: allow rather than block, then exit cleanly. The
101
- // write-once emitter makes this a no-op when the decision was already
102
- // written before the rejection.
103
- process.stderr.write(`[ory-agent] fatal: ${err}\n`);
104
- emit(FAIL_OPEN);
105
- await flushEvents();
106
- process.exit(0);
30
+ /** The event name hooks.json passes as the first argument. */
31
+ const argvEvent = process.argv[2];
32
+ void (0, argus_1.runHookProcess)({
33
+ harness: "antigravity",
34
+ handle: (input, client) => (0, handlers_js_1.handleHookEvent)(input, client, { event: argvEvent }),
35
+ respond: (output) => ({ stdout: JSON.stringify(output) }),
36
+ failOpen: { stdout: JSON.stringify(failOpen(argvEvent)) },
37
+ // A hook that outlives Antigravity's timeout may block the tool, so exit as
38
+ // soon as the answer is written and activity is flushed.
39
+ exitImmediately: true,
107
40
  });
package/dist/types.d.ts CHANGED
@@ -1,64 +1,125 @@
1
1
  /**
2
- * Google Antigravity (`agy` CLI / IDE) hook contract.
2
+ * Google Antigravity (`agy` CLI / App / IDE) hook contract.
3
3
  *
4
- * Verified against `agy 1.0.13`: hooks run as subprocesses, receive a
5
- * JSON payload on stdin, and emit a JSON response on stdout. The payload
6
- * uses Claude-Code-style snake_case field names (`tool_name`,
7
- * `tool_input`, `session_id`, `transcript_path`, `hook_event_name`).
4
+ * Source: https://antigravity.google/docs/hooks, cross-checked against the
5
+ * `exa.hooks_pb` descriptors in the `agy 1.1.10` binary.
8
6
  *
9
- * IMPORTANT — Antigravity hooks FAIL CLOSED. On a `PreToolUse` event, a
10
- * hook that crashes, times out, or omits `allow_tool` BLOCKS the tool
11
- * call. This is the inverse of every other harness in this repo, so the
12
- * hook entry point must always emit `{ "allow_tool": true }` (and exit 0)
13
- * on any allow/error path. See `hook.ts`.
7
+ * Hooks run as subprocesses: a JSON payload on stdin, a JSON response on
8
+ * stdout. Field names are camelCase. The payload does NOT name the event, so
9
+ * the generated hooks.json registers each event with its name as the hook
10
+ * command's first argument and the entry point routes on that argument.
11
+ *
12
+ * Supported events: `SessionStart`, `PreToolUse`, `PostToolUse`,
13
+ * `PreInvocation`, `PostInvocation`, and `Stop`. There is no `SessionEnd` or
14
+ * `Notification` event.
15
+ *
16
+ * Failure behavior: the docs do not say what Antigravity does when a hook
17
+ * crashes, times out, or prints malformed output. `decision` is documented as
18
+ * required on `PreToolUse`, so the entry point always prints an explicit
19
+ * allow on every non-deny path, including its own error paths. See `hook.ts`.
14
20
  */
15
- /** Hook event names emitted by Antigravity. */
16
- export type AntigravityHookEvent = "SessionStart" | "SessionEnd" | "PreToolUse" | "PostToolUse" | "PreInvocation" | "PostInvocation" | "Stop" | "Notification" | string;
21
+ /** Hook events Antigravity documents. */
22
+ export type AntigravityHookEvent = "SessionStart" | "PreToolUse" | "PostToolUse" | "PreInvocation" | "PostInvocation" | "Stop";
23
+ export declare const ANTIGRAVITY_HOOK_EVENTS: readonly AntigravityHookEvent[];
24
+ export declare function isAntigravityHookEvent(value: unknown): value is AntigravityHookEvent;
25
+ /** Tool call details on `PreToolUse` / `PostToolUse`. */
26
+ export interface AntigravityToolCall {
27
+ name?: string;
28
+ args?: Record<string, unknown>;
29
+ }
30
+ /** Metadata every event carries. */
31
+ export interface AntigravityHookCommon {
32
+ conversationId?: string;
33
+ workspacePaths?: string[];
34
+ transcriptPath?: string;
35
+ artifactDirectoryPath?: string;
36
+ modelName?: string;
37
+ lastUserInput?: string;
38
+ }
17
39
  /**
18
- * Hook event payload delivered on stdin. Field availability depends on
19
- * `hook_event_name`; everything past the first two is optional.
40
+ * Hook payload delivered on stdin.
41
+ *
42
+ * The documented shape is flat: the common fields sit next to the
43
+ * event-specific ones. The binary's protobuf schema wraps the same fields as
44
+ * `common` plus one per-event `*HookArgs` object, so both are accepted. The
45
+ * snake_case fields are the payload older `agy` builds sent (1.0.x), kept so
46
+ * an older harness still routes and gates.
20
47
  */
21
- export interface AntigravityHookInput {
22
- hook_event_name: AntigravityHookEvent;
23
- session_id: string;
24
- /** Path to the conversation transcript for this session. */
25
- transcript_path?: string;
26
- /** Workspace roots for the session. */
27
- workspace_paths?: string[];
28
- /** Current working directory, when provided. */
29
- cwd?: string;
30
- /** Tool the agent is about to run (or just ran). */
48
+ export interface AntigravityHookInput extends AntigravityHookCommon {
49
+ toolCall?: AntigravityToolCall;
50
+ stepIdx?: number;
51
+ /** PostToolUse / Stop: error message; empty on success. */
52
+ error?: string;
53
+ /** PostToolUse: tool result, when present. */
54
+ result?: unknown;
55
+ invocationNum?: number;
56
+ initialNumSteps?: number;
57
+ executionNum?: number;
58
+ terminationReason?: string;
59
+ fullyIdle?: boolean;
60
+ common?: AntigravityHookCommon;
61
+ sessionStartHookArgs?: Record<string, unknown>;
62
+ preToolHookArgs?: {
63
+ toolCall?: AntigravityToolCall;
64
+ stepIdx?: number;
65
+ };
66
+ postToolHookArgs?: {
67
+ toolCall?: AntigravityToolCall;
68
+ stepIdx?: number;
69
+ error?: string;
70
+ result?: unknown;
71
+ };
72
+ preInvocationHookArgs?: Record<string, unknown>;
73
+ postInvocationHookArgs?: Record<string, unknown>;
74
+ stopHookArgs?: {
75
+ terminationReason?: string;
76
+ error?: string;
77
+ fullyIdle?: boolean;
78
+ };
79
+ hook_event_name?: string;
80
+ session_id?: string;
31
81
  tool_name?: string;
32
- /** Arguments passed to the tool. */
33
82
  tool_input?: Record<string, unknown>;
34
- /** Tool result, on PostToolUse. */
35
83
  tool_response?: Record<string, unknown>;
36
- /** Tool error payload, when a tool failed. */
37
84
  tool_error?: unknown;
38
85
  model?: string;
39
- /** SessionStart source: startup | resume | ... */
40
86
  source?: string;
41
- /** Termination reason. */
42
87
  reason?: string;
43
- /** Free-form notification / permission-prompt message. */
44
- message?: string;
45
88
  [key: string]: unknown;
46
89
  }
90
+ /** One step injected into the conversation (`SessionStart`, invocation events). */
91
+ export type AntigravityInjectedStep = {
92
+ systemMessage: {
93
+ systemMessage: string;
94
+ metadata?: Record<string, unknown>;
95
+ };
96
+ } | {
97
+ userMessage: string;
98
+ } | {
99
+ ephemeralMessage: string;
100
+ } | {
101
+ errorMessage: {
102
+ userMessage: string;
103
+ };
104
+ };
47
105
  /**
48
106
  * Hook response written to stdout.
49
107
  *
50
- * On `PreToolUse`, `allow_tool` is authoritative:
51
- * - `allow_tool: true` → the tool runs.
52
- * - `allow_tool: false` → the tool is blocked; `deny_reason` is shown.
53
- * - omitted / invalid → Antigravity FAILS CLOSED and blocks the tool.
108
+ * `PreToolUse`: `decision` is required. `"allow"` lets the call proceed to
109
+ * the next hook or the default policy; `"deny"` blocks it, and `reason` is
110
+ * shown to the agent or the user. `allow_tool` / `deny_reason` are the older
111
+ * spelling, still declared on the binary's `PreToolHookResult`, and are set
112
+ * alongside with the same meaning for older `agy` builds.
54
113
  *
55
- * For non-tool events, an empty object (or no output) is fine.
114
+ * `SessionStart`: `injectSteps` optionally adds steps to the conversation.
115
+ * Other events answer `{}`.
56
116
  */
57
117
  export interface AntigravityHookOutput {
58
- /** PreToolUse gate decision. Always set it explicitly on PreToolUse. */
118
+ decision?: "allow" | "deny";
119
+ reason?: string;
120
+ /** Older spelling of `decision`. */
59
121
  allow_tool?: boolean;
60
- /** Human-readable reason shown when `allow_tool` is false. */
122
+ /** Older spelling of `reason`. */
61
123
  deny_reason?: string;
62
- /** Optional audit/log message surfaced by the harness. */
63
- system_message?: string;
124
+ injectSteps?: AntigravityInjectedStep[];
64
125
  }
package/dist/types.js CHANGED
@@ -1,16 +1,35 @@
1
1
  "use strict";
2
2
  /**
3
- * Google Antigravity (`agy` CLI / IDE) hook contract.
3
+ * Google Antigravity (`agy` CLI / App / IDE) hook contract.
4
4
  *
5
- * Verified against `agy 1.0.13`: hooks run as subprocesses, receive a
6
- * JSON payload on stdin, and emit a JSON response on stdout. The payload
7
- * uses Claude-Code-style snake_case field names (`tool_name`,
8
- * `tool_input`, `session_id`, `transcript_path`, `hook_event_name`).
5
+ * Source: https://antigravity.google/docs/hooks, cross-checked against the
6
+ * `exa.hooks_pb` descriptors in the `agy 1.1.10` binary.
9
7
  *
10
- * IMPORTANT — Antigravity hooks FAIL CLOSED. On a `PreToolUse` event, a
11
- * hook that crashes, times out, or omits `allow_tool` BLOCKS the tool
12
- * call. This is the inverse of every other harness in this repo, so the
13
- * hook entry point must always emit `{ "allow_tool": true }` (and exit 0)
14
- * on any allow/error path. See `hook.ts`.
8
+ * Hooks run as subprocesses: a JSON payload on stdin, a JSON response on
9
+ * stdout. Field names are camelCase. The payload does NOT name the event, so
10
+ * the generated hooks.json registers each event with its name as the hook
11
+ * command's first argument and the entry point routes on that argument.
12
+ *
13
+ * Supported events: `SessionStart`, `PreToolUse`, `PostToolUse`,
14
+ * `PreInvocation`, `PostInvocation`, and `Stop`. There is no `SessionEnd` or
15
+ * `Notification` event.
16
+ *
17
+ * Failure behavior: the docs do not say what Antigravity does when a hook
18
+ * crashes, times out, or prints malformed output. `decision` is documented as
19
+ * required on `PreToolUse`, so the entry point always prints an explicit
20
+ * allow on every non-deny path, including its own error paths. See `hook.ts`.
15
21
  */
16
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.ANTIGRAVITY_HOOK_EVENTS = void 0;
24
+ exports.isAntigravityHookEvent = isAntigravityHookEvent;
25
+ exports.ANTIGRAVITY_HOOK_EVENTS = [
26
+ "SessionStart",
27
+ "PreToolUse",
28
+ "PostToolUse",
29
+ "PreInvocation",
30
+ "PostInvocation",
31
+ "Stop",
32
+ ];
33
+ function isAntigravityHookEvent(value) {
34
+ return typeof value === "string" && exports.ANTIGRAVITY_HOOK_EVENTS.includes(value);
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ory/antigravity",
3
- "version": "1.9.1",
3
+ "version": "1.10.0",
4
4
  "description": "Ory plugin for Google Antigravity: scaffolding skills, a local Ory instance, and authentication, authorization, and audit for every tool call",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/ory/ory-agent-plugins/tree/main/packages/antigravity",
@@ -75,7 +75,7 @@
75
75
  ],
76
76
  "dependencies": {
77
77
  "reova": "^0.7.0",
78
- "@ory/argus": "1.9.1"
78
+ "@ory/argus": "1.10.0"
79
79
  },
80
80
  "devDependencies": {
81
81
  "typescript": "^7.0.2"
package/dist/emit.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Write-once stdout emitter for the Antigravity hook.
3
- *
4
- * Antigravity parses the hook's stdout as a single JSON document and
5
- * FAILS CLOSED on malformed output. If two code paths both write, stdout
6
- * carries two concatenated JSON documents and the harness blocks the
7
- * tool. This factory guarantees exactly one write ever reaches stdout.
8
- */
9
- export type EmitOnce<T> = (output: T) => boolean;
10
- /**
11
- * Create an emitter that serializes `output` as JSON and writes it via
12
- * `write` on the first call only. Subsequent calls are no-ops that
13
- * return `false`.
14
- */
15
- export declare function createEmitOnce<T>(write?: (chunk: string) => void): EmitOnce<T>;
package/dist/emit.js DELETED
@@ -1,28 +0,0 @@
1
- "use strict";
2
- /**
3
- * Write-once stdout emitter for the Antigravity hook.
4
- *
5
- * Antigravity parses the hook's stdout as a single JSON document and
6
- * FAILS CLOSED on malformed output. If two code paths both write, stdout
7
- * carries two concatenated JSON documents and the harness blocks the
8
- * tool. This factory guarantees exactly one write ever reaches stdout.
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.createEmitOnce = createEmitOnce;
12
- /**
13
- * Create an emitter that serializes `output` as JSON and writes it via
14
- * `write` on the first call only. Subsequent calls are no-ops that
15
- * return `false`.
16
- */
17
- function createEmitOnce(write = (chunk) => {
18
- process.stdout.write(chunk);
19
- }) {
20
- let wrote = false;
21
- return (output) => {
22
- if (wrote)
23
- return false;
24
- wrote = true;
25
- write(JSON.stringify(output));
26
- return true;
27
- };
28
- }