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