@operad-io/harness-radian 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.
Files changed (3) hide show
  1. package/README.md +4 -0
  2. package/package.json +4 -4
  3. package/src/index.ts +148 -191
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, reports whether radian's credentials file (`$RADIAN_HOME/credentials/auth.json`, or `~/.radian/credentials/auth.json`) holds a credential. Only the presence of a credential is read; no key or token is read into operad, kept or returned. A missing file is `false`; a file that cannot be read or parsed is absent.
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,14 +1,14 @@
1
1
  {
2
2
  "name": "@operad-io/harness-radian",
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
- "@operad-io/access-match": "0.1.1",
10
- "@operad-io/engine": "0.1.1",
11
- "@operad-io/harness-process": "0.1.1"
9
+ "@operad-io/access-match": "0.3.0",
10
+ "@operad-io/engine": "0.3.0",
11
+ "@operad-io/harness-process": "0.3.0"
12
12
  },
13
13
  "description": "operad: the radian harness",
14
14
  "repository": {
package/src/index.ts CHANGED
@@ -7,17 +7,18 @@
7
7
 
8
8
  import pkg from "../package.json" with { type: "json" };
9
9
  import { mkdir, readFile, writeFile } from "node:fs/promises";
10
- import { dirname } from "node:path";
10
+ import { dirname, join } from "node:path";
11
+ import { homedir } from "node:os";
11
12
  import { fileURLToPath } from "node:url";
12
13
  import { mapRadianCall } from "./refusal.ts";
13
14
  export { radianRefusal } from "./refusal.ts";
14
- import { firstErrorLine, match, readProfile, secretValuesOf, summarizeCall, type AccessProfile } from "@operad-io/access-match";
15
+ import { firstErrorLine, match, readProfile, secretValuesOf, summarizeCall, withDefaultAccess, type AccessProfile } from "@operad-io/access-match";
15
16
  import {
17
+ isMissingFile,
16
18
  isRecord,
17
19
  paramsObject,
18
20
  defineFlow,
19
21
  definePlugin,
20
- type AgentResultData,
21
22
  type PluginStepResult,
22
23
  type StepContext,
23
24
  } from "@operad-io/engine";
@@ -26,33 +27,37 @@ import {
26
27
  askNote,
27
28
  eventNote,
28
29
  directoryError,
30
+ failure,
29
31
  findCommand,
30
32
  flagValue,
31
33
  JsonlLog,
32
34
  deliverLine,
33
- MAX_LINE_CHARS,
34
35
  OPERAD_SERVER,
35
36
  operadToolsOf,
36
37
  mountedServersOf,
37
38
  optionalText,
39
+ promptWithSkills,
38
40
  secs,
39
41
  serverCommand,
40
- standardUsage,
42
+ refuseResult,
43
+ StepTimings,
41
44
  stringListParam,
42
45
  text,
46
+ withTimings,
43
47
  type RawCost,
44
48
  type RawCounts,
45
49
  type UsageSource,
50
+ type AgentWorkerResult,
46
51
  modelLimit,
52
+ personStarted,
53
+ resultFor,
47
54
  runAgent,
55
+ skippedLineRecord,
48
56
  systemClock,
49
- type AgentRunOutcome,
50
57
  type Clock,
51
58
  type ToolEvent,
52
59
  } from "@operad-io/harness-process";
53
60
 
54
- export { EVENT_NOTE_TEMPLATE, eventNote } from "@operad-io/harness-process";
55
-
56
61
  /** How long an agent may run before the step stops it. */
57
62
  export const DEFAULT_WALL_TIME_SECS = 300;
58
63
 
@@ -199,6 +204,8 @@ export function radianModel(args: unknown): string | undefined {
199
204
  export interface RadianHarnessSettings {
200
205
  /** The command name or path; defaults to `radian`. */
201
206
  readonly command?: string | undefined;
207
+ /** The credentials file; defaults to `$RADIAN_HOME/credentials/auth.json` or `~/.radian/credentials/auth.json`. */
208
+ readonly authPath?: string | undefined;
202
209
  /** The default wall-time limit in seconds. */
203
210
  readonly wallTimeSecs?: number | undefined;
204
211
  /** The default stall limit in seconds. */
@@ -208,6 +215,42 @@ export interface RadianHarnessSettings {
208
215
  readonly now?: (() => number) | undefined;
209
216
  }
210
217
 
218
+ /** The credentials file radian's own login writes. */
219
+ export function defaultRadianAuthPath(): string {
220
+ const home = process.env.RADIAN_HOME;
221
+ return home !== undefined && home.length > 0
222
+ ? join(home, "credentials", "auth.json")
223
+ : join(homedir(), ".radian", "credentials", "auth.json");
224
+ }
225
+
226
+ /** A credential is any object stored under a provider; its fields are never read. */
227
+ function hasCredential(auth: unknown): boolean {
228
+ return isRecord(auth) && Object.values(auth).some((value) => isRecord(value));
229
+ }
230
+
231
+ /**
232
+ * Whether radian's auth file holds a credential. The file is parsed but no
233
+ * credential field is read, kept or returned; a missing file means no
234
+ * credential (false), and an unreadable or malformed one means it cannot tell
235
+ * (undefined).
236
+ */
237
+ async function radianSignedIn(authPath: string): Promise<boolean | undefined> {
238
+ let text: string;
239
+ try {
240
+ text = await readFile(authPath, "utf8");
241
+ } catch (error) {
242
+ return isMissingFile(error) ? false : undefined;
243
+ }
244
+ let value: unknown;
245
+ try {
246
+ value = JSON.parse(text);
247
+ } catch {
248
+ return undefined;
249
+ }
250
+ if (!isRecord(value)) return undefined;
251
+ return hasCredential(value);
252
+ }
253
+
211
254
  interface ResolvedSettings {
212
255
  readonly command: string;
213
256
  readonly wallTimeSecs: number;
@@ -228,14 +271,17 @@ const PLUGIN_SETTINGS = {
228
271
  properties: {
229
272
  command: {
230
273
  type: "string" as const,
274
+ title: "Radian command",
231
275
  description: "The radian executable to run.",
232
276
  },
233
277
  wallTimeSecs: {
234
278
  type: "number" as const,
279
+ title: "Run time limit",
235
280
  description: "The longest one agent run may take.",
236
281
  },
237
282
  stallSecs: {
238
283
  type: "number" as const,
284
+ title: "Stall limit",
239
285
  description: "How long an agent may be silent between tool calls.",
240
286
  },
241
287
  concurrency: CONCURRENCY_SETTING,
@@ -254,13 +300,7 @@ interface ParsedResult {
254
300
  }
255
301
 
256
302
  /** 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
- }
303
+ function resultValue(value: unknown): ParsedResult | undefined {
264
304
  if (!isRecord(value) || value.type !== "Result") return undefined;
265
305
 
266
306
  const counts = isRecord(value.usage) ? (value.usage as RawCounts) : {};
@@ -290,38 +330,36 @@ function modelErrorData(
290
330
  return result?.modelError == null ? {} : { modelError: result.modelError };
291
331
  }
292
332
 
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> {
333
+ /**
334
+ * Radian's Result record as the worker result the shared mapping reads. A
335
+ * Result names no worker result of its own in this step: a non-zero exit is
336
+ * the failure, so a present Result maps to `done`. Only its model_error is
337
+ * kept by the step, because radian prints the whole error object and dev reads
338
+ * its kind from there.
339
+ */
340
+ function workerResultOf(result: ParsedResult | undefined): AgentWorkerResult | undefined {
341
+ if (result === undefined) return undefined;
342
+ const cost = result.cost;
301
343
  return {
302
- ...agentData(who, outcome, result, log, durationMs),
303
- ...modelErrorData(result),
304
- ...extra,
344
+ type: "result",
345
+ result: "done",
346
+ sessionId: result.sessionId,
347
+ usage: result.counts,
348
+ cost:
349
+ cost === null
350
+ ? null
351
+ : {
352
+ micros: cost.micros,
353
+ ...(cost.incomplete === true ? { incomplete: true as const } : {}),
354
+ ...(cost.estimated === true ? { quality: "estimated" as const } : {}),
355
+ },
356
+ finalMessage: result.finalMessage,
305
357
  };
306
358
  }
307
359
 
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
- };
360
+ /** Adds radian's own model_error, whole, to a step result when it reported one. */
361
+ function withModelError(result: ParsedResult | undefined, step: PluginStepResult): PluginStepResult {
362
+ return { ...step, data: { ...(step.data ?? {}), ...modelErrorData(result) } };
325
363
  }
326
364
 
327
365
  /** Whether the profile has a rule radian's calls must be judged by. */
@@ -391,101 +429,6 @@ function radianArgs(
391
429
  return { args: argv, stdin };
392
430
  }
393
431
 
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
432
  /**
490
433
  * Creates the radian harness plugin. The prompt flow uses the settings for
491
434
  * its limits; a direct `agent` step may override them.
@@ -498,6 +441,7 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
498
441
  clock: settings.clock ?? systemClock,
499
442
  now: settings.now ?? Date.now,
500
443
  };
444
+ const authPath = settings.authPath ?? defaultRadianAuthPath();
501
445
 
502
446
  const promptFlow = defineFlow({
503
447
  name: "radian:prompt",
@@ -527,6 +471,7 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
527
471
  version: pkg.version,
528
472
  models: RADIAN_MODELS,
529
473
  efforts: RADIAN_EFFORTS,
474
+ signedIn: (_settings: Readonly<Record<string, unknown>>) => radianSignedIn(authPath),
530
475
  settings: PLUGIN_SETTINGS,
531
476
  steps: [
532
477
  {
@@ -543,13 +488,18 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
543
488
  ),
544
489
  async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
545
490
  const at = "radian/agent";
491
+ const timings = new StepTimings(defaults.now);
546
492
  const input = paramsObject(params, at);
547
493
  const flow = isRecord(ctx.params) ? ctx.params : {};
548
494
 
549
495
  const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
496
+ const skills = stringListParam(
497
+ input.skills === undefined ? flow.skills : input.skills,
498
+ `${at}: params.skills`,
499
+ );
550
500
  const note = eventNote(ctx.trigger);
551
501
  const answerNote = askNote(input.askAnswer ?? flow.askAnswer);
552
- const promptWithNote = [prompt, note, answerNote]
502
+ const promptWithNote = [promptWithSkills(prompt, skills), note, answerNote]
553
503
  .filter((part): part is string => part !== undefined)
554
504
  .join("\n\n");
555
505
  const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
@@ -574,7 +524,10 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
574
524
  ? defaults.command
575
525
  : text(ctx.settings.command, `${at}: settings.command`);
576
526
 
577
- const readAccess = readProfile(ctx.access ?? {});
527
+ // A generated step that names no profile still starts from the default.
528
+ const startAccess = withDefaultAccess(ctx.access as AccessProfile | undefined);
529
+ const access = personStarted(ctx.trigger) ? startAccess : { ...startAccess, background: true };
530
+ const readAccess = readProfile(access);
578
531
  const logSecrets = await secretValuesOf(ctx.secrets);
579
532
  const logProfile: AccessProfile = readAccess.ok ? readAccess.profile : {};
580
533
 
@@ -585,44 +538,25 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
585
538
 
586
539
  // radian has no hook that sees a tool call, so it cannot let one
587
540
  // 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
- };
541
+ if (isRecord(access) && Array.isArray(access.grants) && access.grants.length > 0) {
542
+ return await refuseResult({
543
+ log: (message) => ctx.logger.write(message),
544
+ timings,
545
+ who,
546
+ reason: "grant_unsupported",
547
+ message: `${at}: radian cannot enforce a one-time permission (no hook sees its tool calls); ask with pi, or without a grant`,
548
+ });
606
549
  }
607
550
 
608
551
  const cwdProblem = await directoryError(cwd);
609
552
  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
- };
553
+ return await refuseResult({
554
+ log: (message) => ctx.logger.write(message),
555
+ timings,
556
+ who,
557
+ reason: "cwd",
558
+ message: cwdProblem,
559
+ });
626
560
  }
627
561
 
628
562
  // Operad's tools: radian starts the server named in this file.
@@ -653,10 +587,21 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
653
587
  ? await writeHookConfig(`${ctx.logger.path}.hook`, logProfile)
654
588
  : undefined;
655
589
  const command = radianArgs(cwd, args, promptWithNote, resumeSession, mcpConfig, hookConfig);
656
- const started = Date.now();
657
- const jsonl = new JsonlLog(ctx.logger, defaults.clock);
590
+ const jsonl = new JsonlLog(ctx.logger, defaults.clock, defaults.now);
658
591
  let result: ParsedResult | undefined;
659
592
  const openTools = new Map<string, { at: number; name: string }>();
593
+ // radian has no session handshake: the prompt is handed to the
594
+ // process at its start, so its session is ready then, not at its
595
+ // first output (which may wait for the model).
596
+ const writeSession = (): void => {
597
+ const session = jsonl.stamp(JSON.stringify({
598
+ type: "session",
599
+ ...(resumeSession === undefined ? {} : { sessionId: resumeSession }),
600
+ }));
601
+ timings.record(session.value, session.at);
602
+ void jsonl.pushStamped(session);
603
+ deliverLine(ctx.receiver, session.text, logSecrets);
604
+ };
660
605
 
661
606
  const outcome = await runAgent({
662
607
  command: commandName,
@@ -668,16 +613,23 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
668
613
  signal: ctx.signal,
669
614
  clock: defaults.clock,
670
615
  toolEvent: radianToolEvent,
616
+ onStart: writeSession,
617
+ onSkipped: (chars) => {
618
+ void jsonl.pushStamped(jsonl.stamp(skippedLineRecord(chars)));
619
+ },
671
620
  onLine(line) {
672
621
  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);
622
+ const received = jsonl.stamp(logged);
623
+ timings.record(received.value, received.at);
624
+ const writing = jsonl.pushStamped(received);
625
+ deliverLine(ctx.receiver, received.text, logSecrets);
626
+ const parsed = resultValue(received.value);
676
627
  if (parsed !== undefined) result = parsed;
677
628
  return writing;
678
629
  },
679
630
  });
680
631
  await jsonl.end();
632
+ const worker = workerResultOf(result);
681
633
 
682
634
  // A resumed run continues the session it was given. Another id means
683
635
  // radian started afresh and the earlier conversation is lost.
@@ -688,25 +640,30 @@ export function createRadianHarnessPlugin(settings: RadianHarnessSettings = {})
688
640
  outcome.exitCode === 0 &&
689
641
  result.sessionId !== resumeSession
690
642
  ) {
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
- };
643
+ const timing = timings.finish();
644
+ return withTimings(
645
+ withModelError(
646
+ result,
647
+ failure(who, "failed", outcome, worker, ctx.logger.path, timing.totalMs, {
648
+ reason: "session_missing",
649
+ message: `radian did not continue the session ${resumeSession}; it answered with ${result.sessionId ?? "no session"}`,
650
+ }),
651
+ ),
652
+ timing,
653
+ );
698
654
  }
699
655
 
700
- return resultFor(
656
+ const timing = timings.finish();
657
+ const stepResult = resultFor(
701
658
  who,
702
659
  outcome,
703
- result,
660
+ worker,
704
661
  ctx.logger.path,
705
- Date.now() - started,
706
- wallTimeSecs,
707
- stallSecs,
662
+ timing.totalMs,
663
+ { wallTimeSecs, stallSecs },
708
664
  commandName,
709
665
  );
666
+ return withTimings(withModelError(result, stepResult), timing);
710
667
  },
711
668
  },
712
669
  ],