@operad-io/harness-claude 0.1.1 → 0.3.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
@@ -4,6 +4,10 @@
4
4
 
5
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
6
 
7
+ ## Signed in
8
+
9
+ The plugin's `signedIn` answer, which `GET /v1/plugins` carries for clients, comes from `claude auth status`: `true` when `loggedIn` is true, `false` when it is false. The answer is kept for a short time, so a client can ask it without starting a session; the probe runs without blocking `serve`. It is absent when `claude` is not found or its answer cannot be read, and only the yes/no is ever exposed, never an account detail.
10
+
7
11
  ## Documentation
8
12
 
9
13
  - User guide: [docs/user/dev.md](https://github.com/operad-io/operad/blob/main/docs/user/dev.md)
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@operad-io/harness-claude",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
7
7
  },
8
8
  "dependencies": {
9
9
  "@anthropic-ai/claude-agent-sdk": "^0.3.319",
10
- "@operad-io/access-match": "0.1.1",
11
- "@operad-io/engine": "0.1.1",
12
- "@operad-io/harness-process": "0.1.1"
10
+ "@operad-io/access-match": "0.3.0",
11
+ "@operad-io/engine": "0.3.0",
12
+ "@operad-io/harness-process": "0.3.0"
13
13
  },
14
14
  "description": "operad: the claude harness, a client of the Claude Agent SDK",
15
15
  "repository": {
package/src/access.ts CHANGED
@@ -55,6 +55,8 @@ export const INERT_TOOLS: readonly string[] = [
55
55
  "TodoWrite",
56
56
  "WebFetch",
57
57
  "WebSearch",
58
+ // The agent's own question asks a person through ctx.ask, not the profile.
59
+ "AskUserQuestion",
58
60
  "ExitPlanMode",
59
61
  "BashOutput",
60
62
  "KillShell",
@@ -64,7 +66,11 @@ export const INERT_TOOLS: readonly string[] = [
64
66
 
65
67
  /** Whether the profile has a rule that an unchecked call could break. */
66
68
  export function hasRules(profile: AccessProfile): boolean {
67
- return (profile.denyPaths ?? []).length > 0 || (profile.denyCommands ?? []).length > 0;
69
+ return (
70
+ (profile.denyPaths ?? []).length > 0 ||
71
+ (profile.denyCommands ?? []).length > 0 ||
72
+ (profile.level !== undefined && profile.level !== "full")
73
+ );
68
74
  }
69
75
 
70
76
  export type Translated =
@@ -96,73 +102,149 @@ export function translate(name: string, input: Readonly<Record<string, unknown>>
96
102
  return row.required ? { kind: "missing", field: row.from } : { kind: "mapped", tool: row.tool, input: {} };
97
103
  }
98
104
 
99
- export type AccessDecision =
100
- | { readonly allow: true }
105
+ /** What the profile says about one call, before any grant or person is asked. */
106
+ export type ProfileCheck =
107
+ | { readonly kind: "allow" }
101
108
  | {
102
- readonly allow: false;
109
+ readonly kind: "grant";
110
+ readonly waitId: string;
103
111
  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;
112
+ /** The same call also matches an ask rule; without a grant it would ask. */
113
+ readonly question?: CallQuestion | undefined;
114
+ }
115
+ | {
116
+ readonly kind: "ask";
117
+ readonly reason: string;
118
+ readonly question: CallQuestion;
119
+ }
120
+ | {
121
+ readonly kind: "refuse";
122
+ readonly reason: string;
123
+ /** The profile rule that refused, as the profile wrote it. */
124
+ readonly rule?: string | undefined;
106
125
  };
107
126
 
108
127
  /**
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.
128
+ * The profile's own verdict for one call: the one matcher `canUseTool` uses
129
+ * and the `PreToolUse` hook applies before a user setting's allow rule can.
130
+ * A grant is not a pass yet (the host may not use it up) and an ask is not a
131
+ * refusal; only `refuse` is final.
114
132
  */
115
- export async function decideAccess(
133
+ export function checkProfile(
116
134
  profile: AccessProfile,
117
135
  name: string,
118
136
  input: Readonly<Record<string, unknown>>,
119
137
  cwd: string,
120
- useGrant?: (waitId: string) => Promise<boolean>,
121
- ask?: (question: CallQuestion) => Promise<CallAnswer>,
122
- ): Promise<AccessDecision> {
138
+ ): ProfileCheck {
123
139
  const translated = translate(name, input, profile.allowMcp !== undefined);
124
- if (translated.kind === "inert") return { allow: true };
140
+ if (translated.kind === "inert") return { kind: "allow" };
125
141
  if (translated.kind === "unmapped") {
126
- if (!hasRules(profile)) return { allow: true };
142
+ if (!hasRules(profile)) return { kind: "allow" };
127
143
  return {
128
- allow: false,
144
+ kind: "refuse",
129
145
  reason: `tool "${name}" is not one the access profile can check; it is refused while denyPaths or denyCommands is set`,
130
146
  };
131
147
  }
132
148
  if (translated.kind === "missing") {
133
- if (!hasRules(profile)) return { allow: true };
149
+ if (!hasRules(profile)) return { kind: "allow" };
134
150
  return {
135
- allow: false,
151
+ kind: "refuse",
136
152
  reason: `tool "${name}" has no ${translated.field}; it is refused while denyPaths or denyCommands is set`,
137
153
  };
138
154
  }
139
155
 
140
156
  const call = { tool: translated.tool, input: translated.input, cwd };
141
157
  const verdict = match(profile, call);
142
- if (verdict.allow) return { allow: true };
158
+ if (verdict.allow) return { kind: "allow" };
159
+ const question: CallQuestion | undefined =
160
+ verdict.ask === true
161
+ ? {
162
+ kind: verdict.kind,
163
+ value: verdict.value,
164
+ ...(verdict.tool === undefined ? {} : { tool: verdict.tool }),
165
+ ...(verdict.outward === undefined ? {} : { outward: verdict.outward }),
166
+ }
167
+ : undefined;
143
168
  // A one-time permission covers one exact call that would be refused. The
144
169
  // host writes the fact before it answers, so a crash after it cannot give
145
170
  // the permission twice.
146
171
  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 };
172
+ if (grant !== undefined) {
173
+ return {
174
+ kind: "grant",
175
+ waitId: grant.waitId,
176
+ reason: verdict.reason,
177
+ ...(question === undefined ? {} : { question }),
178
+ };
155
179
  }
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" };
180
+ if (question !== undefined) return { kind: "ask", reason: verdict.reason, question };
181
+ return {
182
+ kind: "refuse",
183
+ reason: verdict.reason,
184
+ ...(verdict.rule === undefined ? {} : { rule: verdict.rule }),
185
+ };
186
+ }
187
+
188
+ export type AccessDecision =
189
+ | { readonly allow: true }
190
+ | {
191
+ readonly allow: false;
192
+ readonly reason: string;
193
+ /** The wait for a person ended; the program is about to be ended and holds the call. */
194
+ readonly stop?: true;
195
+ };
196
+
197
+ /**
198
+ * Whether one call of claude may run. `useGrant` asks the host to use up a
199
+ * one-time permission; without it no grant applies. `ask` asks a person about a
200
+ * call the profile says must ask (`askCommands`, `askPaths`); without it such a call is
201
+ * refused. A deny wins over an ask, so `ask` only ever sees a call no deny
202
+ * rule matched.
203
+ */
204
+ export async function decideAccess(
205
+ profile: AccessProfile,
206
+ name: string,
207
+ input: Readonly<Record<string, unknown>>,
208
+ cwd: string,
209
+ useGrant?: (waitId: string) => Promise<boolean>,
210
+ ask?: (question: CallQuestion) => Promise<CallAnswer>,
211
+ ): Promise<AccessDecision> {
212
+ const check = checkProfile(profile, name, input, cwd);
213
+ if (check.kind === "allow") return { allow: true };
214
+ if (check.kind === "grant") {
215
+ if (useGrant !== undefined) {
216
+ let used = false;
217
+ try {
218
+ used = await useGrant(check.waitId);
219
+ } catch {
220
+ used = false;
221
+ }
222
+ if (used) return { allow: true };
162
223
  }
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"}` };
224
+ if (check.question !== undefined && ask !== undefined) {
225
+ return askFor(ask, check.question, check.reason);
226
+ }
227
+ return { allow: false, reason: check.reason };
228
+ }
229
+ if (check.kind === "ask") {
230
+ if (ask === undefined) return { allow: false, reason: check.reason };
231
+ return askFor(ask, check.question, check.reason);
232
+ }
233
+ return { allow: false, reason: check.reason };
234
+ }
235
+
236
+ async function askFor(
237
+ ask: (question: CallQuestion) => Promise<CallAnswer>,
238
+ question: CallQuestion,
239
+ reason: string,
240
+ ): Promise<AccessDecision> {
241
+ let answer: CallAnswer;
242
+ try {
243
+ answer = await ask(question);
244
+ } catch {
245
+ answer = { decision: "deny", reason: "the question could not be asked" };
166
246
  }
167
- return { allow: false, reason: verdict.reason };
247
+ if (answer.decision === "allow") return { allow: true };
248
+ if (answer.decision === "stop") return { allow: false, reason: "waiting for an answer", stop: true };
249
+ return { allow: false, reason: `${reason}; ${answer.reason ?? "a person refused it"}` };
168
250
  }
@@ -6,6 +6,10 @@
6
6
  */
7
7
 
8
8
  import { realpathSync } from "node:fs";
9
+ import { realpath } from "node:fs/promises";
10
+ import { compareVersions } from "@operad-io/harness-process";
11
+
12
+ export { compareVersions };
9
13
 
10
14
  /** The oldest Claude Code the worker is written for. */
11
15
  export const CLAUDE_FLOOR = "2.1.319";
@@ -16,6 +20,17 @@ export const DEFAULT_CLAUDE_COMMAND = "claude";
16
20
  /** How long `claude --version` or `claude auth status` may take. */
17
21
  const PROBE_TIMEOUT_MS = 30_000;
18
22
 
23
+ /**
24
+ * How many times a probe that must print is run in all: its answer, and one
25
+ * more ask when that answer is an empty success. A spawned command can exit 0
26
+ * with nothing on its output, which is not an answer; one more ask is enough,
27
+ * and it is not five waits for a probe that genuinely prints nothing.
28
+ */
29
+ export const PROBE_EMPTY_ATTEMPTS = 2;
30
+
31
+ /** How long `claude auth status` may take when a client asks for the login state. */
32
+ export const SIGNED_IN_PROBE_TIMEOUT_MS = 10_000;
33
+
19
34
  /** The check could not pass; the message says what to do. */
20
35
  export class ClaudeInstallError extends Error {
21
36
  constructor(message: string) {
@@ -33,27 +48,28 @@ export class ClaudeNotFoundError extends ClaudeInstallError {
33
48
  }
34
49
  }
35
50
 
51
+ /** The command on `path`, before its real path is resolved. */
52
+ function whichClaude(command: string | undefined, path: string | undefined): string {
53
+ const wanted = command ?? DEFAULT_CLAUDE_COMMAND;
54
+ const found = wanted.includes("/") ? Bun.which(wanted) : Bun.which(wanted, { PATH: path ?? "" });
55
+ if (found === null) throw new ClaudeNotFoundError(wanted);
56
+ return found;
57
+ }
58
+
36
59
  /**
37
60
  * The real path of the claude command: a name looked up on `path`, or a path.
38
61
  * Throws `ClaudeNotFoundError` when there is none.
39
62
  */
40
63
  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);
64
+ return realpathSync(whichClaude(command, path));
45
65
  }
46
66
 
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;
67
+ /** As `findClaude`, but resolving the real path without blocking the event loop. */
68
+ export async function findClaudeAsync(
69
+ command: string | undefined,
70
+ path: string | undefined = process.env.PATH,
71
+ ): Promise<string> {
72
+ return await realpath(whichClaude(command, path));
57
73
  }
58
74
 
59
75
  /** What `operad plugin check` learns about the install. */
@@ -76,7 +92,7 @@ interface Ran {
76
92
  readonly stdout: string;
77
93
  }
78
94
 
79
- function runClaude(path: string, args: readonly string[]): Ran {
95
+ function runClaudeOnce(path: string, args: readonly string[]): Ran {
80
96
  const ran = Bun.spawnSync([path, ...args], {
81
97
  stdin: "ignore",
82
98
  stdout: "pipe",
@@ -86,6 +102,19 @@ function runClaude(path: string, args: readonly string[]): Ran {
86
102
  return { exitCode: ran.exitCode, stdout: ran.stdout.toString("utf8") };
87
103
  }
88
104
 
105
+ /** Both probes must print on success, so an empty success is asked again. */
106
+ function runClaude(path: string, args: readonly string[]): Ran {
107
+ let ran = runClaudeOnce(path, args);
108
+ for (
109
+ let attempt = 1;
110
+ attempt < PROBE_EMPTY_ATTEMPTS && ran.exitCode === 0 && ran.stdout.trim().length === 0;
111
+ attempt += 1
112
+ ) {
113
+ ran = runClaudeOnce(path, args);
114
+ }
115
+ return ran;
116
+ }
117
+
89
118
  /** A login field that is safe to print: a short word, not free text. */
90
119
  function word(value: unknown): string | undefined {
91
120
  return typeof value === "string" && /^[A-Za-z0-9_. -]{1,40}$/.test(value) ? value : undefined;
@@ -115,6 +144,76 @@ function loginKind(stdout: string): string | undefined {
115
144
  return extra.length === 0 ? method : `${method} (${extra.join(", ")})`;
116
145
  }
117
146
 
147
+ /**
148
+ * The `loggedIn` answer of `claude auth status`, when the output carries a
149
+ * boolean; undefined when it cannot be read. Only this field is read.
150
+ */
151
+ function loggedInOf(stdout: string): boolean | undefined {
152
+ let value: unknown;
153
+ try {
154
+ value = JSON.parse(stdout);
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
159
+ const answer = Reflect.get(value, "loggedIn");
160
+ return typeof answer === "boolean" ? answer : undefined;
161
+ }
162
+
163
+ interface AsyncRan {
164
+ readonly exitCode: number | null;
165
+ readonly stdout: string;
166
+ }
167
+
168
+ /** Runs `claude` without blocking the event loop, and gives up after the timeout. */
169
+ async function runClaudeAsync(path: string, args: readonly string[]): Promise<AsyncRan | undefined> {
170
+ const signal = AbortSignal.timeout(SIGNED_IN_PROBE_TIMEOUT_MS);
171
+ let child: ReturnType<typeof Bun.spawn>;
172
+ try {
173
+ child = Bun.spawn([path, ...args], {
174
+ stdin: "ignore",
175
+ stdout: "pipe",
176
+ stderr: "ignore",
177
+ signal,
178
+ });
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ try {
183
+ const stream = child.stdout;
184
+ if (!(stream instanceof ReadableStream)) return undefined;
185
+ const [stdout, exitCode] = await Promise.all([
186
+ new Response(stream).text(),
187
+ child.exited,
188
+ ]);
189
+ return signal.aborted ? undefined : { exitCode, stdout };
190
+ } catch {
191
+ return undefined;
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Whether the user's claude is signed in, from `claude auth status`: true or
197
+ * false when that answer can be read, undefined when there is no claude or the
198
+ * answer is not usable. It never blocks the event loop and reads no account
199
+ * detail, only `loggedIn`.
200
+ */
201
+ export async function claudeSignedIn(command: string | undefined): Promise<boolean | undefined> {
202
+ let path: string;
203
+ try {
204
+ path = await findClaudeAsync(command);
205
+ } catch {
206
+ return undefined;
207
+ }
208
+ const ran = await runClaudeAsync(path, ["auth", "status"]);
209
+ if (ran === undefined) return undefined;
210
+ const loggedIn = loggedInOf(ran.stdout);
211
+ if (loggedIn === undefined) return undefined;
212
+ // A failing exit with `loggedIn: true` contradicts itself; do not guess.
213
+ if (ran.exitCode !== 0 && loggedIn) return undefined;
214
+ return loggedIn;
215
+ }
216
+
118
217
  /**
119
218
  * Finds the installed claude and checks it: the version is at or above the
120
219
  * floor and the login works. Throws `ClaudeInstallError` with what to do.