@operad-io/harness-claude 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @operad-io/harness-claude
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The claude harness.** Runs a prompt through the Claude Agent SDK, which starts your own `claude` command. operad bundles no claude.
4
+
5
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
6
+
7
+ ## Documentation
8
+
9
+ - User guide: [docs/user/dev.md](https://github.com/operad-io/operad/blob/main/docs/user/dev.md)
10
+ - Website: <https://operad.io>
11
+ - Developer reference: `REFERENCE.md` in this directory
12
+
13
+ MIT licensed.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@operad-io/harness-claude",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@anthropic-ai/claude-agent-sdk": "^0.3.319",
10
+ "@operad-io/access-match": "0.1.0",
11
+ "@operad-io/engine": "0.1.0",
12
+ "@operad-io/harness-process": "0.1.0"
13
+ },
14
+ "description": "operad: the claude harness, a client of the Claude Agent SDK",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/operad-io/operad.git",
18
+ "directory": "packages/harness/claude"
19
+ },
20
+ "license": "MIT",
21
+ "files": [
22
+ "src",
23
+ "README.md",
24
+ "LICENSE"
25
+ ]
26
+ }
package/src/access.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The access profile applied to claude's tool calls
3
+ * (ADR 0024 D6).
4
+ *
5
+ * `@operad-io/access-match` judges calls by lower-case tool names and the
6
+ * input fields `command` and `path`; claude names its tools in Title case and
7
+ * keeps the path in `file_path` (or `notebook_path`). `TOOL_TABLE` is the one
8
+ * place that maps the two.
9
+ */
10
+
11
+ import { findGrant, match, MCP_TOOL, type AccessProfile } from "@operad-io/access-match";
12
+ import { OPERAD_TOOL_PREFIX, type CallAnswer, type CallQuestion } from "@operad-io/harness-process";
13
+
14
+ export type { CallAnswer, CallQuestion };
15
+
16
+ /** One tool of claude and what `access-match` calls it. */
17
+ export interface ToolRow {
18
+ /** The tool name claude uses. */
19
+ readonly claude: string;
20
+ /** The name `access-match` knows. */
21
+ readonly tool: "bash" | "read" | "write" | "edit" | "grep" | "find" | "ls";
22
+ /** The input field of claude's call that holds the command or the path. */
23
+ readonly from: "command" | "file_path" | "notebook_path" | "path";
24
+ /** The field `access-match` reads it from. */
25
+ readonly to: "command" | "path";
26
+ /**
27
+ * Whether the call must carry that field. When it must and does not, the
28
+ * call is refused while a rule is set: a call without its target cannot be
29
+ * judged. `Glob` and `Grep` search the working directory without one.
30
+ */
31
+ readonly required: boolean;
32
+ }
33
+
34
+ export const TOOL_TABLE: readonly ToolRow[] = [
35
+ { claude: "Bash", tool: "bash", from: "command", to: "command", required: true },
36
+ { claude: "Read", tool: "read", from: "file_path", to: "path", required: true },
37
+ { claude: "Write", tool: "write", from: "file_path", to: "path", required: true },
38
+ { claude: "Edit", tool: "edit", from: "file_path", to: "path", required: true },
39
+ { claude: "MultiEdit", tool: "edit", from: "file_path", to: "path", required: true },
40
+ { claude: "NotebookEdit", tool: "edit", from: "notebook_path", to: "path", required: true },
41
+ { claude: "Grep", tool: "grep", from: "path", to: "path", required: false },
42
+ { claude: "Glob", tool: "find", from: "path", to: "path", required: false },
43
+ ];
44
+
45
+ /**
46
+ * Tools that neither run a command nor name a file, so no deny rule can
47
+ * apply to them. A subagent (`Task`, `Agent`) is here because every tool call
48
+ * of the subagent comes to `canUseTool` too and is judged on its own.
49
+ *
50
+ * A tool in neither list is unmapped: it is allowed only when the profile
51
+ * has no `denyPaths` and no `denyCommands`, since a rule that could match it
52
+ * cannot be checked. That covers MCP tools and any tool a later claude adds.
53
+ */
54
+ export const INERT_TOOLS: readonly string[] = [
55
+ "TodoWrite",
56
+ "WebFetch",
57
+ "WebSearch",
58
+ "ExitPlanMode",
59
+ "BashOutput",
60
+ "KillShell",
61
+ "Task",
62
+ "Agent",
63
+ ];
64
+
65
+ /** Whether the profile has a rule that an unchecked call could break. */
66
+ export function hasRules(profile: AccessProfile): boolean {
67
+ return (profile.denyPaths ?? []).length > 0 || (profile.denyCommands ?? []).length > 0;
68
+ }
69
+
70
+ export type Translated =
71
+ | { readonly kind: "mapped"; readonly tool: ToolRow["tool"] | typeof MCP_TOOL; readonly input: Record<string, unknown> }
72
+ | { readonly kind: "missing"; readonly field: string }
73
+ | { readonly kind: "inert" }
74
+ | { readonly kind: "unmapped" };
75
+
76
+ /** Claude's call in the words `access-match` takes. */
77
+ export function translate(name: string, input: Readonly<Record<string, unknown>>, mcpUnderProfile = false): Translated {
78
+ // Operad's own tools run under the owner's MCP allow lists, not the profile.
79
+ if (name.startsWith(OPERAD_TOOL_PREFIX)) return { kind: "inert" };
80
+ // With `allowMcp` in the profile, a tool of another MCP server (`mcp__<server>__<tool>`) is judged by server and tool.
81
+ if (mcpUnderProfile && name.startsWith("mcp__")) {
82
+ const rest = name.slice("mcp__".length);
83
+ const at = rest.indexOf("__");
84
+ if (at > 0 && at + 2 < rest.length) {
85
+ return { kind: "mapped", tool: MCP_TOOL, input: { server: rest.slice(0, at), tool: rest.slice(at + 2) } };
86
+ }
87
+ }
88
+ const row = TOOL_TABLE.find((candidate) => candidate.claude === name);
89
+ if (row === undefined) {
90
+ return INERT_TOOLS.includes(name) ? { kind: "inert" } : { kind: "unmapped" };
91
+ }
92
+ const value = input[row.from];
93
+ if (typeof value === "string" && value.length > 0) {
94
+ return { kind: "mapped", tool: row.tool, input: { [row.to]: value } };
95
+ }
96
+ return row.required ? { kind: "missing", field: row.from } : { kind: "mapped", tool: row.tool, input: {} };
97
+ }
98
+
99
+ export type AccessDecision =
100
+ | { readonly allow: true }
101
+ | {
102
+ readonly allow: false;
103
+ readonly reason: string;
104
+ /** The wait for a person ended; the program is about to be ended and holds the call. */
105
+ readonly stop?: true;
106
+ };
107
+
108
+ /**
109
+ * Whether one call of claude may run. `useGrant` asks the host to use up a
110
+ * one-time permission; without it no grant applies. `ask` asks a person about a
111
+ * call the profile says must ask (`askCommands`, `askPaths`); without it such a call is
112
+ * refused. A deny wins over an ask, so `ask` only ever sees a call no deny
113
+ * rule matched.
114
+ */
115
+ export async function decideAccess(
116
+ profile: AccessProfile,
117
+ name: string,
118
+ input: Readonly<Record<string, unknown>>,
119
+ cwd: string,
120
+ useGrant?: (waitId: string) => Promise<boolean>,
121
+ ask?: (question: CallQuestion) => Promise<CallAnswer>,
122
+ ): Promise<AccessDecision> {
123
+ const translated = translate(name, input, profile.allowMcp !== undefined);
124
+ if (translated.kind === "inert") return { allow: true };
125
+ if (translated.kind === "unmapped") {
126
+ if (!hasRules(profile)) return { allow: true };
127
+ return {
128
+ allow: false,
129
+ reason: `tool "${name}" is not one the access profile can check; it is refused while denyPaths or denyCommands is set`,
130
+ };
131
+ }
132
+ if (translated.kind === "missing") {
133
+ if (!hasRules(profile)) return { allow: true };
134
+ return {
135
+ allow: false,
136
+ reason: `tool "${name}" has no ${translated.field}; it is refused while denyPaths or denyCommands is set`,
137
+ };
138
+ }
139
+
140
+ const call = { tool: translated.tool, input: translated.input, cwd };
141
+ const verdict = match(profile, call);
142
+ if (verdict.allow) return { allow: true };
143
+ // A one-time permission covers one exact call that would be refused. The
144
+ // host writes the fact before it answers, so a crash after it cannot give
145
+ // the permission twice.
146
+ const grant = findGrant(profile, call);
147
+ if (grant !== undefined && useGrant !== undefined) {
148
+ let used = false;
149
+ try {
150
+ used = await useGrant(grant.waitId);
151
+ } catch {
152
+ used = false;
153
+ }
154
+ if (used) return { allow: true };
155
+ }
156
+ if (verdict.ask === true && ask !== undefined) {
157
+ let answer: CallAnswer;
158
+ try {
159
+ answer = await ask({ kind: verdict.kind, value: verdict.value, ...(verdict.tool === undefined ? {} : { tool: verdict.tool }) });
160
+ } catch {
161
+ answer = { decision: "deny", reason: "the question could not be asked" };
162
+ }
163
+ if (answer.decision === "allow") return { allow: true };
164
+ if (answer.decision === "stop") return { allow: false, reason: "waiting for an answer", stop: true };
165
+ return { allow: false, reason: `${verdict.reason}; ${answer.reason ?? "a person refused it"}` };
166
+ }
167
+ return { allow: false, reason: verdict.reason };
168
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The user's own `claude`: found, never bundled
3
+ * (ADR 0024 D2, D10). `inspectClaude`
4
+ * is what `operad plugin check` runs: `claude --version` and
5
+ * `claude auth status`.
6
+ */
7
+
8
+ import { realpathSync } from "node:fs";
9
+
10
+ /** The oldest Claude Code the worker is written for. */
11
+ export const CLAUDE_FLOOR = "2.1.319";
12
+
13
+ /** The command looked up on PATH when the `command` setting is unset. */
14
+ export const DEFAULT_CLAUDE_COMMAND = "claude";
15
+
16
+ /** How long `claude --version` or `claude auth status` may take. */
17
+ const PROBE_TIMEOUT_MS = 30_000;
18
+
19
+ /** The check could not pass; the message says what to do. */
20
+ export class ClaudeInstallError extends Error {
21
+ constructor(message: string) {
22
+ super(message);
23
+ this.name = "ClaudeInstallError";
24
+ }
25
+ }
26
+
27
+ export class ClaudeNotFoundError extends ClaudeInstallError {
28
+ constructor(command: string) {
29
+ super(
30
+ `no \`${command}\` command was found; install claude first (https://code.claude.com) or set the command setting to its path`,
31
+ );
32
+ this.name = "ClaudeNotFoundError";
33
+ }
34
+ }
35
+
36
+ /**
37
+ * The real path of the claude command: a name looked up on `path`, or a path.
38
+ * Throws `ClaudeNotFoundError` when there is none.
39
+ */
40
+ export function findClaude(command: string | undefined, path: string | undefined = process.env.PATH): string {
41
+ const wanted = command ?? DEFAULT_CLAUDE_COMMAND;
42
+ const found = wanted.includes("/") ? Bun.which(wanted) : Bun.which(wanted, { PATH: path ?? "" });
43
+ if (found === null) throw new ClaudeNotFoundError(wanted);
44
+ return realpathSync(found);
45
+ }
46
+
47
+ /** Negative, zero or positive as version `a` is below, equal to or above `b`. */
48
+ export function compareVersions(a: string, b: string): number {
49
+ const parts = (version: string): number[] => version.split(".").map((part) => Number(part));
50
+ const left = parts(a);
51
+ const right = parts(b);
52
+ for (let at = 0; at < 3; at += 1) {
53
+ const diff = (left[at] ?? 0) - (right[at] ?? 0);
54
+ if (diff !== 0) return diff;
55
+ }
56
+ return 0;
57
+ }
58
+
59
+ /** What `operad plugin check` learns about the install. */
60
+ export interface ClaudeInstall {
61
+ readonly path: string;
62
+ readonly version: string;
63
+ /** The login kind, such as `claude.ai (max)`; never an account detail. */
64
+ readonly login: string;
65
+ }
66
+
67
+ export interface InspectOptions {
68
+ /** The PATH to search; defaults to the process's own. */
69
+ readonly path?: string | undefined;
70
+ /** The floor to compare with; defaults to `CLAUDE_FLOOR`. */
71
+ readonly floor?: string | undefined;
72
+ }
73
+
74
+ interface Ran {
75
+ readonly exitCode: number | null;
76
+ readonly stdout: string;
77
+ }
78
+
79
+ function runClaude(path: string, args: readonly string[]): Ran {
80
+ const ran = Bun.spawnSync([path, ...args], {
81
+ stdin: "ignore",
82
+ stdout: "pipe",
83
+ stderr: "ignore",
84
+ timeout: PROBE_TIMEOUT_MS,
85
+ });
86
+ return { exitCode: ran.exitCode, stdout: ran.stdout.toString("utf8") };
87
+ }
88
+
89
+ /** A login field that is safe to print: a short word, not free text. */
90
+ function word(value: unknown): string | undefined {
91
+ return typeof value === "string" && /^[A-Za-z0-9_. -]{1,40}$/.test(value) ? value : undefined;
92
+ }
93
+
94
+ /**
95
+ * The login kind from `claude auth status`. Only the kind is read: the e-mail,
96
+ * the organisation and everything else in that output are left alone.
97
+ */
98
+ function loginKind(stdout: string): string | undefined {
99
+ let value: unknown;
100
+ try {
101
+ value = JSON.parse(stdout);
102
+ } catch {
103
+ throw new ClaudeInstallError("`claude auth status` printed something this check cannot read");
104
+ }
105
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
106
+ throw new ClaudeInstallError("`claude auth status` printed something this check cannot read");
107
+ }
108
+ if (Reflect.get(value, "loggedIn") !== true) return undefined;
109
+ const method = word(Reflect.get(value, "authMethod")) ?? "unknown login";
110
+ const plan = word(Reflect.get(value, "subscriptionType"));
111
+ const provider = word(Reflect.get(value, "apiProvider"));
112
+ const extra = [plan, provider !== undefined && provider !== "firstParty" ? provider : undefined].filter(
113
+ (part): part is string => part !== undefined,
114
+ );
115
+ return extra.length === 0 ? method : `${method} (${extra.join(", ")})`;
116
+ }
117
+
118
+ /**
119
+ * Finds the installed claude and checks it: the version is at or above the
120
+ * floor and the login works. Throws `ClaudeInstallError` with what to do.
121
+ */
122
+ export function inspectClaude(
123
+ command: string | undefined,
124
+ options: InspectOptions = {},
125
+ ): ClaudeInstall {
126
+ const floor = options.floor ?? CLAUDE_FLOOR;
127
+ const path = findClaude(command, options.path);
128
+
129
+ const versionRun = runClaude(path, ["--version"]);
130
+ const match = /^\s*(\d+\.\d+\.\d+)\b/.exec(versionRun.stdout);
131
+ if (versionRun.exitCode !== 0 || match === null || match[1] === undefined) {
132
+ const seen = versionRun.stdout.trim().split("\n")[0]?.slice(0, 80) ?? "";
133
+ throw new ClaudeInstallError(
134
+ `\`${path} --version\` did not print a version this check can read${seen.length === 0 ? "" : ` (it printed "${seen}")`}`,
135
+ );
136
+ }
137
+ const version = match[1];
138
+ if (compareVersions(version, floor) < 0) {
139
+ throw new ClaudeInstallError(
140
+ `claude ${version} at ${path} is older than the floor ${floor}; update claude (claude update)`,
141
+ );
142
+ }
143
+
144
+ const status = runClaude(path, ["auth", "status"]);
145
+ const login = loginKind(status.stdout);
146
+ if (login === undefined || status.exitCode !== 0) {
147
+ throw new ClaudeInstallError("claude is not logged in; run `claude auth login`, then check again");
148
+ }
149
+ return { path, version, login };
150
+ }
151
+
152
+ /** The version of the Agent SDK this package imports, or undefined if it cannot be read. */
153
+ export async function sdkVersion(): Promise<string | undefined> {
154
+ try {
155
+ const entry = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", import.meta.dir);
156
+ let dir = entry;
157
+ for (let step = 0; step < 6; step += 1) {
158
+ dir = dir.slice(0, dir.lastIndexOf("/"));
159
+ const file = Bun.file(`${dir}/package.json`);
160
+ if (!(await file.exists())) continue;
161
+ const manifest: unknown = await file.json();
162
+ if (
163
+ typeof manifest === "object" &&
164
+ manifest !== null &&
165
+ Reflect.get(manifest, "name") === "@anthropic-ai/claude-agent-sdk"
166
+ ) {
167
+ const version: unknown = Reflect.get(manifest, "version");
168
+ return typeof version === "string" ? version : undefined;
169
+ }
170
+ }
171
+ } catch {
172
+ // The SDK is only reported, never required here.
173
+ }
174
+ return undefined;
175
+ }