@oked/hook-core 0.6.24 → 0.6.25

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
@@ -31,7 +31,7 @@ Decisions are made in Telegram or on the [web dashboard](https://oked.ai/dashboa
31
31
 
32
32
  `classify()` knows Claude Code names (`Bash`, `Write`, `Edit`, `mcp__server__tool`). Host packages map their own names onto those before calling `decide()`. Unknown names stay unknown, and the classifier treats an unknown tool as `review` (approval required). `mapPatch()` and `mapFileDelete()` turn patches and deletes into the same effect classes the bash classifier already uses.
33
33
 
34
- `findClaudeOkedHooks()` reports an existing `oked-hook` entry in Claude settings. A host that also loads those files uses it so one action is not asked twice.
34
+ `findClaudeOkedHooks()` reports an existing `oked-hook` entry in Claude settings. A host that also loads those files uses it so one action is not asked twice. The Claude Code plugin uses the same check. When that plugin is enabled and its hook file is installed, the settings hook returns allow and the plugin is the only gate. When the plugin is not the gate, the plugin hook returns allow for tools the settings hook already matches.
35
35
 
36
36
  ## Troubleshooting
37
37
 
@@ -3,6 +3,13 @@ export interface ClaudeHookHit {
3
3
  scope: ClaudeHookScope;
4
4
  path: string;
5
5
  }
6
+ export interface ClaudeOkedCommand {
7
+ scope: ClaudeHookScope;
8
+ path: string;
9
+ /** Omitted matcher matches every tool, same as Claude Code. */
10
+ matcher?: string;
11
+ command: string;
12
+ }
6
13
  /** User-level Claude Code settings. `CLAUDE_CONFIG_DIR` moves the directory. */
7
14
  export declare function claudeUserSettingsPath(): string;
8
15
  /** True when a Claude settings object has an `oked-hook` PreToolUse command. */
@@ -15,3 +22,15 @@ export declare function settingsHasOkedHook(settings: unknown): boolean;
15
22
  export declare function findClaudeOkedHooks(cwd: string, opts?: {
16
23
  includeUser?: boolean;
17
24
  }): ClaudeHookHit[];
25
+ /** Every `oked-hook` PreToolUse command, including its matcher. */
26
+ export declare function listClaudeOkedCommands(cwd: string, opts?: {
27
+ includeUser?: boolean;
28
+ }): ClaudeOkedCommand[];
29
+ /**
30
+ * Claude Code matchers are regular expressions. An omitted matcher matches
31
+ * every tool. A matcher that does not compile does not match, so the other
32
+ * gate stays responsible.
33
+ */
34
+ export declare function matcherCoversTool(matcher: string | undefined, toolName: string): boolean;
35
+ /** True when `command` is an existing file, or a name on `PATH`. */
36
+ export declare function commandIsResolvable(command: string, pathEnv?: string): boolean;
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from "fs";
2
2
  import { homedir } from "os";
3
- import { join } from "path";
3
+ import { delimiter, join } from "path";
4
4
  /** User-level Claude Code settings. `CLAUDE_CONFIG_DIR` moves the directory. */
5
5
  export function claudeUserSettingsPath() {
6
6
  return join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "settings.json");
@@ -32,31 +32,106 @@ export function settingsHasOkedHook(settings) {
32
32
  }
33
33
  return false;
34
34
  }
35
- /**
36
- * Claude settings files that already install `@oked/claude-code`.
37
- * Cursor reads the user file and both project files. Copilot's CLI and VS
38
- * Code read the two project files. Pass `includeUser: false` for Copilot.
39
- */
40
- export function findClaudeOkedHooks(cwd, opts) {
35
+ function settingsCandidates(cwd, includeUser) {
41
36
  const candidates = [
42
37
  { scope: "project-local", path: join(cwd, ".claude", "settings.local.json") },
43
38
  { scope: "project", path: join(cwd, ".claude", "settings.json") },
44
39
  ];
45
- if (opts?.includeUser !== false) {
40
+ if (includeUser)
46
41
  candidates.push({ scope: "user", path: claudeUserSettingsPath() });
42
+ return candidates;
43
+ }
44
+ function readJson(path) {
45
+ try {
46
+ return JSON.parse(readFileSync(path, "utf-8"));
47
47
  }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ /**
53
+ * Claude settings files that already install `@oked/claude-code`.
54
+ * Cursor reads the user file and both project files. Copilot's CLI and VS
55
+ * Code read the two project files. Pass `includeUser: false` for Copilot.
56
+ */
57
+ export function findClaudeOkedHooks(cwd, opts) {
48
58
  const hits = [];
49
- for (const candidate of candidates) {
59
+ for (const candidate of settingsCandidates(cwd, opts?.includeUser !== false)) {
50
60
  if (!existsSync(candidate.path))
51
61
  continue;
52
- try {
53
- const parsed = JSON.parse(readFileSync(candidate.path, "utf-8"));
54
- if (settingsHasOkedHook(parsed))
55
- hits.push(candidate);
62
+ if (settingsHasOkedHook(readJson(candidate.path)))
63
+ hits.push(candidate);
64
+ }
65
+ return hits;
66
+ }
67
+ /** Every `oked-hook` PreToolUse command, including its matcher. */
68
+ export function listClaudeOkedCommands(cwd, opts) {
69
+ const commands = [];
70
+ for (const candidate of settingsCandidates(cwd, opts?.includeUser !== false)) {
71
+ if (!existsSync(candidate.path))
72
+ continue;
73
+ const settings = readJson(candidate.path);
74
+ if (!settings || typeof settings !== "object")
75
+ continue;
76
+ const pre = settings.hooks?.PreToolUse;
77
+ if (!Array.isArray(pre))
78
+ continue;
79
+ for (const entry of pre) {
80
+ if (!entry || typeof entry !== "object")
81
+ continue;
82
+ const matcher = entry.matcher;
83
+ const list = entry.hooks;
84
+ if (!Array.isArray(list))
85
+ continue;
86
+ for (const hook of list) {
87
+ if (!hook || typeof hook !== "object")
88
+ continue;
89
+ const command = hook.command;
90
+ if (!commandIsOkedHook(command))
91
+ continue;
92
+ commands.push({
93
+ scope: candidate.scope,
94
+ path: candidate.path,
95
+ ...(typeof matcher === "string" ? { matcher } : {}),
96
+ command: command.trim(),
97
+ });
98
+ }
56
99
  }
57
- catch {
58
- // A file that does not parse is not a hook we can see.
100
+ }
101
+ return commands;
102
+ }
103
+ /**
104
+ * Claude Code matchers are regular expressions. An omitted matcher matches
105
+ * every tool. A matcher that does not compile does not match, so the other
106
+ * gate stays responsible.
107
+ */
108
+ export function matcherCoversTool(matcher, toolName) {
109
+ if (matcher === undefined)
110
+ return true;
111
+ try {
112
+ return new RegExp(matcher).test(toolName);
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /** True when `command` is an existing file, or a name on `PATH`. */
119
+ export function commandIsResolvable(command, pathEnv = process.env.PATH ?? "") {
120
+ const trimmed = command.trim();
121
+ if (!trimmed)
122
+ return false;
123
+ if (trimmed.includes("/") || trimmed.includes("\\"))
124
+ return existsSync(trimmed);
125
+ const names = process.platform === "win32"
126
+ ? [trimmed, `${trimmed}.cmd`, `${trimmed}.exe`, `${trimmed}.bat`]
127
+ : [trimmed];
128
+ for (const dir of pathEnv.split(delimiter)) {
129
+ if (!dir)
130
+ continue;
131
+ for (const name of names) {
132
+ if (existsSync(join(dir, name)))
133
+ return true;
59
134
  }
60
135
  }
61
- return hits;
136
+ return false;
62
137
  }
@@ -0,0 +1,48 @@
1
+ /** Marketplace and manifest name for the Claude Code plugin. */
2
+ export declare const OKED_PLUGIN_NAME = "oked";
3
+ /** Hook file the plugin runs. Settings stand down only when this file is installed. */
4
+ export declare const OKED_PLUGIN_HOOK_FILE: string;
5
+ export interface OkedInstallRecord {
6
+ id: string;
7
+ installPath?: string;
8
+ }
9
+ export interface OkedPluginResolution {
10
+ enabled: boolean;
11
+ id?: string;
12
+ }
13
+ /** `oked`, `oked@oked`, `oked@inline`, and any other `oked@...` id. */
14
+ export declare function isOkedPluginId(id: string): boolean;
15
+ /**
16
+ * Directories that can hold `installed_plugins.json`.
17
+ * Claude Code keeps plugins under `~/.claude/plugins` unless
18
+ * `CLAUDE_CODE_PLUGIN_CACHE_DIR` is set. `CLAUDE_CONFIG_DIR` moves settings,
19
+ * and some installs keep plugins beside those settings, so both are checked.
20
+ */
21
+ export declare function claudePluginsDirs(env?: NodeJS.ProcessEnv): string[];
22
+ /** OKed rows from an `installed_plugins.json` document. */
23
+ export declare function installedOkedRecords(doc: unknown): OkedInstallRecord[];
24
+ /**
25
+ * Merge OKed `enabledPlugins` flags. `layersLowToHigh` is user, then project,
26
+ * then local. A higher layer that sets true or false wins for that id.
27
+ * An installed id with no flag is enabled, because the plugin's
28
+ * `defaultEnabled` is true.
29
+ */
30
+ export declare function resolveOkedPluginEnabled(installedIds: string[], layersLowToHigh: unknown[]): OkedPluginResolution;
31
+ export declare function loadInstalledOkedRecords(env?: NodeJS.ProcessEnv): OkedInstallRecord[];
32
+ /** True when an OKed Claude Code plugin should be loaded for this project. */
33
+ export declare function okedPluginIsEnabled(cwd: string, env?: NodeJS.ProcessEnv): boolean;
34
+ /** True when an installed copy contains the bundled hook file. */
35
+ export declare function okedPluginBundleOnDisk(env?: NodeJS.ProcessEnv): boolean;
36
+ export declare function bundleExistsAt(installPath: string): boolean;
37
+ /**
38
+ * The `oked init` settings hook returns allow, without calling OKed, when the
39
+ * plugin is enabled and its hook file is on disk. The plugin hook then gates.
40
+ * If the file is missing, this returns false and the settings hook still gates.
41
+ */
42
+ export declare function settingsHookYieldsToPlugin(cwd: string, env?: NodeJS.ProcessEnv): boolean;
43
+ /**
44
+ * The plugin hook returns allow, without calling OKed, when an `oked-hook`
45
+ * command will also run for this tool and the settings hook is not yielding.
46
+ * The two hooks never both yield, and they never both call OKed.
47
+ */
48
+ export declare function pluginHookYieldsToSettingsHook(toolName: string, cwd: string, env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,174 @@
1
+ import { existsSync, readFileSync } from "fs";
2
+ import { homedir } from "os";
3
+ import { join } from "path";
4
+ import { claudeUserSettingsPath, commandIsResolvable, listClaudeOkedCommands, matcherCoversTool, } from "./claude-hooks.js";
5
+ /** Marketplace and manifest name for the Claude Code plugin. */
6
+ export const OKED_PLUGIN_NAME = "oked";
7
+ /** Hook file the plugin runs. Settings stand down only when this file is installed. */
8
+ export const OKED_PLUGIN_HOOK_FILE = join("scripts", "oked-hook.mjs");
9
+ /** `oked`, `oked@oked`, `oked@inline`, and any other `oked@...` id. */
10
+ export function isOkedPluginId(id) {
11
+ return id === OKED_PLUGIN_NAME || id.startsWith(`${OKED_PLUGIN_NAME}@`);
12
+ }
13
+ function readJson(path) {
14
+ try {
15
+ return JSON.parse(readFileSync(path, "utf-8"));
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /**
22
+ * Directories that can hold `installed_plugins.json`.
23
+ * Claude Code keeps plugins under `~/.claude/plugins` unless
24
+ * `CLAUDE_CODE_PLUGIN_CACHE_DIR` is set. `CLAUDE_CONFIG_DIR` moves settings,
25
+ * and some installs keep plugins beside those settings, so both are checked.
26
+ */
27
+ export function claudePluginsDirs(env = process.env) {
28
+ const dirs = [];
29
+ const add = (dir) => {
30
+ if (!dirs.includes(dir))
31
+ dirs.push(dir);
32
+ };
33
+ if (env.CLAUDE_CODE_PLUGIN_CACHE_DIR)
34
+ add(env.CLAUDE_CODE_PLUGIN_CACHE_DIR);
35
+ const config = env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), ".claude");
36
+ add(join(config, "plugins"));
37
+ add(join(env.HOME || homedir(), ".claude", "plugins"));
38
+ return dirs;
39
+ }
40
+ /** OKed rows from an `installed_plugins.json` document. */
41
+ export function installedOkedRecords(doc) {
42
+ if (!doc || typeof doc !== "object")
43
+ return [];
44
+ const plugins = doc.plugins;
45
+ const records = [];
46
+ const push = (id, value) => {
47
+ if (!isOkedPluginId(id))
48
+ return;
49
+ const entries = Array.isArray(value) ? value : [value];
50
+ let pushed = false;
51
+ for (const entry of entries) {
52
+ if (!entry || typeof entry !== "object")
53
+ continue;
54
+ const installPath = entry.installPath;
55
+ records.push({
56
+ id,
57
+ ...(typeof installPath === "string" && installPath ? { installPath } : {}),
58
+ });
59
+ pushed = true;
60
+ }
61
+ if (!pushed)
62
+ records.push({ id });
63
+ };
64
+ if (Array.isArray(plugins)) {
65
+ for (const entry of plugins) {
66
+ if (!entry || typeof entry !== "object")
67
+ continue;
68
+ const raw = entry.id ?? entry.name;
69
+ if (typeof raw === "string")
70
+ push(raw, entry);
71
+ }
72
+ return records;
73
+ }
74
+ if (plugins && typeof plugins === "object") {
75
+ for (const [id, value] of Object.entries(plugins))
76
+ push(id, value);
77
+ }
78
+ return records;
79
+ }
80
+ /**
81
+ * Merge OKed `enabledPlugins` flags. `layersLowToHigh` is user, then project,
82
+ * then local. A higher layer that sets true or false wins for that id.
83
+ * An installed id with no flag is enabled, because the plugin's
84
+ * `defaultEnabled` is true.
85
+ */
86
+ export function resolveOkedPluginEnabled(installedIds, layersLowToHigh) {
87
+ const ids = new Set();
88
+ for (const id of installedIds)
89
+ if (isOkedPluginId(id))
90
+ ids.add(id);
91
+ const maps = layersLowToHigh.map(enabledMap);
92
+ for (const map of maps) {
93
+ if (!map)
94
+ continue;
95
+ for (const id of Object.keys(map))
96
+ if (isOkedPluginId(id))
97
+ ids.add(id);
98
+ }
99
+ let enabledId;
100
+ for (const id of ids) {
101
+ let mentioned = false;
102
+ let value = false;
103
+ for (const map of maps) {
104
+ if (!map || !Object.prototype.hasOwnProperty.call(map, id))
105
+ continue;
106
+ const flag = map[id];
107
+ if (flag === true || flag === false) {
108
+ mentioned = true;
109
+ value = flag;
110
+ }
111
+ }
112
+ const on = mentioned ? value : installedIds.includes(id);
113
+ if (on)
114
+ enabledId = id;
115
+ }
116
+ return enabledId ? { enabled: true, id: enabledId } : { enabled: false };
117
+ }
118
+ function enabledMap(settings) {
119
+ if (!settings || typeof settings !== "object")
120
+ return undefined;
121
+ const enabled = settings.enabledPlugins;
122
+ if (!enabled || typeof enabled !== "object" || Array.isArray(enabled))
123
+ return undefined;
124
+ return enabled;
125
+ }
126
+ export function loadInstalledOkedRecords(env = process.env) {
127
+ const records = [];
128
+ for (const dir of claudePluginsDirs(env)) {
129
+ const file = join(dir, "installed_plugins.json");
130
+ if (!existsSync(file))
131
+ continue;
132
+ records.push(...installedOkedRecords(readJson(file)));
133
+ }
134
+ return records;
135
+ }
136
+ function settingsLayers(cwd) {
137
+ return [
138
+ readJson(claudeUserSettingsPath()),
139
+ readJson(join(cwd, ".claude", "settings.json")),
140
+ readJson(join(cwd, ".claude", "settings.local.json")),
141
+ ];
142
+ }
143
+ /** True when an OKed Claude Code plugin should be loaded for this project. */
144
+ export function okedPluginIsEnabled(cwd, env = process.env) {
145
+ const records = loadInstalledOkedRecords(env);
146
+ return resolveOkedPluginEnabled(records.map((record) => record.id), settingsLayers(cwd)).enabled;
147
+ }
148
+ /** True when an installed copy contains the bundled hook file. */
149
+ export function okedPluginBundleOnDisk(env = process.env) {
150
+ return loadInstalledOkedRecords(env).some((record) => record.installPath && bundleExistsAt(record.installPath));
151
+ }
152
+ export function bundleExistsAt(installPath) {
153
+ if (installPath.endsWith("oked-hook.mjs"))
154
+ return existsSync(installPath);
155
+ return existsSync(join(installPath, OKED_PLUGIN_HOOK_FILE));
156
+ }
157
+ /**
158
+ * The `oked init` settings hook returns allow, without calling OKed, when the
159
+ * plugin is enabled and its hook file is on disk. The plugin hook then gates.
160
+ * If the file is missing, this returns false and the settings hook still gates.
161
+ */
162
+ export function settingsHookYieldsToPlugin(cwd, env = process.env) {
163
+ return okedPluginIsEnabled(cwd, env) && okedPluginBundleOnDisk(env);
164
+ }
165
+ /**
166
+ * The plugin hook returns allow, without calling OKed, when an `oked-hook`
167
+ * command will also run for this tool and the settings hook is not yielding.
168
+ * The two hooks never both yield, and they never both call OKed.
169
+ */
170
+ export function pluginHookYieldsToSettingsHook(toolName, cwd, env = process.env) {
171
+ if (settingsHookYieldsToPlugin(cwd, env))
172
+ return false;
173
+ return listClaudeOkedCommands(cwd).some((command) => matcherCoversTool(command.matcher, toolName) && commandIsResolvable(command.command, env.PATH ?? ""));
174
+ }
package/dist/decide.d.ts CHANGED
@@ -30,6 +30,12 @@ export interface DecideOptions {
30
30
  * Other hosts pass a sentence that names their own init command.
31
31
  */
32
32
  invalidKeyReason?: (status: number) => string;
33
+ /**
34
+ * When set to a non-empty string, this key is used instead of `OKED_API_KEY`
35
+ * and `~/.oked/config.json`. The Claude Code plugin passes
36
+ * `CLAUDE_PLUGIN_OPTION_APIKEY`.
37
+ */
38
+ apiKey?: string;
33
39
  log?: (msg: string) => void;
34
40
  /**
35
41
  * When set, overrides Claude Code sandbox detection.
package/dist/decide.js CHANGED
@@ -54,7 +54,11 @@ export async function decide(call, options) {
54
54
  cwd: call.cwd,
55
55
  ...(sandboxEnforced === false ? { sandboxEnforced: false } : {}),
56
56
  };
57
- const client = new OKedClient({ client: options.clientId, source: options.source });
57
+ const client = new OKedClient({
58
+ client: options.clientId,
59
+ source: options.source,
60
+ ...(options.apiKey ? { apiKey: options.apiKey } : {}),
61
+ });
58
62
  // Presence ping (throttled to once/day on disk, never throws). Fired before
59
63
  // the safe/warning fast-path return so installs that only ever run safe
60
64
  // actions still register for retention. Bounded by the 3s internal timeout,
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ export { decide, type ToolCallInput, type DecideOptions, type GateDecision, type
2
2
  export { HOOK_TIMEOUT_SECONDS } from "./timeout.js";
3
3
  export { logDecision, errorInfo, OKED_HOOK_LOG, type DecisionLogEntry, type ErrorInfo, } from "./log.js";
4
4
  export { appendReceipt, verifyReceiptsFile, OKED_RECEIPTS_LOG, type LocalVerifyReport, } from "./receipts.js";
5
- export { findClaudeOkedHooks, settingsHasOkedHook, claudeUserSettingsPath, type ClaudeHookHit, type ClaudeHookScope, } from "./claude-hooks.js";
5
+ export { findClaudeOkedHooks, listClaudeOkedCommands, settingsHasOkedHook, claudeUserSettingsPath, matcherCoversTool, commandIsResolvable, type ClaudeHookHit, type ClaudeHookScope, type ClaudeOkedCommand, } from "./claude-hooks.js";
6
+ export { OKED_PLUGIN_NAME, OKED_PLUGIN_HOOK_FILE, isOkedPluginId, installedOkedRecords, resolveOkedPluginEnabled, loadInstalledOkedRecords, okedPluginIsEnabled, okedPluginBundleOnDisk, bundleExistsAt, settingsHookYieldsToPlugin, pluginHookYieldsToSettingsHook, type OkedInstallRecord, type OkedPluginResolution, } from "./claude-plugin.js";
6
7
  export { stringField, withNormalizedFields, asToolInput, shQuote, mapFileDelete, extractPatchPaths, mapPatch, } from "./normalize.js";
7
8
  export { pairDevice, writeOkedConfig, maskKey, type PairOptions } from "./pair.js";
8
9
  export { claudeSandboxEnforced, readClaudeSandbox, exclusionCoversCommand, SANDBOX_INIT_HINT, type ClaudeSandboxView, } from "./sandbox.js";
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@ export { decide } from "./decide.js";
2
2
  export { HOOK_TIMEOUT_SECONDS } from "./timeout.js";
3
3
  export { logDecision, errorInfo, OKED_HOOK_LOG, } from "./log.js";
4
4
  export { appendReceipt, verifyReceiptsFile, OKED_RECEIPTS_LOG, } from "./receipts.js";
5
- export { findClaudeOkedHooks, settingsHasOkedHook, claudeUserSettingsPath, } from "./claude-hooks.js";
5
+ export { findClaudeOkedHooks, listClaudeOkedCommands, settingsHasOkedHook, claudeUserSettingsPath, matcherCoversTool, commandIsResolvable, } from "./claude-hooks.js";
6
+ export { OKED_PLUGIN_NAME, OKED_PLUGIN_HOOK_FILE, isOkedPluginId, installedOkedRecords, resolveOkedPluginEnabled, loadInstalledOkedRecords, okedPluginIsEnabled, okedPluginBundleOnDisk, bundleExistsAt, settingsHookYieldsToPlugin, pluginHookYieldsToSettingsHook, } from "./claude-plugin.js";
6
7
  export { stringField, withNormalizedFields, asToolInput, shQuote, mapFileDelete, extractPatchPaths, mapPatch, } from "./normalize.js";
7
8
  export { pairDevice, writeOkedConfig, maskKey } from "./pair.js";
8
9
  export { claudeSandboxEnforced, readClaudeSandbox, exclusionCoversCommand, SANDBOX_INIT_HINT, } from "./sandbox.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oked/hook-core",
3
- "version": "0.6.24",
3
+ "version": "0.6.25",
4
4
  "description": "Shared OKed approval gate for coding-agent hooks. Builds the request, waits for a decision, checks the receipt, and fails closed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -47,7 +47,7 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@oked/sdk": "0.6.24"
50
+ "@oked/sdk": "0.6.25"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^26.6.5",