@open-cr-agent/runtime-direct 0.14.0 → 0.16.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/dist/anthropic.js CHANGED
@@ -7,6 +7,10 @@ const MAX_OUTPUT_TOKENS = 32_000;
7
7
  // Anthropic charges a quarter above the input rate for input it stores.
8
8
  const CACHE_WRITE_FACTOR = 1.25;
9
9
  const CACHED = { cache_control: { type: "ephemeral" } };
10
+ // The API takes four cache marks a request: the system prompt's, the newest
11
+ // block's, and these. A dialogue of one request leaves its newest block
12
+ // unmarked and has that mark for a shared start.
13
+ const MAX_SHARED_MARKS = 2;
10
14
  // How the API names the effort parameters in a 400 that refuses them.
11
15
  const EFFORT_PARAMETER = /\b(?:effort|output_config|thinking)\b/i;
12
16
  // The API has no level under "low", and its newer models cannot stop
@@ -21,22 +25,28 @@ const LEVELS = {
21
25
  // A conversation in Anthropic's Messages protocol, streamed so a long answer
22
26
  // does not sit behind an idle connection. The system prompt and the
23
27
  // conversation so far are marked for the provider's prompt cache at every
24
- // request: an agent's next step reads what the last one stored.
25
- export const anthropicWire = ({ endpoint, model, price, system }) => {
28
+ // request: an agent's next step reads what the last one stored. A start the
29
+ // run's other conversations open with is marked too, so they read it from
30
+ // the first that stored it (ADR-0064). A dialogue of one request has no next
31
+ // step, and storing costs a quarter more than sending, so its conversation
32
+ // goes unmarked; its system prompt stays marked for the other calls of its
33
+ // kind.
34
+ export const anthropicWire = ({ endpoint, model, price, system, oneRequest }) => {
26
35
  const client = clientOf(endpoint);
27
36
  const secrets = endpoint.apiKey ? [endpoint.apiKey] : [];
28
37
  const messages = [];
29
38
  const send = (request, signal) => onceMore(() => stream(client, request, price, secrets, signal), signal);
30
39
  return {
31
- say: (text) => {
32
- messages.push({ role: "user", content: [{ type: "text", text }] });
40
+ say: (text, shared = []) => {
41
+ const marks = oneRequest ? MAX_SHARED_MARKS + 1 : MAX_SHARED_MARKS;
42
+ messages.push({ role: "user", content: textBlocks(text, shared, marks) });
33
43
  },
34
44
  ask: async (tools, settings, signal) => {
35
45
  const request = (sent) => ({
36
46
  model,
37
47
  max_tokens: MAX_OUTPUT_TOKENS,
38
48
  system: [{ type: "text", text: system, ...CACHED }],
39
- messages: withBreakpoint(messages),
49
+ messages: oneRequest ? messages : withBreakpoint(messages),
40
50
  ...(tools.length > 0 ? { tools: tools.map(toolSpec) } : {}),
41
51
  ...effortParams(sent.effort),
42
52
  });
@@ -102,6 +112,19 @@ function effortParams(effort) {
102
112
  ...(effort === "none" ? {} : { thinking: { type: "adaptive" } }),
103
113
  };
104
114
  }
115
+ // The text as blocks that end where a shared start does: together they read
116
+ // as the text does. The first `marks` are stored; a later one only ends a
117
+ // block, which is where a request looks for what another stored.
118
+ function textBlocks(text, shared, marks) {
119
+ const ends = shared.filter((end) => end > 0 && end < text.length);
120
+ const blocks = [];
121
+ let from = 0;
122
+ for (const [i, end] of ends.entries()) {
123
+ blocks.push({ type: "text", text: text.slice(from, end), ...(i < marks ? CACHED : {}) });
124
+ from = end;
125
+ }
126
+ return [...blocks, { type: "text", text: text.slice(from) }];
127
+ }
105
128
  // The last block of the conversation carries the cache mark; the stored
106
129
  // messages stay unmarked, so each request has one.
107
130
  function withBreakpoint(messages) {
package/dist/loop.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ModelPrice, type ReviewContext, type TaskAttempt, type ToolDefinition, type Usage } from "@open-cr-agent/core";
1
+ import { type ModelPrice, type RateLimits, type ReviewContext, type TaskAttempt, type ToolDefinition, type Usage } from "@open-cr-agent/core";
2
2
  import { type CallSettings, type Endpoint, type Wire } from "./wire.js";
3
3
  export interface LoopInput {
4
4
  wire: Wire;
@@ -7,9 +7,11 @@ export interface LoopInput {
7
7
  price: ModelPrice;
8
8
  system: string;
9
9
  user: string;
10
+ shared?: readonly number[];
10
11
  tools: readonly ToolDefinition[];
11
12
  context: ReviewContext;
12
13
  maxSteps: number;
14
+ oneRequest?: boolean;
13
15
  resume?: string;
14
16
  wrapUp?: WrapUpTurn;
15
17
  timeoutMs: number;
@@ -17,6 +19,7 @@ export interface LoopInput {
17
19
  onEffortRefused?: () => void;
18
20
  signal: AbortSignal;
19
21
  onUsage?: (spent: Usage) => void;
22
+ limits?: RateLimits;
20
23
  }
21
24
  interface WrapUpTurn {
22
25
  message: string;
package/dist/loop.js CHANGED
@@ -7,14 +7,14 @@ import { withoutEffort, } from "./wire.js";
7
7
  // for the pipeline to validate.
8
8
  export async function runLoop(input) {
9
9
  const conversation = new Conversation(input);
10
- const outcome = await conversation.turn(input.user, input.tools, input.maxSteps, input.resume);
10
+ const outcome = await conversation.turn({ text: input.user, ...(input.shared ? { shared: input.shared } : {}) }, input.tools, input.maxSteps, input.resume);
11
11
  const { wrapUp } = input;
12
12
  if (!wrapUp)
13
13
  return outcome;
14
14
  const tools = input.tools.filter((t) => wrapUp.tools.includes(t.name));
15
15
  return {
16
16
  ...outcome,
17
- wrapUp: () => conversation.turn(wrapUp.message, tools, outcome.steps + wrapUp.steps),
17
+ wrapUp: () => conversation.turn({ text: wrapUp.message }, tools, outcome.steps + wrapUp.steps),
18
18
  };
19
19
  }
20
20
  // One attempt's dialogue and outcome, which a later turn continues under the
@@ -47,14 +47,10 @@ class Conversation {
47
47
  const { input, dialogue, outcome, texts, uses } = this;
48
48
  const tools = new Map(offered.map((t) => [t.name, t]));
49
49
  let done = false;
50
- dialogue.say(message);
50
+ dialogue.say(message.text, message.shared);
51
51
  while (outcome.steps < maxSteps) {
52
- const response = await dialogue.ask(offered, this.settings, this.signal);
52
+ const response = await this.ask(offered);
53
53
  outcome.steps += 1;
54
- if (response.effortDropped) {
55
- this.settings = withoutEffort(this.settings);
56
- input.onEffortRefused?.();
57
- }
58
54
  if (!response.ok) {
59
55
  outcome.error = this.timeout.aborted
60
56
  ? { message: `timed out after ${Math.round(input.timeoutMs / 1000)}s`, retryable: true }
@@ -65,6 +61,9 @@ class Conversation {
65
61
  input.onUsage?.(outcome.usage);
66
62
  if (response.text)
67
63
  texts.push(response.text);
64
+ // A completion's tools are only there to match a task's request.
65
+ if (input.oneRequest)
66
+ break;
68
67
  if (response.calls.length === 0) {
69
68
  const stoppedEarly = resume && !outcome.resumed && texts.join("").trim() === "";
70
69
  if (stoppedEarly && outcome.steps < maxSteps) {
@@ -93,6 +92,22 @@ class Conversation {
93
92
  delete outcome.atStepCap;
94
93
  return { ...snapshot(outcome), ...exploredBy(uses) };
95
94
  }
95
+ // One step's answer. A request the endpoint rate-limits is sent again once
96
+ // the model's pause is over: the conversation is kept, where a new attempt
97
+ // would ask and pay for every step before it again.
98
+ async ask(offered) {
99
+ for (;;) {
100
+ const response = await this.dialogue.ask(offered, this.settings, this.signal);
101
+ if (response.effortDropped) {
102
+ this.settings = withoutEffort(this.settings);
103
+ this.input.onEffortRefused?.();
104
+ }
105
+ const quota = response.ok ? undefined : response.error.quota;
106
+ if (!quota || this.signal.aborted || !(await this.input.limits?.waitOut(quota))) {
107
+ return response;
108
+ }
109
+ }
110
+ }
96
111
  }
97
112
  // A later turn adds to the outcome; what an earlier turn returned stays as
98
113
  // it was.
package/dist/runtime.js CHANGED
@@ -31,7 +31,7 @@ export class DirectRuntime {
31
31
  this.efforts = new EffortLedger(this.sampling);
32
32
  this.chains = new ChainRunner(options.models, {
33
33
  refuse: (chain) => this.unreachable(chain),
34
- task: (model, spec, signal, onUsage) => this.attemptTask(model, spec, signal, onUsage),
34
+ task: (model, spec, signal, onUsage, limits) => this.attemptTask(model, spec, signal, onUsage, limits),
35
35
  complete: (model, request, signal) => this.attemptCompletion(model, request, signal),
36
36
  });
37
37
  }
@@ -66,12 +66,13 @@ export class DirectRuntime {
66
66
  complete(request, signal) {
67
67
  return this.chains.complete(request, signal);
68
68
  }
69
- attemptTask(model, spec, signal, onUsage) {
69
+ attemptTask(model, spec, signal, onUsage, limits) {
70
70
  return runLoop({
71
71
  ...this.target(model),
72
72
  ...this.call({ agent: spec.reviewer, effort: spec.effort, model }),
73
73
  system: spec.systemPrompt,
74
74
  user: spec.userPrompt,
75
+ ...(spec.sharedPrefixes ? { shared: spec.sharedPrefixes } : {}),
75
76
  tools: this.tools,
76
77
  context: spec.context,
77
78
  maxSteps: MAX_AGENT_STEPS,
@@ -80,6 +81,7 @@ export class DirectRuntime {
80
81
  timeoutMs: spec.timeoutMs,
81
82
  signal,
82
83
  onUsage,
84
+ limits,
83
85
  });
84
86
  }
85
87
  attemptCompletion(model, request, signal) {
@@ -88,9 +90,12 @@ export class DirectRuntime {
88
90
  ...this.call({ agent: request.agent ?? request.tier, effort: request.effort, model }),
89
91
  system: request.system,
90
92
  user: request.user,
91
- tools: [],
93
+ ...(request.sharedPrefixes ? { shared: request.sharedPrefixes } : {}),
94
+ // As the task that follows opens, so that it reads what this stores.
95
+ tools: request.sharedPrefixes ? this.tools : [],
92
96
  context: NO_CONTEXT,
93
97
  maxSteps: 1,
98
+ oneRequest: true,
94
99
  timeoutMs: request.timeoutMs,
95
100
  signal,
96
101
  });
package/dist/wire.d.ts CHANGED
@@ -34,7 +34,7 @@ export type Answer = ({
34
34
  effortDropped?: true;
35
35
  };
36
36
  export interface Dialogue {
37
- say(text: string): void;
37
+ say(text: string, shared?: readonly number[]): void;
38
38
  ask(tools: readonly ToolDefinition[], settings: CallSettings, signal: AbortSignal): Promise<Answer>;
39
39
  answer(outputs: readonly {
40
40
  call: ToolRequest;
@@ -46,6 +46,7 @@ interface DialogueStart {
46
46
  model: string;
47
47
  price: ModelPrice;
48
48
  system: string;
49
+ oneRequest?: boolean;
49
50
  }
50
51
  export type Wire = (start: DialogueStart) => Dialogue;
51
52
  export declare function withoutEffort(settings: CallSettings): CallSettings;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/runtime-direct",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Agent runtime for Open-CR-Agent that calls declared OpenAI-compatible and Anthropic endpoints directly",
5
5
  "keywords": [
6
6
  "code-review",
@@ -35,7 +35,7 @@
35
35
  ],
36
36
  "dependencies": {
37
37
  "@anthropic-ai/sdk": "^1.12.0",
38
- "@open-cr-agent/core": "0.14.0",
38
+ "@open-cr-agent/core": "0.16.0",
39
39
  "zod": "^4.6.6"
40
40
  },
41
41
  "publishConfig": {