@operad-io/harness-radian 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-radian
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 radian harness.** Runs `radian exec` in a directory as one agent step and reads its closing result.
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,25 @@
1
1
  {
2
2
  "name": "@operad-io/harness-radian",
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
+ "@operad-io/access-match": "0.1.0",
10
+ "@operad-io/engine": "0.1.0",
11
+ "@operad-io/harness-process": "0.1.0"
12
+ },
13
+ "description": "operad: the radian harness",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/operad-io/operad.git",
17
+ "directory": "packages/harness/radian"
18
+ },
19
+ "license": "MIT",
20
+ "files": [
21
+ "src",
22
+ "README.md",
23
+ "LICENSE"
24
+ ]
25
+ }
package/src/hook.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The program radian runs before each tool call (a `PreToolUse` hook) when the
3
+ * run's access profile has rules: `bun hook.ts <profile file>`. It reads the
4
+ * call from stdin, asks the access profile and exits 2 with the reason on stderr
5
+ * to deny it, which radian does before the tool runs; it exits 0 to let it go.
6
+ * Any other exit also denies, so a broken hook never lets a call through.
7
+ */
8
+
9
+ import { readFileSync } from "node:fs";
10
+ import { readProfile } from "@operad-io/access-match";
11
+ import { radianRefusal } from "./refusal.ts";
12
+
13
+ const file = process.argv[2] ?? "";
14
+ const read = readProfile(JSON.parse(readFileSync(file, "utf8")));
15
+ if (!read.ok) {
16
+ process.stderr.write(`the access profile is not usable: ${read.message}\n`);
17
+ process.exit(3);
18
+ }
19
+ const call: unknown = JSON.parse(await Bun.stdin.text());
20
+ const record = typeof call === "object" && call !== null ? (call as Record<string, unknown>) : {};
21
+ const toolName = typeof record.tool_name === "string" ? record.tool_name : "";
22
+ const cwd = typeof record.cwd === "string" ? record.cwd : process.cwd();
23
+ const why = radianRefusal(read.profile, toolName, record.tool_input, cwd);
24
+ if (why !== undefined) {
25
+ process.stderr.write(`${toolName} call ${why}\n`);
26
+ process.exit(2);
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,728 @@
1
+ /**
2
+ * The radian harness: one `agent` step that runs `radian exec` in a directory
3
+ * and reads its closing Result record, plus the `radian:prompt` flow
4
+ * that runs one prompt. Only the plugin interface and the process helper are
5
+ * used; the kernel never knows how radian is started.
6
+ */
7
+
8
+ import pkg from "../package.json" with { type: "json" };
9
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
10
+ import { dirname } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { mapRadianCall } from "./refusal.ts";
13
+ export { radianRefusal } from "./refusal.ts";
14
+ import { firstErrorLine, match, readProfile, secretValuesOf, summarizeCall, type AccessProfile } from "@operad-io/access-match";
15
+ import {
16
+ isRecord,
17
+ paramsObject,
18
+ defineFlow,
19
+ definePlugin,
20
+ type AgentResultData,
21
+ type PluginStepResult,
22
+ type StepContext,
23
+ } from "@operad-io/engine";
24
+ import {
25
+ CONCURRENCY_SETTING,
26
+ askNote,
27
+ eventNote,
28
+ directoryError,
29
+ findCommand,
30
+ flagValue,
31
+ JsonlLog,
32
+ deliverLine,
33
+ MAX_LINE_CHARS,
34
+ OPERAD_SERVER,
35
+ operadToolsOf,
36
+ mountedServersOf,
37
+ optionalText,
38
+ secs,
39
+ serverCommand,
40
+ standardUsage,
41
+ stringListParam,
42
+ text,
43
+ type RawCost,
44
+ type RawCounts,
45
+ type UsageSource,
46
+ modelLimit,
47
+ runAgent,
48
+ systemClock,
49
+ type AgentRunOutcome,
50
+ type Clock,
51
+ type ToolEvent,
52
+ } from "@operad-io/harness-process";
53
+
54
+ export { EVENT_NOTE_TEMPLATE, eventNote } from "@operad-io/harness-process";
55
+
56
+ /** How long an agent may run before the step stops it. */
57
+ export const DEFAULT_WALL_TIME_SECS = 300;
58
+
59
+ /** How long an agent may go without a new output line. */
60
+ export const DEFAULT_STALL_SECS = 600;
61
+
62
+ /**
63
+ * A prompt longer than this goes through stdin. It is well below the OS
64
+ * argument limit, so the argv never approaches it.
65
+ */
66
+ export const PROMPT_ARG_SAFE_BYTES = 128 * 1024;
67
+
68
+ /**
69
+ * Reads one radian JSONL line and reports the tool call it starts or settles.
70
+ * Radian writes the event under `event` and a type under `type`.
71
+ */
72
+ export function radianToolEvent(line: string): ToolEvent | undefined {
73
+ let value: unknown;
74
+ try {
75
+ value = JSON.parse(line);
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ if (!isRecord(value)) return undefined;
80
+ const event = typeof value.event === "string" ? value.event : value.type;
81
+ if (event === "ToolExecutionStarted") return "tool-start";
82
+ if (event === "ToolExecutionSettled") return "tool-end";
83
+ return undefined;
84
+ }
85
+
86
+ function firstString(record: Record<string, unknown>, keys: readonly string[]): string | undefined {
87
+ for (const key of keys) {
88
+ const value = record[key];
89
+ if (typeof value === "string" && value.length > 0) return value;
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ /**
95
+ * Radian's own tool names, read as the access-match tool the profile judges:
96
+ * `shell` is a bash command, `patch` an edit, `glob` a find, and any other tool
97
+ * with a `path` is a read of it. The log still names the radian tool.
98
+ */
99
+ function summarizeRadianCall(
100
+ profile: AccessProfile,
101
+ toolName: string,
102
+ args: unknown,
103
+ cwd: string,
104
+ secrets: readonly string[],
105
+ ): string | undefined {
106
+ if (!isRecord(args)) return undefined;
107
+ const lower = toolName.toLowerCase();
108
+ const { mapped, input } = mapRadianCall(toolName, args);
109
+ const summary = summarizeCall(profile, mapped, input, cwd, { secrets, keepLines: true });
110
+ const denied = `${mapped} denied by the access profile`;
111
+ if (summary !== undefined && summary.startsWith(denied)) return `${toolName}${summary.slice(mapped.length)}`;
112
+ // Unknown tools keep the plain summary of their main argument.
113
+ if (mapped === "read" && lower !== "read") return summarizeCall({}, toolName, args, cwd, { secrets });
114
+ return summary;
115
+ }
116
+
117
+ /**
118
+ * Turns radian's tool journal lines into the log lines the other harnesses
119
+ * write: `tool_execution_start` with the command or path summary and its start
120
+ * time, `tool_execution_end` with the duration and an error's first line. Any
121
+ * other line, and a tool line it cannot read, is returned as radian wrote it.
122
+ * The summary is cut, has secret values masked, and says only that the call
123
+ * was denied where the run's access profile refuses it.
124
+ */
125
+ export function radianLogLine(
126
+ line: string,
127
+ now: () => number,
128
+ open: Map<string, { at: number; name: string; denied?: boolean }>,
129
+ cwd: string,
130
+ profile: AccessProfile = {},
131
+ secrets: readonly string[] = [],
132
+ ): string {
133
+ const kind = radianToolEvent(line);
134
+ if (kind === undefined) return line;
135
+ let value: unknown;
136
+ try {
137
+ value = JSON.parse(line);
138
+ } catch {
139
+ return line;
140
+ }
141
+ if (!isRecord(value)) return line;
142
+ const nested = isRecord(value.data) ? value.data : isRecord(value.payload) ? value.payload : {};
143
+ const field = (keys: readonly string[]): string | undefined =>
144
+ firstString(value as Record<string, unknown>, keys) ?? firstString(nested, keys);
145
+ const id = field(["toolCallId", "tool_call_id", "callId", "call_id", "id"]) ?? "";
146
+ const name = field(["toolName", "tool_name", "tool", "name"]);
147
+ if (kind === "tool-start") {
148
+ const at = now();
149
+ const toolName = name ?? "tool";
150
+ const args = value.input ?? value.args ?? value.arguments ?? nested.input ?? nested.args ?? nested.arguments;
151
+ const summary = summarizeRadianCall(profile, toolName, args, cwd, secrets);
152
+ open.set(id, { at, name: toolName, denied: summary?.includes(" denied by the access profile") === true });
153
+ return JSON.stringify({
154
+ type: "tool_execution_start",
155
+ toolCallId: id,
156
+ toolName,
157
+ at,
158
+ ...(summary === undefined ? {} : { input: summary }),
159
+ });
160
+ }
161
+ const begun = open.get(id);
162
+ open.delete(id);
163
+ // Radian settles a call as data.result: `is_error` and content blocks of
164
+ // `{ text: { text } }`. Only the first error line of that text is kept.
165
+ const settled = isRecord(nested.result) ? nested.result : {};
166
+ const isError =
167
+ value.isError === true || nested.isError === true || value.is_error === true || settled.is_error === true;
168
+ const blocks = Array.isArray(settled.content) ? settled.content : [];
169
+ const first: unknown = blocks[0];
170
+ const blockText =
171
+ isRecord(first) && isRecord(first.text) && typeof first.text.text === "string" ? first.text.text : undefined;
172
+ const error =
173
+ isError && begun?.denied !== true
174
+ ? firstErrorLine(field(["error", "message"]) ?? blockText, { secrets })
175
+ : undefined;
176
+ return JSON.stringify({
177
+ type: "tool_execution_end",
178
+ toolCallId: id,
179
+ toolName: name ?? begun?.name ?? "tool",
180
+ isError,
181
+ durationMs: begun === undefined ? 0 : Math.max(0, now() - begun.at),
182
+ ...(error === undefined ? {} : { error }),
183
+ });
184
+ }
185
+
186
+ /**
187
+ * The model a step passes to radian as `<provider>/<model>`, from `--provider`
188
+ * and `--model` in its args. A model that already names a provider (it has a
189
+ * `/`) is not prefixed again; a step without `--model` has none.
190
+ */
191
+ export function radianModel(args: unknown): string | undefined {
192
+ const model = flagValue(args, "--model");
193
+ if (model === undefined) return undefined;
194
+ const provider = flagValue(args, "--provider");
195
+ return provider === undefined || model.includes("/") ? model : `${provider}/${model}`;
196
+ }
197
+
198
+ /** Settings for one radian harness plugin. A test injects a clock. */
199
+ export interface RadianHarnessSettings {
200
+ /** The command name or path; defaults to `radian`. */
201
+ readonly command?: string | undefined;
202
+ /** The default wall-time limit in seconds. */
203
+ readonly wallTimeSecs?: number | undefined;
204
+ /** The default stall limit in seconds. */
205
+ readonly stallSecs?: number | undefined;
206
+ readonly clock?: Clock | undefined;
207
+ /** Milliseconds now, for tool call start times and durations; a test injects it. */
208
+ readonly now?: (() => number) | undefined;
209
+ }
210
+
211
+ interface ResolvedSettings {
212
+ readonly command: string;
213
+ readonly wallTimeSecs: number;
214
+ readonly stallSecs: number;
215
+ readonly clock: Clock;
216
+ readonly now: () => number;
217
+ }
218
+
219
+ /** The models a chat may pick with this agent, and the one used when none is set. */
220
+ export const RADIAN_MODELS = { list: [], default: null } as const;
221
+
222
+ /** radian cannot honour an effort a chat picks, so it declares none. */
223
+ export const RADIAN_EFFORTS = { list: [], default: null } as const;
224
+
225
+ /** The settings a config.json section may set for this plugin. */
226
+ const PLUGIN_SETTINGS = {
227
+ type: "object" as const,
228
+ properties: {
229
+ command: {
230
+ type: "string" as const,
231
+ description: "The radian executable to run.",
232
+ },
233
+ wallTimeSecs: {
234
+ type: "number" as const,
235
+ description: "The longest one agent run may take.",
236
+ },
237
+ stallSecs: {
238
+ type: "number" as const,
239
+ description: "How long an agent may be silent between tool calls.",
240
+ },
241
+ concurrency: CONCURRENCY_SETTING,
242
+ },
243
+ additionalProperties: false as const,
244
+ };
245
+
246
+ interface ParsedResult {
247
+ readonly sessionId: string | null;
248
+ readonly finalMessage: string | null;
249
+ /** radian's own counts and cost, as it prints them. */
250
+ readonly counts: RawCounts;
251
+ readonly cost: RawCost | null;
252
+ /** The `model_error` of a run that ended on a model failure, as data. */
253
+ readonly modelError: Readonly<Record<string, unknown>> | null;
254
+ }
255
+
256
+ /** Reads the closing `Result` record of radian's JSONL, or undefined. */
257
+ function parseResult(line: string): ParsedResult | undefined {
258
+ let value: unknown;
259
+ try {
260
+ value = JSON.parse(line);
261
+ } catch {
262
+ return undefined;
263
+ }
264
+ if (!isRecord(value) || value.type !== "Result") return undefined;
265
+
266
+ const counts = isRecord(value.usage) ? (value.usage as RawCounts) : {};
267
+ const cost: RawCost | null =
268
+ isRecord(value.cost) &&
269
+ typeof value.cost.micros === "number" &&
270
+ Number.isFinite(value.cost.micros)
271
+ ? {
272
+ micros: value.cost.micros,
273
+ incomplete: value.cost.incomplete === true,
274
+ estimated: value.cost.estimated === true,
275
+ }
276
+ : null;
277
+ return {
278
+ sessionId: typeof value.session_id === "string" ? value.session_id : null,
279
+ finalMessage: typeof value.text === "string" ? value.text : null,
280
+ counts,
281
+ cost,
282
+ modelError: isRecord(value.model_error) ? value.model_error : null,
283
+ };
284
+ }
285
+
286
+ /** `{ modelError }` when radian reported one, so a caller can classify it. */
287
+ function modelErrorData(
288
+ result: ParsedResult | undefined,
289
+ ): Record<string, unknown> {
290
+ return result?.modelError == null ? {} : { modelError: result.modelError };
291
+ }
292
+
293
+ function failureData(
294
+ who: UsageSource,
295
+ outcome: AgentRunOutcome,
296
+ result: ParsedResult | undefined,
297
+ log: string,
298
+ durationMs: number,
299
+ extra: Readonly<Record<string, unknown>>,
300
+ ): Record<string, unknown> {
301
+ return {
302
+ ...agentData(who, outcome, result, log, durationMs),
303
+ ...modelErrorData(result),
304
+ ...extra,
305
+ };
306
+ }
307
+
308
+ function agentData(
309
+ who: UsageSource,
310
+ outcome: AgentRunOutcome,
311
+ result: ParsedResult | undefined,
312
+ log: string,
313
+ durationMs: number,
314
+ ): AgentResultData {
315
+ return {
316
+ exitCode: outcome.exitCode,
317
+ signal: outcome.signal,
318
+ sessionId: result?.sessionId ?? null,
319
+ finalMessage: result?.finalMessage ?? null,
320
+ usage: standardUsage(who, result?.counts, result?.cost),
321
+ log,
322
+ durationMs,
323
+ stderr: outcome.stderrTail,
324
+ };
325
+ }
326
+
327
+ /** Whether the profile has a rule radian's calls must be judged by. */
328
+ function hasProfileRules(profile: AccessProfile): boolean {
329
+ return (
330
+ profile.readOnly === true ||
331
+ [profile.denyPaths, profile.denyCommands, profile.askCommands, profile.askPaths].some((rules) => (rules?.length ?? 0) > 0)
332
+ );
333
+ }
334
+
335
+ const HOOK_PATH = fileURLToPath(new URL("./hook.ts", import.meta.url));
336
+
337
+ function quoted(text: string): string {
338
+ return `'${text.replace(/'/g, `'\\''`)}'`;
339
+ }
340
+
341
+ /**
342
+ * Writes the profile and a radian config that runs the hook before every tool
343
+ * call; returns the config's path. The user's own radian config (`RADIAN_CONFIG`
344
+ * or the default file) is kept, because `--config` replaces it.
345
+ */
346
+ async function writeHookConfig(base: string, profile: AccessProfile): Promise<string> {
347
+ const profileFile = `${base}.profile.json`;
348
+ const configFile = `${base}.config.toml`;
349
+ await mkdir(dirname(configFile), { recursive: true });
350
+ await writeFile(profileFile, JSON.stringify(profile));
351
+ const own = process.env.RADIAN_CONFIG ?? `${process.env.HOME ?? ""}/.radian/config/config.toml`;
352
+ let existing = "";
353
+ try {
354
+ existing = await readFile(own, "utf8");
355
+ } catch {
356
+ existing = "";
357
+ }
358
+ const command = `${quoted(process.execPath)} ${quoted(HOOK_PATH)} ${quoted(profileFile)}`;
359
+ const hook = [
360
+ "",
361
+ "[[hooks.PreToolUse]]",
362
+ 'matcher = "*"',
363
+ "[[hooks.PreToolUse.hooks]]",
364
+ 'type = "command"',
365
+ `command = ${JSON.stringify(command)}`,
366
+ "timeout = 30",
367
+ "",
368
+ ].join("\n");
369
+ await writeFile(configFile, existing + hook);
370
+ return configFile;
371
+ }
372
+
373
+ /** Builds the argv radian receives; the prompt itself may travel on stdin. */
374
+ function radianArgs(
375
+ cwd: string,
376
+ args: readonly string[],
377
+ prompt: string,
378
+ resumeSession: string | undefined,
379
+ mcpConfig?: string | undefined,
380
+ config?: string | undefined,
381
+ ): { readonly args: string[]; readonly stdin: string | undefined } {
382
+ const argv = ["exec", "--workspace", cwd, "--output", "jsonl"];
383
+ if (resumeSession !== undefined) argv.push("--resume", resumeSession);
384
+ if (mcpConfig !== undefined) argv.push("--mcp-config", mcpConfig);
385
+ if (config !== undefined) argv.push("--config", config);
386
+ argv.push(...args);
387
+
388
+ const stdin =
389
+ Buffer.byteLength(prompt, "utf8") > PROMPT_ARG_SAFE_BYTES ? prompt : undefined;
390
+ argv.push("-p", stdin === undefined ? prompt : "-");
391
+ return { args: argv, stdin };
392
+ }
393
+
394
+ function resultFor(
395
+ who: UsageSource,
396
+ outcome: AgentRunOutcome,
397
+ result: ParsedResult | undefined,
398
+ log: string,
399
+ durationMs: number,
400
+ wallTimeSecs: number,
401
+ stallSecs: number,
402
+ command: string,
403
+ ): PluginStepResult {
404
+ if (outcome.cancelled) {
405
+ return {
406
+ result: "interrupted",
407
+ data: failureData(who, outcome, result, log, durationMs, {
408
+ reason: "cancelled",
409
+ message: "the harness run was cancelled",
410
+ }),
411
+ };
412
+ }
413
+ if (outcome.missing) {
414
+ return {
415
+ result: "failed",
416
+ data: failureData(who, outcome, result, log, durationMs, {
417
+ reason: "missing",
418
+ message: `${command} was not found on PATH`,
419
+ }),
420
+ };
421
+ }
422
+ if (outcome.spawnError !== undefined) {
423
+ return {
424
+ result: "failed",
425
+ data: failureData(who, outcome, result, log, durationMs, {
426
+ reason: "spawn",
427
+ message: outcome.spawnError,
428
+ }),
429
+ };
430
+ }
431
+ if (outcome.wall) {
432
+ return {
433
+ result: "failed",
434
+ data: failureData(who, outcome, result, log, durationMs, {
435
+ reason: "wall",
436
+ message: `the harness ran longer than ${wallTimeSecs}s`,
437
+ }),
438
+ };
439
+ }
440
+ if (outcome.stall) {
441
+ return {
442
+ result: "failed",
443
+ data: failureData(who, outcome, result, log, durationMs, {
444
+ reason: "stall",
445
+ message: `the harness printed no new line for ${stallSecs}s`,
446
+ }),
447
+ };
448
+ }
449
+ if (outcome.lineTooLong) {
450
+ return {
451
+ result: "failed",
452
+ data: failureData(who, outcome, result, log, durationMs, {
453
+ reason: "line_too_long",
454
+ message: `the harness printed a line longer than ${MAX_LINE_CHARS} characters`,
455
+ }),
456
+ };
457
+ }
458
+ if (outcome.exitCode !== 0) {
459
+ const message =
460
+ outcome.signal !== null
461
+ ? `the harness was killed by ${outcome.signal}`
462
+ : `the harness exited ${String(outcome.exitCode)}`;
463
+ return {
464
+ result: "failed",
465
+ data: failureData(who, outcome, result, log, durationMs, {
466
+ reason: "exit",
467
+ message,
468
+ }),
469
+ };
470
+ }
471
+ if (result === undefined) {
472
+ return {
473
+ result: "failed",
474
+ data: failureData(who, outcome, result, log, durationMs, {
475
+ reason: "no_result",
476
+ message: "the harness exited 0 without a Result record",
477
+ }),
478
+ };
479
+ }
480
+ return {
481
+ result: "done",
482
+ data: {
483
+ ...agentData(who, outcome, result, log, durationMs),
484
+ ...modelErrorData(result),
485
+ } as unknown as Record<string, unknown>,
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Creates the radian harness plugin. The prompt flow uses the settings for
491
+ * its limits; a direct `agent` step may override them.
492
+ */
493
+ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {}) {
494
+ const defaults: ResolvedSettings = {
495
+ command: settings.command ?? "radian",
496
+ wallTimeSecs: settings.wallTimeSecs ?? DEFAULT_WALL_TIME_SECS,
497
+ stallSecs: settings.stallSecs ?? DEFAULT_STALL_SECS,
498
+ clock: settings.clock ?? systemClock,
499
+ now: settings.now ?? Date.now,
500
+ };
501
+
502
+ const promptFlow = defineFlow({
503
+ name: "radian:prompt",
504
+ entry: "agent",
505
+ steps: [
506
+ {
507
+ id: "agent",
508
+ kind: "plugin",
509
+ params: { use: "radian/agent", params: {} },
510
+ replay: "unsafe",
511
+ next: { done: "done", failed: "failed", interrupted: "cancelled" },
512
+ },
513
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
514
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
515
+ {
516
+ id: "cancelled",
517
+ kind: "end",
518
+ params: { status: "cancelled" },
519
+ replay: "safe",
520
+ },
521
+ ],
522
+ });
523
+
524
+ return definePlugin({
525
+ name: "radian",
526
+ kind: "harness",
527
+ version: pkg.version,
528
+ models: RADIAN_MODELS,
529
+ efforts: RADIAN_EFFORTS,
530
+ settings: PLUGIN_SETTINGS,
531
+ steps: [
532
+ {
533
+ name: "agent",
534
+ // A question's answer comes back as `resumeSession` and `askAnswer`.
535
+ resumable: true,
536
+ // No hook sees radian's tool calls: `ctx.ask` refuses a question that
537
+ // offers a one-time permission before it asks anyone.
538
+ grants: false,
539
+ results: ["done", "failed", "interrupted"],
540
+ // The model is what the step passes to radian: `<provider>/<model>`.
541
+ limit: modelLimit("radian", (params) =>
542
+ isRecord(params) ? radianModel(params.args) : undefined,
543
+ ),
544
+ async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
545
+ const at = "radian/agent";
546
+ const input = paramsObject(params, at);
547
+ const flow = isRecord(ctx.params) ? ctx.params : {};
548
+
549
+ const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
550
+ const note = eventNote(ctx.trigger);
551
+ const answerNote = askNote(input.askAnswer ?? flow.askAnswer);
552
+ const promptWithNote = [prompt, note, answerNote]
553
+ .filter((part): part is string => part !== undefined)
554
+ .join("\n\n");
555
+ const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
556
+ const args = stringListParam(
557
+ input.args === undefined ? flow.args : input.args,
558
+ `${at}: params.args`,
559
+ );
560
+ const resumeSession = optionalText(
561
+ input.resumeSession ?? flow.resumeSession,
562
+ `${at}: params.resumeSession`,
563
+ );
564
+ const wallTimeSecs = secs(
565
+ input.wallTimeSecs ?? ctx.settings.wallTimeSecs ?? defaults.wallTimeSecs,
566
+ `${at}: params.wallTimeSecs`,
567
+ );
568
+ const stallSecs = secs(
569
+ input.stallSecs ?? ctx.settings.stallSecs ?? defaults.stallSecs,
570
+ `${at}: params.stallSecs`,
571
+ );
572
+ const commandName =
573
+ ctx.settings.command === undefined
574
+ ? defaults.command
575
+ : text(ctx.settings.command, `${at}: settings.command`);
576
+
577
+ const readAccess = readProfile(ctx.access ?? {});
578
+ const logSecrets = await secretValuesOf(ctx.secrets);
579
+ const logProfile: AccessProfile = readAccess.ok ? readAccess.profile : {};
580
+
581
+ const who: UsageSource = {
582
+ harness: "radian",
583
+ model: radianModel(args) ?? null,
584
+ };
585
+
586
+ // radian has no hook that sees a tool call, so it cannot let one
587
+ // call through and no other: a one-time permission is refused.
588
+ if (isRecord(ctx.access) && Array.isArray(ctx.access.grants) && ctx.access.grants.length > 0) {
589
+ const message = `${at}: radian cannot enforce a one-time permission (no hook sees its tool calls); ask with pi, or without a grant`;
590
+ const log = await ctx.logger.write(message);
591
+ return {
592
+ result: "failed",
593
+ data: {
594
+ reason: "grant_unsupported",
595
+ message,
596
+ exitCode: null,
597
+ signal: null,
598
+ sessionId: null,
599
+ finalMessage: null,
600
+ usage: standardUsage(who, undefined, null),
601
+ log,
602
+ durationMs: 0,
603
+ stderr: [message],
604
+ },
605
+ };
606
+ }
607
+
608
+ const cwdProblem = await directoryError(cwd);
609
+ if (cwdProblem !== undefined) {
610
+ const log = await ctx.logger.write(cwdProblem);
611
+ return {
612
+ result: "failed",
613
+ data: {
614
+ reason: "cwd",
615
+ message: cwdProblem,
616
+ exitCode: null,
617
+ signal: null,
618
+ sessionId: null,
619
+ finalMessage: null,
620
+ usage: standardUsage(who, undefined, null),
621
+ log,
622
+ durationMs: 0,
623
+ stderr: [cwdProblem],
624
+ },
625
+ };
626
+ }
627
+
628
+ // Operad's tools: radian starts the server named in this file.
629
+ const operadTools = operadToolsOf(input.operadTools ?? flow.operadTools);
630
+ // A bot's servers: each is started behind its guard, which holds the secrets.
631
+ const mounted = mountedServersOf(input.mcpServers ?? flow.mcpServers);
632
+ let mcpConfig: string | undefined;
633
+ if (operadTools !== undefined || mounted !== undefined) {
634
+ const servers: Record<string, unknown> = {};
635
+ if (operadTools !== undefined) {
636
+ const server = serverCommand(operadTools);
637
+ servers[OPERAD_SERVER] = {
638
+ command: server.command,
639
+ args: server.args,
640
+ env: { OPERAD_HOME: operadTools.home },
641
+ };
642
+ }
643
+ for (const [name, server] of Object.entries(mounted ?? {})) {
644
+ servers[name] = { command: server.command, args: server.args };
645
+ }
646
+ mcpConfig = `${ctx.logger.path}.mcp.json`;
647
+ await mkdir(dirname(mcpConfig), { recursive: true });
648
+ await writeFile(mcpConfig, JSON.stringify({ mcpServers: servers }));
649
+ }
650
+ // radian runs its own tools and has no way to ask, so the profile's
651
+ // rules are given to it as a hook it runs before each call.
652
+ const hookConfig = hasProfileRules(logProfile)
653
+ ? await writeHookConfig(`${ctx.logger.path}.hook`, logProfile)
654
+ : undefined;
655
+ const command = radianArgs(cwd, args, promptWithNote, resumeSession, mcpConfig, hookConfig);
656
+ const started = Date.now();
657
+ const jsonl = new JsonlLog(ctx.logger, defaults.clock);
658
+ let result: ParsedResult | undefined;
659
+ const openTools = new Map<string, { at: number; name: string }>();
660
+
661
+ const outcome = await runAgent({
662
+ command: commandName,
663
+ args: command.args,
664
+ cwd,
665
+ stdin: command.stdin,
666
+ wallMs: wallTimeSecs * 1000,
667
+ stallMs: stallSecs * 1000,
668
+ signal: ctx.signal,
669
+ clock: defaults.clock,
670
+ toolEvent: radianToolEvent,
671
+ onLine(line) {
672
+ const logged = radianLogLine(line, defaults.now, openTools, cwd, logProfile, logSecrets);
673
+ const writing = jsonl.push(logged);
674
+ deliverLine(ctx.receiver, logged, logSecrets);
675
+ const parsed = parseResult(line);
676
+ if (parsed !== undefined) result = parsed;
677
+ return writing;
678
+ },
679
+ });
680
+ await jsonl.end();
681
+
682
+ // A resumed run continues the session it was given. Another id means
683
+ // radian started afresh and the earlier conversation is lost.
684
+ if (
685
+ resumeSession !== undefined &&
686
+ result !== undefined &&
687
+ !outcome.cancelled &&
688
+ outcome.exitCode === 0 &&
689
+ result.sessionId !== resumeSession
690
+ ) {
691
+ return {
692
+ result: "failed",
693
+ data: failureData(who, outcome, result, ctx.logger.path, Date.now() - started, {
694
+ reason: "session_missing",
695
+ message: `radian did not continue the session ${resumeSession}; it answered with ${result.sessionId ?? "no session"}`,
696
+ }),
697
+ };
698
+ }
699
+
700
+ return resultFor(
701
+ who,
702
+ outcome,
703
+ result,
704
+ ctx.logger.path,
705
+ Date.now() - started,
706
+ wallTimeSecs,
707
+ stallSecs,
708
+ commandName,
709
+ );
710
+ },
711
+ },
712
+ ],
713
+ flows: [promptFlow],
714
+ async check(ctx) {
715
+ const command =
716
+ ctx.settings.command === undefined
717
+ ? defaults.command
718
+ : text(ctx.settings.command, "radian: settings.command");
719
+ const found = await findCommand(command);
720
+ if (found === undefined) {
721
+ throw new Error(`${command} was not found on PATH`);
722
+ }
723
+ return `${command} is available`;
724
+ },
725
+ });
726
+ }
727
+
728
+ export default createRadianHarnessPlugin();
package/src/refusal.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { match, MCP_TOOL, type AccessProfile } from "@operad-io/access-match";
2
+ import { isRecord } from "@operad-io/engine";
3
+
4
+ /** One radian tool call as the access-match call it stands for. */
5
+ export function mapRadianCall(
6
+ toolName: string,
7
+ args: Record<string, unknown>,
8
+ ): { readonly mapped: string; readonly input: Record<string, unknown> } {
9
+ const lower = toolName.toLowerCase();
10
+ let mapped = lower;
11
+ let input: Record<string, unknown> = args;
12
+ if (lower === "shell") mapped = "bash";
13
+ else if (lower === "patch") mapped = "edit";
14
+ else if (lower === "glob") {
15
+ mapped = "find";
16
+ const where = typeof args.path === "string" && args.path.length > 0 ? args.path : args.pattern;
17
+ input = typeof where === "string" ? { ...args, path: where } : args;
18
+ } else if (lower === "list") mapped = "ls";
19
+ else if (!["bash", "read", "write", "edit", "grep", "find", "ls"].includes(lower) && typeof args.path === "string") {
20
+ mapped = "read";
21
+ }
22
+ return { mapped, input };
23
+ }
24
+
25
+ /** What to tell the agent after a refusal in a read-only directory. */
26
+ export const READ_ONLY_ADVICE = "Do not retry it; tell the person what you want to change, and they can open a worktree for it.";
27
+
28
+ /** The tools that only read, in a read-only directory (radian's names). */
29
+ const READ_ONLY_TOOLS = new Set(["read", "glob", "grep", "list", "memory_search", "ask_user", "skill", "job"]);
30
+
31
+ /** The server id of operad's own tools: its tools are `operad__<tool>`. */
32
+ const OPERAD_TOOL_PREFIX = "operad__";
33
+
34
+ /** Every path a `patch` call names: its own `path` and the `path` of each edit. */
35
+ function patchPaths(args: Record<string, unknown>): readonly string[] {
36
+ const paths: string[] = [];
37
+ const own = args.path ?? args.file_path;
38
+ if (typeof own === "string" && own.length > 0) paths.push(own);
39
+ for (const key of ["edits", "files", "patches"]) {
40
+ const list = args[key];
41
+ if (!Array.isArray(list)) continue;
42
+ for (const entry of list) {
43
+ if (!isRecord(entry)) continue;
44
+ const path = entry.path ?? entry.file_path;
45
+ if (typeof path === "string" && path.length > 0) paths.push(path);
46
+ }
47
+ }
48
+ return paths;
49
+ }
50
+
51
+ function describe(profile: AccessProfile, verdict: { readonly rule?: string | undefined; readonly ask?: true | undefined }): string {
52
+ if (verdict.rule === "readOnly" || (verdict.ask === true && profile.readOnly === true)) {
53
+ return `is refused: this chat is read-only here. ${READ_ONLY_ADVICE}`;
54
+ }
55
+ return verdict.rule === undefined
56
+ ? "is refused by the access profile"
57
+ : `is refused by the access profile (rule: ${verdict.rule.replace(/\s+/g, " ").slice(0, 120)})`;
58
+ }
59
+
60
+ /**
61
+ * Why the access profile refuses a radian tool call, or undefined when it lets
62
+ * it run. radian has no way to ask, so a call that would ask is refused too. In
63
+ * a read-only directory only tools known to read run, and operad's own tools;
64
+ * any other tool, a user's MCP server included, is refused. A `patch` is judged
65
+ * on every path it names, and refused when it names none.
66
+ */
67
+ export function radianRefusal(profile: AccessProfile, toolName: string, args: unknown, cwd: string): string | undefined {
68
+ const lower = toolName.toLowerCase();
69
+ const record = isRecord(args) ? args : {};
70
+ if (profile.readOnly === true && !lower.startsWith(OPERAD_TOOL_PREFIX) && lower !== "shell" && !READ_ONLY_TOOLS.has(lower)) {
71
+ return lower === "write" || lower === "patch"
72
+ ? `is refused: this chat is read-only here. ${READ_ONLY_ADVICE}`
73
+ : `is refused: this chat is read-only here and only reading tools and operad's tools run. ${READ_ONLY_ADVICE}`;
74
+ }
75
+ if (lower === "patch") {
76
+ const paths = patchPaths(record);
77
+ if (paths.length === 0) return "is refused: it names no file, so the access profile cannot judge it";
78
+ for (const path of paths) {
79
+ const verdict = match(profile, { tool: "edit", input: { path }, cwd });
80
+ if (!verdict.allow) return describe(profile, verdict);
81
+ }
82
+ return undefined;
83
+ }
84
+ if (lower.startsWith(OPERAD_TOOL_PREFIX)) return undefined;
85
+ // A tool of another MCP server is `<server>__<tool>`; it is judged by server and tool.
86
+ const split = toolName.indexOf("__");
87
+ if (profile.allowMcp !== undefined && split > 0 && split + 2 < toolName.length) {
88
+ const verdict = match(profile, { tool: MCP_TOOL, input: { server: toolName.slice(0, split), tool: toolName.slice(split + 2) }, cwd });
89
+ return verdict.allow ? undefined : describe(profile, verdict);
90
+ }
91
+ const { mapped, input } = mapRadianCall(toolName, record);
92
+ const verdict = match(profile, { tool: mapped, input, cwd });
93
+ return verdict.allow ? undefined : describe(profile, verdict);
94
+ }