@ory/openclaw 1.9.2 → 1.10.1

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.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /**
3
- * Read/write helpers for registering the Ory plugin in an OpenClaw
4
- * `.openclaw/config.json`.
3
+ * Pure transforms for the Ory entries in OpenClaw's config (`openclaw.json`;
4
+ * see `openclaw-config.ts` for where that file lives).
5
5
  *
6
6
  * Current OpenClaw addresses plugins by their **manifest id** (ours is
7
7
  * `ory-agent-security`, from `openclaw.plugin.json`) under a nested
@@ -11,9 +11,11 @@
11
11
  * `openclaw plugins install` + `openclaw plugins enable` pair:
12
12
  *
13
13
  * 1. Discovery — the plugin's package directory (the one holding
14
- * `openclaw.plugin.json`) is added to `plugins.load.paths`. OpenClaw only
15
- * scans its bundled dir, `~/.openclaw/extensions`, `<ws>/.openclaw/extensions`,
16
- * and configured `load.paths`; it does *not* auto-scan `node_modules`.
14
+ * `openclaw.plugin.json` and the `package.json` whose
15
+ * `openclaw.extensions` names the entry) is added to `plugins.load.paths`.
16
+ * OpenClaw only scans its bundled dir, `~/.openclaw/extensions`,
17
+ * `<ws>/.openclaw/extensions`, and configured `load.paths`; it does *not*
18
+ * auto-scan `node_modules`.
17
19
  * 2. Enablement — `plugins.entries["ory-agent-security"].enabled = true`,
18
20
  * byte-for-byte what `openclaw plugins enable` writes.
19
21
  *
@@ -21,6 +23,12 @@
21
23
  * present and non-empty, OpenClaw loads *only* the listed ids, so writing one
22
24
  * onto a config that didn't have it would silently disable every other
23
25
  * plugin. We only append our id to an allowlist that already exists.
26
+ *
27
+ * OpenClaw validates the root config as a strict object, so every key written
28
+ * here must exist in its schema: `plugins.*`, `mcp.servers.*`, and
29
+ * `skills.load.extraDirs`. A root `mcpServers` key (which earlier versions of
30
+ * this installer wrote) is not in the schema and makes the Gateway refuse to
31
+ * start, so it is removed wherever it is found.
24
32
  */
25
33
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
26
34
  if (k2 === undefined) k2 = k;
@@ -56,23 +64,47 @@ var __importStar = (this && this.__importStar) || (function () {
56
64
  };
57
65
  })();
58
66
  Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.PLUGIN_MODULE = exports.PLUGIN_ID = void 0;
67
+ exports.MCP_SERVER_NAME = exports.PLUGIN_MODULE = exports.PLUGIN_ID = void 0;
60
68
  exports.resolvePluginRoot = resolvePluginRoot;
61
69
  exports.registerPluginInConfig = registerPluginInConfig;
62
70
  exports.unregisterPluginFromConfig = unregisterPluginFromConfig;
63
71
  exports.isPluginRegistered = isPluginRegistered;
72
+ exports.registeredPluginDir = registeredPluginDir;
73
+ exports.mergeOpenClawMcpServer = mergeOpenClawMcpServer;
74
+ exports.removeOpenClawMcpServer = removeOpenClawMcpServer;
75
+ exports.addSkillsExtraDir = addSkillsExtraDir;
76
+ exports.removeSkillsExtraDir = removeSkillsExtraDir;
77
+ const fs = __importStar(require("node:fs"));
64
78
  const path = __importStar(require("node:path"));
65
- const argus_1 = require("@ory/argus");
79
+ const install_1 = require("@ory/argus/install");
66
80
  /** Plugin manifest id (from `openclaw.plugin.json`). */
67
81
  exports.PLUGIN_ID = "ory-agent-security";
68
82
  /** npm module name — used only to migrate away the legacy flat-array shape. */
69
83
  exports.PLUGIN_MODULE = "@ory/openclaw";
84
+ /** Name of the Ory MCP server under `mcp.servers`. */
85
+ exports.MCP_SERVER_NAME = "ory";
86
+ const MANIFEST_FILENAME = "openclaw.plugin.json";
70
87
  /** Shallow-clone a value into a plain record, or start fresh if it isn't one. */
71
88
  function asRec(value) {
72
89
  return value && typeof value === "object" && !Array.isArray(value)
73
90
  ? { ...value }
74
91
  : {};
75
92
  }
93
+ /**
94
+ * True when `dir` holds a copy of this plugin: its manifest declares our id.
95
+ * Used to drop load paths left by an earlier install (a previous runtime
96
+ * version, a project `node_modules`), since two roots with one plugin id make
97
+ * OpenClaw warn and pick one.
98
+ */
99
+ function isOryPluginDir(dir) {
100
+ try {
101
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, MANIFEST_FILENAME), "utf-8"));
102
+ return manifest.id === exports.PLUGIN_ID;
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
76
108
  /**
77
109
  * Resolve the directory that contains the plugin's `openclaw.plugin.json`
78
110
  * manifest, so it can be registered on `plugins.load.paths`.
@@ -90,7 +122,7 @@ function asRec(value) {
90
122
  function resolvePluginRoot(runtimeDir) {
91
123
  if (runtimeDir)
92
124
  return path.resolve(runtimeDir);
93
- const wired = (0, argus_1.getRuntimeWiring)("openclaw");
125
+ const wired = (0, install_1.getRuntimeWiring)("openclaw");
94
126
  if (wired)
95
127
  return path.resolve(wired.packageDir);
96
128
  // Nothing wired (uninstall before install, or a manifest that was wiped):
@@ -110,7 +142,7 @@ function registerPluginInConfig(config, runtimeDir) {
110
142
  // 1. Discovery — add the package dir to plugins.load.paths (deduped).
111
143
  const load = asRec(plugins.load);
112
144
  const paths = Array.isArray(load.paths)
113
- ? load.paths.filter((p) => p !== root)
145
+ ? load.paths.filter((p) => p !== root && !isOryPluginDir(p))
114
146
  : [];
115
147
  paths.push(root);
116
148
  load.paths = paths;
@@ -153,7 +185,7 @@ function unregisterPluginFromConfig(config, runtimeDir) {
153
185
  // Remove our load path.
154
186
  const load = asRec(plugins.load);
155
187
  if (Array.isArray(load.paths)) {
156
- const paths = load.paths.filter((p) => p !== root);
188
+ const paths = load.paths.filter((p) => p !== root && !isOryPluginDir(p));
157
189
  if (paths.length === 0)
158
190
  delete load.paths;
159
191
  else
@@ -196,3 +228,79 @@ function isPluginRegistered(config) {
196
228
  const entry = entries[exports.PLUGIN_ID];
197
229
  return (!!entry && typeof entry === "object" && entry.enabled === true);
198
230
  }
231
+ /** The registered load path that holds this plugin's manifest, if any. */
232
+ function registeredPluginDir(config) {
233
+ const paths = asRec(asRec(config.plugins).load).paths;
234
+ if (!Array.isArray(paths))
235
+ return undefined;
236
+ return paths.find((p) => typeof p === "string" && isOryPluginDir(p));
237
+ }
238
+ // ─── MCP server (`mcp.servers.ory`) ────────────────────────────────
239
+ /**
240
+ * Register the Ory MCP server under `mcp.servers`, the key OpenClaw reads
241
+ * (`McpConfigSchema`), keeping other servers and other `mcp.*` settings. Also
242
+ * drops the root `mcpServers.ory` earlier installer versions wrote.
243
+ */
244
+ function mergeOpenClawMcpServer(config, cmd) {
245
+ const next = (0, install_1.removeMcpServer)(config);
246
+ const mcp = asRec(next.mcp);
247
+ const servers = asRec(mcp.servers);
248
+ servers[exports.MCP_SERVER_NAME] = (0, install_1.mcpServerEntry)(cmd);
249
+ mcp.servers = servers;
250
+ next.mcp = mcp;
251
+ return next;
252
+ }
253
+ /** Remove the Ory MCP server, pruning `mcp.servers` and `mcp` only when empty. */
254
+ function removeOpenClawMcpServer(config) {
255
+ const next = (0, install_1.removeMcpServer)(config);
256
+ if (next.mcp == null)
257
+ return next;
258
+ const mcp = asRec(next.mcp);
259
+ const servers = asRec(mcp.servers);
260
+ delete servers[exports.MCP_SERVER_NAME];
261
+ if (Object.keys(servers).length === 0)
262
+ delete mcp.servers;
263
+ else
264
+ mcp.servers = servers;
265
+ if (Object.keys(mcp).length === 0)
266
+ delete next.mcp;
267
+ else
268
+ next.mcp = mcp;
269
+ return next;
270
+ }
271
+ // ─── Skills (`skills.load.extraDirs`) ──────────────────────────────
272
+ /** Add a skills directory to `skills.load.extraDirs` unless it is already listed. */
273
+ function addSkillsExtraDir(config, absDir) {
274
+ const next = { ...config };
275
+ const skills = asRec(next.skills);
276
+ const load = asRec(skills.load);
277
+ const dirs = Array.isArray(load.extraDirs) ? load.extraDirs : [];
278
+ load.extraDirs = dirs.includes(absDir) ? dirs : [...dirs, absDir];
279
+ skills.load = load;
280
+ next.skills = skills;
281
+ return next;
282
+ }
283
+ /** Remove a skills directory from `skills.load.extraDirs`, pruning empties. */
284
+ function removeSkillsExtraDir(config, absDir) {
285
+ const next = { ...config };
286
+ if (next.skills == null)
287
+ return next;
288
+ const skills = asRec(next.skills);
289
+ const load = asRec(skills.load);
290
+ if (Array.isArray(load.extraDirs)) {
291
+ const dirs = load.extraDirs.filter((d) => d !== absDir);
292
+ if (dirs.length === 0)
293
+ delete load.extraDirs;
294
+ else
295
+ load.extraDirs = dirs;
296
+ }
297
+ if (Object.keys(load).length === 0)
298
+ delete skills.load;
299
+ else
300
+ skills.load = load;
301
+ if (Object.keys(skills).length === 0)
302
+ delete next.skills;
303
+ else
304
+ next.skills = skills;
305
+ return next;
306
+ }
@@ -3,9 +3,11 @@
3
3
  * Setup CLI for the Ory OpenClaw plugin.
4
4
  *
5
5
  * Usage:
6
- * npx ory-openclaw-setup # Auto-detect and configure
7
- * npx ory-openclaw-setup --project-dir /path/to/repo
6
+ * npx ory-openclaw-setup # Register in OpenClaw's config
8
7
  * npx ory-openclaw-setup --print # Print config to stdout without writing
9
8
  * npx ory-openclaw-setup --uninstall # Remove Ory plugin from config
9
+ *
10
+ * OpenClaw's config is `OPENCLAW_CONFIG_PATH`, else
11
+ * `$OPENCLAW_STATE_DIR/openclaw.json`, else `~/.openclaw/openclaw.json`.
10
12
  */
11
13
  export {};
package/dist/cli/setup.js CHANGED
@@ -4,10 +4,12 @@
4
4
  * Setup CLI for the Ory OpenClaw plugin.
5
5
  *
6
6
  * Usage:
7
- * npx ory-openclaw-setup # Auto-detect and configure
8
- * npx ory-openclaw-setup --project-dir /path/to/repo
7
+ * npx ory-openclaw-setup # Register in OpenClaw's config
9
8
  * npx ory-openclaw-setup --print # Print config to stdout without writing
10
9
  * npx ory-openclaw-setup --uninstall # Remove Ory plugin from config
10
+ *
11
+ * OpenClaw's config is `OPENCLAW_CONFIG_PATH`, else
12
+ * `$OPENCLAW_STATE_DIR/openclaw.json`, else `~/.openclaw/openclaw.json`.
11
13
  */
12
14
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
15
  if (k2 === undefined) k2 = k;
@@ -43,79 +45,65 @@ var __importStar = (this && this.__importStar) || (function () {
43
45
  };
44
46
  })();
45
47
  Object.defineProperty(exports, "__esModule", { value: true });
46
- const fs = __importStar(require("node:fs"));
47
48
  const path = __importStar(require("node:path"));
48
- const argus_1 = require("@ory/argus");
49
+ const cli_1 = require("@ory/argus/cli");
50
+ const install_1 = require("@ory/argus/install");
49
51
  const assets_js_1 = require("./assets.js");
52
+ const installer_js_1 = require("./installer.js");
53
+ const openclaw_config_js_1 = require("./openclaw-config.js");
50
54
  const plugin_config_js_1 = require("./plugin-config.js");
51
- const CONFIG_DIR = ".openclaw";
52
- function getConfigPath(args) {
53
- return path.join(args.projectDir, CONFIG_DIR, "config.json");
54
- }
55
- function ensureConfigDir(args) {
56
- const dir = path.join(args.projectDir, CONFIG_DIR);
57
- if (!fs.existsSync(dir)) {
58
- fs.mkdirSync(dir, { recursive: true });
59
- }
60
- }
61
55
  function main() {
62
56
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
63
- (0, argus_1.printSetupHelp)("ory-openclaw-setup", "OpenClaw");
57
+ (0, install_1.printSetupHelp)("ory-openclaw-setup", "OpenClaw");
64
58
  process.exit(0);
65
59
  }
66
- const args = (0, argus_1.parseSetupArgs)();
60
+ const args = (0, install_1.parseSetupArgs)();
61
+ const argv = process.argv.slice(2);
67
62
  if (args.print) {
68
63
  // Nothing is resolved or written on a --print run.
69
- console.log(JSON.stringify((0, plugin_config_js_1.registerPluginInConfig)({}, "<resolved runtime>"), null, 2));
64
+ let plan = (0, plugin_config_js_1.registerPluginInConfig)({}, "<resolved runtime>");
65
+ plan.plugins.load.paths = ["<resolved runtime dir>"];
66
+ plan = (0, plugin_config_js_1.mergeOpenClawMcpServer)(plan, { command: "<node>", args: ["<ory mcp shim>"] });
67
+ plan = (0, plugin_config_js_1.addSkillsExtraDir)(plan, (0, assets_js_1.orySkillsDir)());
68
+ console.error(`Would merge into ${(0, openclaw_config_js_1.resolveOpenClawConfigPath)()}:`);
69
+ console.log(JSON.stringify(plan, null, 2));
70
70
  return;
71
71
  }
72
- const configPath = getConfigPath(args);
73
- const existing = (0, argus_1.readJsonFile)(configPath);
74
72
  if (args.uninstall) {
75
- if (!fs.existsSync(configPath)) {
76
- console.log("No OpenClaw config found. Nothing to uninstall.");
77
- return;
78
- }
79
- (0, assets_js_1.uninstallOpenclawOryAssets)(args.projectDir);
80
- let updated = (0, plugin_config_js_1.unregisterPluginFromConfig)(existing);
81
- updated = (0, argus_1.removeMcpServer)(updated);
82
- (0, argus_1.writeJsonFile)(configPath, updated);
83
- console.log(`Removed Ory plugin, MCP server, and skills from ${configPath}`);
84
- (0, argus_1.removeRuntimeWiring)("openclaw");
85
- for (const pruned of (0, argus_1.pruneRuntimeStores)()) {
86
- console.log(` Removed runtime: ${pruned}`);
87
- }
73
+ const result = (0, installer_js_1.uninstallOpenclaw)({ args: argv });
74
+ console.log(result.configChanged
75
+ ? `Removed Ory plugin, MCP server, and skills from ${result.configPath}`
76
+ : `No Ory entries found in ${result.configPath}.`);
88
77
  return;
89
78
  }
90
- ensureConfigDir(args);
91
- const runtime = (0, argus_1.wireRuntime)({
92
- harness: "openclaw",
93
- packageName: "@ory/openclaw",
79
+ const result = (0, installer_js_1.installOpenclaw)({
80
+ args: argv,
94
81
  packageRoot: path.resolve(__dirname, "..", ".."),
95
- installCommand: "npx -y -p @ory/openclaw ory-openclaw install",
96
- args: process.argv.slice(2),
97
- entryRelPath: "dist/index.js",
98
- inProcess: true,
99
82
  });
100
- let merged = (0, plugin_config_js_1.registerPluginInConfig)(existing, runtime.target.packageDir);
101
- if (runtime.mcpServer) {
102
- merged = (0, argus_1.mergeMcpServer)(merged, runtime.mcpServer);
103
- }
104
- (0, argus_1.writeJsonFile)(configPath, merged);
105
- (0, assets_js_1.installOpenclawOryAssets)(args.projectDir);
106
- console.log(`Ory plugin and MCP server configured in ${configPath}`);
107
- console.log(`Ory skills installed to ${path.join(args.projectDir, CONFIG_DIR, "skills")}`);
108
- (0, argus_1.printNextSteps)("OpenClaw", "npx -y -p @ory/openclaw ory-openclaw-setup --uninstall", {
83
+ console.log(`Ory plugin and MCP server configured in ${result.configPath}`);
84
+ console.log(`Ory skills installed to ${result.skillsDir}`);
85
+ (0, install_1.printNextSteps)("OpenClaw", "npx -y -p @ory/openclaw ory-openclaw-setup --uninstall", {
109
86
  binName: "ory-openclaw",
110
87
  harness: "openclaw",
111
88
  });
112
89
  }
113
- main();
90
+ try {
91
+ main();
92
+ }
93
+ catch (err) {
94
+ // An unreadable or read-only OpenClaw config stops the command with one
95
+ // line and leaves the file untouched; anything else keeps its stack.
96
+ if (err instanceof install_1.ConfigParseError || err instanceof openclaw_config_js_1.OpenClawConfigReadOnlyError) {
97
+ console.error(err.message);
98
+ process.exit(1);
99
+ }
100
+ throw err;
101
+ }
114
102
  // When invoked directly as the `-setup` bin with `--uninstall`, also clear
115
103
  // stored Ory credentials. When required by the plugin's main CLI, that
116
104
  // command owns the purge, so the `require.main` guard prevents a double run.
117
105
  if (require.main === module && process.argv.includes("--uninstall")) {
118
- (0, argus_1.clearCredentialsForUninstall)({
106
+ (0, cli_1.clearCredentialsForUninstall)({
119
107
  harness: "openclaw",
120
108
  purge: process.argv.includes("--purge"),
121
109
  }).then(() => process.exit(0), (err) => {
package/dist/plugin.d.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import { OryAgentClient, ensureAgentIdentity, ensureSubAgentIdentity, ensureUserAuthenticated } from "@ory/argus";
2
2
  import type { OpenClawPluginEntry } from "./types.js";
3
+ /**
4
+ * How long the per-turn `before_agent_run` handler waits for the sign-in
5
+ * refresh. OpenClaw gives that hook 15 s per handler and fails closed: a
6
+ * handler that is still pending then gets the user's message rejected
7
+ * (`src/plugins/hooks.ts`, `before_agent_run: 15_000` with policy
8
+ * `fail-closed`, at v2026.11.3). The handler therefore resolves well inside
9
+ * that budget whatever the refresh is doing; an unfinished refresh keeps
10
+ * running and its result is picked up by the next tool call.
11
+ */
12
+ export declare const BEFORE_AGENT_RUN_BUDGET_MS = 5000;
3
13
  export interface CreateOryPluginDeps {
4
14
  userLogin?: typeof ensureUserAuthenticated;
5
15
  agentGate?: typeof ensureAgentIdentity;
package/dist/plugin.js CHANGED
@@ -1,8 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BEFORE_AGENT_RUN_BUDGET_MS = void 0;
3
4
  exports.createOryPlugin = createOryPlugin;
4
5
  const argus_1 = require("@ory/argus");
5
6
  const HARNESS = "openclaw";
7
+ /**
8
+ * How long the per-turn `before_agent_run` handler waits for the sign-in
9
+ * refresh. OpenClaw gives that hook 15 s per handler and fails closed: a
10
+ * handler that is still pending then gets the user's message rejected
11
+ * (`src/plugins/hooks.ts`, `before_agent_run: 15_000` with policy
12
+ * `fail-closed`, at v2026.11.3). The handler therefore resolves well inside
13
+ * that budget whatever the refresh is doing; an unfinished refresh keeps
14
+ * running and its result is picked up by the next tool call.
15
+ */
16
+ exports.BEFORE_AGENT_RUN_BUDGET_MS = 5_000;
17
+ /**
18
+ * Stands in for the browser PKCE flow on the per-turn refresh, so a turn can
19
+ * reuse or refresh a token but never opens a browser. Interactive sign-in
20
+ * belongs to `session_start`, which OpenClaw does not time out.
21
+ */
22
+ const refreshOnlyLogin = async () => ({
23
+ kind: "declined",
24
+ reason: "headless",
25
+ detail: "the per-turn refresh never opens a browser; sign-in runs at session start",
26
+ });
27
+ /** User login outcomes that leave the session without a signed-in user. */
28
+ const INCOMPLETE_SIGN_IN_MODES = new Set(["declined", "error"]);
6
29
  function createOryPlugin(clientOrConfig, deps = {}) {
7
30
  return {
8
31
  id: "ory-agent-security",
@@ -14,40 +37,48 @@ function createOryPlugin(clientOrConfig, deps = {}) {
14
37
  ? new argus_1.OryAgentClient({ ...clientOrConfig, harness: HARNESS })
15
38
  : argus_1.OryAgentClient.fromEnv(HARNESS);
16
39
  const subagents = new Map();
17
- api.registerHook("session_start", createSessionStartHandler(client, deps), {
18
- name: "ory.session-verify",
19
- description: "Verify session via Ory Identities",
20
- });
21
- api.registerHook("before_agent_run", createBeforeAgentRunHandler(client, deps), {
22
- name: "ory.user-login",
23
- description: "Block runs when the user login denies",
24
- });
40
+ const sessionStartHandler = createSessionStartHandler(client, deps);
41
+ const beforeAgentRun = createBeforeAgentRunHandler(client, deps);
25
42
  const beforeToolCall = createBeforeToolCallHandler(client, subagents);
26
43
  const afterToolCall = createAfterToolCallHandler(client);
44
+ const subagentSpawned = createSubagentSpawnedHandler(client, deps, subagents);
45
+ const subagentEnded = createSubagentEndedHandler(client, subagents);
27
46
  if (typeof api.on === "function") {
28
- // Typed tool hooks only fire through `api.on` on current OpenClaw.
47
+ // Current OpenClaw dispatches typed lifecycle names only through
48
+ // `api.on`; `registerHook` registrations for them are never invoked.
49
+ // `before_agent_run` also needs
50
+ // `plugins.entries.<id>.hooks.allowConversationAccess: true` for a
51
+ // non-bundled plugin; without it only the per-turn refresh is skipped.
52
+ api.on("session_start", (event, ctx) => sessionStartHandler(fromTypedSessionStart(event, ctx)));
53
+ api.on("before_agent_run", (event, ctx) => beforeAgentRun(fromTypedBeforeAgentRun(event, ctx)));
29
54
  api.on("before_tool_call", (event, ctx) => beforeToolCall(fromTypedToolEvent(event, ctx)));
30
55
  api.on("after_tool_call", (event, ctx) => afterToolCall(fromTypedAfterToolEvent(event, ctx)));
56
+ api.on("subagent_spawned", (event, ctx) => subagentSpawned(fromTypedSubagentSpawned(event, ctx)));
57
+ api.on("subagent_ended", (event, ctx) => subagentEnded(fromTypedSubagentEnded(event, ctx)));
58
+ return;
31
59
  }
32
- else {
33
- api.registerHook("before_tool_call", beforeToolCall, {
34
- name: "ory.permission-check",
35
- description: "Check tool permissions via Ory Permissions",
36
- });
37
- api.registerHook("after_tool_call", afterToolCall, {
38
- name: "ory.activity-complete",
39
- description: "Record tool completion activity",
40
- });
41
- }
42
- api.registerHook("subagent_spawning", createSubagentSpawningHandler(client, deps, subagents), {
43
- name: "ory.subagent-register",
44
- description: "Register Ory identity and write delegation tuple for spawned sub-agent",
60
+ // Older OpenClaw without `api.on` invokes these through `registerHook`.
61
+ api.registerHook("session_start", sessionStartHandler, {
62
+ name: "ory.session-start",
63
+ description: "Run the advisory Ory sign-in and agent identity setup",
45
64
  });
46
- api.registerHook("subagent_spawned", createSubagentSpawnedHandler(client), {
65
+ api.registerHook("before_agent_run", beforeAgentRun, {
66
+ name: "ory.user-login-refresh",
67
+ description: "Refresh the Ory user credential before each run (never blocks)",
68
+ });
69
+ api.registerHook("before_tool_call", beforeToolCall, {
70
+ name: "ory.permission-check",
71
+ description: "Check tool permissions via Ory Permissions",
72
+ });
73
+ api.registerHook("after_tool_call", afterToolCall, {
74
+ name: "ory.activity-complete",
75
+ description: "Record tool completion activity",
76
+ });
77
+ api.registerHook("subagent_spawned", subagentSpawned, {
47
78
  name: "ory.subagent-spawned",
48
- description: "Record sub-agent spawn activity",
79
+ description: "Register the sub-agent identity and record spawn activity",
49
80
  });
50
- api.registerHook("subagent_ended", createSubagentEndedHandler(client, subagents), {
81
+ api.registerHook("subagent_ended", subagentEnded, {
51
82
  name: "ory.subagent-ended",
52
83
  description: "Record sub-agent termination activity",
53
84
  });
@@ -60,15 +91,70 @@ function createSessionStartHandler(client, deps) {
60
91
  sessionId: ctx.sessionId,
61
92
  model: ctx.model,
62
93
  });
63
- await (0, argus_1.sessionStart)(client, {
94
+ const result = await (0, argus_1.sessionStart)(client, {
64
95
  harness: HARNESS,
65
96
  binName: "ory-openclaw",
66
97
  userLogin: deps.userLogin,
67
98
  agentGate: deps.agentGate,
68
- activityAttributes: { model: ctx.model },
99
+ activityAttributes: ctx.model ? { model: ctx.model } : undefined,
69
100
  });
101
+ // OpenClaw's hook API has no non-blocking user notification channel
102
+ // (`enqueueSystemEvent` feeds model context, not the user), so an
103
+ // incomplete sign-in is reported through the plugin logger only.
104
+ if (INCOMPLETE_SIGN_IN_MODES.has(result.userMode)) {
105
+ client.logger.warn("session_start.sign_in_incomplete", {
106
+ message: signInIncompleteMessage(result.userReason),
107
+ });
108
+ }
70
109
  });
71
110
  }
111
+ /** The user-facing text for a sign-in that did not complete. */
112
+ function signInIncompleteMessage(reason) {
113
+ return `Ory sign-in did not complete: ${reason.replace(/[.\s]+$/, "")}. Tool calls may be denied this session.`;
114
+ }
115
+ /** Map a typed `session_start` (event, ctx) pair onto the handler context. */
116
+ function fromTypedSessionStart(event, ctx = {}) {
117
+ return {
118
+ sessionId: event.sessionId ?? ctx.sessionId ?? "",
119
+ sessionKey: event.sessionKey ?? ctx.sessionKey,
120
+ };
121
+ }
122
+ /**
123
+ * Map a typed `before_agent_run` pair onto the handler context. The prompt
124
+ * and messages are deliberately not copied: the refresh never reads them.
125
+ */
126
+ function fromTypedBeforeAgentRun(_event, ctx = {}) {
127
+ return {
128
+ sessionId: ctx.sessionId,
129
+ sessionKey: ctx.sessionKey,
130
+ runId: ctx.runId,
131
+ agentId: ctx.agentId,
132
+ model: ctx.modelId,
133
+ };
134
+ }
135
+ /** Map a typed `subagent_spawned` pair onto the handler context. */
136
+ function fromTypedSubagentSpawned(event, ctx = {}) {
137
+ return {
138
+ agentId: event.agentId,
139
+ label: event.label,
140
+ sessionKey: ctx.requesterSessionKey,
141
+ childSessionKey: event.childSessionKey ?? ctx.childSessionKey,
142
+ mode: event.mode,
143
+ requester: event.requester,
144
+ threadRequested: event.threadRequested,
145
+ childRunId: event.runId ?? ctx.runId,
146
+ };
147
+ }
148
+ /** Map a typed `subagent_ended` pair onto the handler context. */
149
+ function fromTypedSubagentEnded(event, ctx = {}) {
150
+ return {
151
+ sessionKey: ctx.requesterSessionKey,
152
+ targetSessionKey: event.targetSessionKey,
153
+ childSessionKey: ctx.childSessionKey,
154
+ childRunId: event.runId ?? ctx.runId,
155
+ reason: event.reason,
156
+ };
157
+ }
72
158
  function createBeforeToolCallHandler(client, subagents) {
73
159
  return (ctx) => (0, argus_1.withHookContext)(client, { sessionId: ctx.sessionId }, async () => {
74
160
  client.logger.info("lifecycle.before_tool_call", {
@@ -171,39 +257,80 @@ function createAfterToolCallHandler(client) {
171
257
  }
172
258
  });
173
259
  }
174
- // OpenClaw refreshes the interactive user credential before every model turn.
260
+ /**
261
+ * Refresh the user credential before every model turn. Never blocks the run
262
+ * and returns nothing: sign-in is advisory, and enforcement happens at the
263
+ * tool gate through the permission mode.
264
+ *
265
+ * Two bounds keep it inside OpenClaw's 15 s fail-closed budget for this hook.
266
+ * The login is refresh-only (`refreshOnlyLogin`), so it reuses or refreshes a
267
+ * persisted token and never starts the 90 s browser flow. And the wait itself
268
+ * is capped at `BEFORE_AGENT_RUN_BUDGET_MS`, which covers a slow token
269
+ * endpoint and a sign-in another process (or this session's `session_start`)
270
+ * still has open.
271
+ */
175
272
  function createBeforeAgentRunHandler(client, deps) {
176
273
  return (ctx) => (0, argus_1.withHookContext)(client, {
177
274
  sessionId: ctx.sessionKey ?? ctx.sessionId,
178
275
  }, async () => {
179
276
  const userLogin = deps.userLogin ?? argus_1.ensureUserAuthenticated;
180
- await userLogin(client, { binName: "ory-openclaw", harness: HARNESS });
277
+ let timer;
278
+ const budget = new Promise((resolve) => {
279
+ timer = setTimeout(() => resolve("timeout"), exports.BEFORE_AGENT_RUN_BUDGET_MS);
280
+ timer.unref?.();
281
+ });
282
+ const refresh = Promise.resolve()
283
+ .then(() => userLogin(client, { binName: "ory-openclaw", harness: HARNESS, loginFn: refreshOnlyLogin }))
284
+ .then(() => "done", (err) => {
285
+ // A throw here would reach OpenClaw as a hook failure, which
286
+ // blocks the run.
287
+ client.logger.warn("before_agent_run.refresh_failed", {
288
+ message: err instanceof Error ? err.message : String(err),
289
+ });
290
+ return "done";
291
+ });
292
+ try {
293
+ if ((await Promise.race([refresh, budget])) === "timeout") {
294
+ client.logger.warn("before_agent_run.refresh_timeout", {
295
+ message: `Ory sign-in refresh still running after ${exports.BEFORE_AGENT_RUN_BUDGET_MS} ms; the run continues without waiting.`,
296
+ });
297
+ }
298
+ }
299
+ finally {
300
+ clearTimeout(timer);
301
+ }
181
302
  });
182
303
  }
183
- function createSubagentSpawningHandler(client, deps, subagents) {
304
+ /**
305
+ * Record the spawn and register the child's identity. OpenClaw removed
306
+ * `subagent_spawning`; `subagent_spawned` fires after launch with the child
307
+ * session key, so a child tool call that races this registration is checked
308
+ * without sub-agent principals until it completes.
309
+ */
310
+ function createSubagentSpawnedHandler(client, deps, subagents) {
184
311
  return (ctx) => (0, argus_1.withHookContext)(client, {
185
312
  sessionId: ctx.sessionKey,
186
313
  }, async () => {
187
314
  const subAgentType = ctx.agentId ?? ctx.label;
188
- client.logger.info("lifecycle.subagent_spawning", {
315
+ client.logger.info("lifecycle.subagent_spawned", {
189
316
  agentId: ctx.agentId,
190
- label: ctx.label,
317
+ childRunId: ctx.childRunId,
191
318
  childSessionKey: ctx.childSessionKey,
192
319
  mode: ctx.mode,
193
- requester: ctx.requester,
194
320
  });
195
- client.logger.activity("subagent.prepare", "ok", {
321
+ client.logger.activity("subagent.start", "ok", {
196
322
  attributes: {
197
323
  subAgentType,
198
324
  agentId: ctx.agentId,
325
+ childRunId: ctx.childRunId,
199
326
  childSessionKey: ctx.childSessionKey,
200
327
  mode: ctx.mode,
201
- requester: ctx.requester,
328
+ stage: "spawned",
202
329
  },
203
330
  });
204
331
  if (!subAgentType) {
205
332
  client.logger.debug("subagent.no_type", {
206
- message: "subagent_spawning event without a stable spawn id; skipping child credential resolution.",
333
+ message: "subagent_spawned event without an agent id or label; skipping child credential resolution.",
207
334
  });
208
335
  return;
209
336
  }
@@ -227,30 +354,13 @@ function createSubagentSpawningHandler(client, deps, subagents) {
227
354
  }
228
355
  });
229
356
  }
230
- function createSubagentSpawnedHandler(client) {
231
- return (ctx) => (0, argus_1.withHookContext)(client, {
232
- sessionId: ctx.sessionKey,
233
- }, async () => {
234
- client.logger.info("lifecycle.subagent_spawned", {
235
- agentId: ctx.agentId,
236
- childRunId: ctx.childRunId,
237
- childSessionKey: ctx.childSessionKey,
238
- });
239
- client.logger.activity("subagent.start", "ok", {
240
- attributes: {
241
- subAgentType: ctx.agentId ?? ctx.label,
242
- agentId: ctx.agentId,
243
- childRunId: ctx.childRunId,
244
- stage: "spawned",
245
- },
246
- });
247
- });
248
- }
249
357
  function createSubagentEndedHandler(client, subagents) {
250
358
  return (ctx) => (0, argus_1.withHookContext)(client, {
251
359
  sessionId: ctx.sessionKey,
252
360
  }, async () => {
253
361
  const childSessionKey = ctx.targetSessionKey ?? ctx.childSessionKey;
362
+ // The typed ended event carries no agent id; recover it from the spawn.
363
+ const subAgentType = ctx.agentId ?? ctx.label ?? (childSessionKey ? subagents.get(childSessionKey)?.type : undefined);
254
364
  if (childSessionKey)
255
365
  subagents.delete(childSessionKey);
256
366
  client.logger.info("lifecycle.subagent_ended", {
@@ -260,7 +370,7 @@ function createSubagentEndedHandler(client, subagents) {
260
370
  });
261
371
  client.logger.activity("subagent.stop", "ok", {
262
372
  attributes: {
263
- subAgentType: ctx.agentId ?? ctx.label,
373
+ subAgentType,
264
374
  agentId: ctx.agentId,
265
375
  childRunId: ctx.childRunId,
266
376
  reason: ctx.reason,