@useavalon/caelence-agent 0.4.0 → 0.6.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 +29 -4
- package/desktop/src/DeskComposer.tsx +10 -0
- package/desktop/src/SettingsPanel.tsx +18 -0
- package/desktop/src/api.ts +12 -1
- package/desktop/src/app.css +8 -3
- package/desktop/src/desk-types.ts +1 -0
- package/desktop/src/desktop-turn.ts +7 -0
- package/desktop/src/stream.ts +1 -0
- package/desktop/src/thought.test.ts +16 -0
- package/desktop/src/thought.ts +15 -4
- package/desktop/src/turn-verbs.ts +14 -0
- package/desktop/src/useDeskPicker.ts +17 -1
- package/package.json +7 -4
- package/src/cli/main.test.ts +12 -0
- package/src/cli/main.ts +45 -5
- package/src/cli/slash-dispatch.test.ts +43 -0
- package/src/cli/slash-dispatch.ts +34 -0
- package/src/cli/slash.test.ts +1 -0
- package/src/cli/slash.ts +2 -0
- package/src/cli/tui-progress.ts +15 -3
- package/src/cli/tui.tsx +15 -1
- package/src/config.ts +38 -2
- package/src/core/events.ts +12 -9
- package/src/core/mode.ts +5 -0
- package/src/core/reasoning.test.ts +37 -0
- package/src/core/reasoning.ts +32 -0
- package/src/core/run-turn.test.ts +112 -0
- package/src/core/run-turn.ts +13 -1
- package/src/core/strands.test.ts +106 -2
- package/src/core/strands.ts +46 -11
- package/src/core/usage.test.ts +80 -1
- package/src/core/usage.ts +35 -3
- package/src/desktop/bridge.test.ts +27 -0
- package/src/desktop/bridge.ts +17 -5
- package/src/index.ts +77 -1
- package/src/memory/brief.ts +62 -0
- package/src/memory/embeddings.ts +104 -0
- package/src/memory/extract.ts +9 -8
- package/src/memory/layered.test.ts +202 -0
- package/src/memory/layered.ts +125 -0
- package/src/memory/memory-store.test.ts +299 -0
- package/src/memory/memory-store.ts +295 -0
- package/src/memory/store.ts +70 -20
- package/src/observability/langfuse.ts +9 -2
- package/src/observability/types.ts +5 -0
- package/src/runtime.test.ts +27 -0
- package/src/runtime.ts +164 -34
- package/src/status/categories.ts +64 -0
- package/src/status/default-verbs.ts +190 -0
- package/src/status/status-verb-categories.json +6167 -0
- package/src/status/status-verbs.test.ts +209 -0
- package/src/status/status-verbs.ts +62 -0
- package/src/tools/background.test.ts +304 -0
- package/src/tools/background.ts +432 -0
- package/src/tools/memory.ts +94 -0
package/src/core/strands.test.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { describe, expect, it } from "bun:test";
|
|
2
2
|
import {
|
|
3
|
+
type AgentConstructionInput,
|
|
3
4
|
type ConstructAgent,
|
|
4
5
|
constructOpenRouterProvider,
|
|
5
6
|
createConstructAgent,
|
|
7
|
+
Offload,
|
|
6
8
|
type StrandsBackedProvider,
|
|
7
9
|
} from "../index.ts";
|
|
8
10
|
|
|
@@ -12,6 +14,7 @@ describe("strands exports", () => {
|
|
|
12
14
|
it("exposes the agent constructor and OpenRouter provider from the package entry", () => {
|
|
13
15
|
expect(typeof createConstructAgent).toBe("function");
|
|
14
16
|
expect(typeof constructOpenRouterProvider).toBe("function");
|
|
17
|
+
expect(typeof Offload.drop).toBe("function");
|
|
15
18
|
});
|
|
16
19
|
});
|
|
17
20
|
|
|
@@ -45,13 +48,89 @@ describe("constructOpenRouterProvider", () => {
|
|
|
45
48
|
expect(typeof provider.setReasoningSink).toBe("function");
|
|
46
49
|
});
|
|
47
50
|
|
|
48
|
-
it("
|
|
51
|
+
it("sends the chosen reasoning effort on chat requests", async () => {
|
|
52
|
+
const bodies: unknown[] = [];
|
|
53
|
+
const realFetch = globalThis.fetch;
|
|
54
|
+
globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
|
|
55
|
+
if (typeof init?.body === "string") bodies.push(JSON.parse(init.body));
|
|
56
|
+
return new Response(JSON.stringify({ error: { message: "stop" } }), { status: 400 });
|
|
57
|
+
}) as unknown as typeof fetch;
|
|
58
|
+
try {
|
|
59
|
+
const provider = constructOpenRouterProvider({
|
|
60
|
+
apiKey: "sk-test",
|
|
61
|
+
model: "x-ai/grok",
|
|
62
|
+
baseUrl: BASE_URL,
|
|
63
|
+
reasoningEffort: "high",
|
|
64
|
+
});
|
|
65
|
+
for await (const _event of provider.stream({
|
|
66
|
+
messages: [{ role: "user", content: "hi" }],
|
|
67
|
+
})) {
|
|
68
|
+
// drain
|
|
69
|
+
}
|
|
70
|
+
} finally {
|
|
71
|
+
globalThis.fetch = realFetch;
|
|
72
|
+
}
|
|
73
|
+
expect(bodies.length).toBeGreaterThan(0);
|
|
74
|
+
const body = bodies[0] as { reasoning?: { effort?: string; exclude?: boolean } };
|
|
75
|
+
expect(body.reasoning).toEqual({ effort: "high", exclude: false });
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("reports no usage before any request has completed", async () => {
|
|
49
79
|
const provider = constructOpenRouterProvider({
|
|
50
80
|
apiKey: "sk-test",
|
|
51
81
|
model: "x-ai/grok",
|
|
52
82
|
baseUrl: BASE_URL,
|
|
53
83
|
});
|
|
54
|
-
expect(provider.takeUsage?.()).toBeUndefined();
|
|
84
|
+
expect(await provider.takeUsage?.()).toBeUndefined();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("adds billed cost from every model call in the turn", async () => {
|
|
88
|
+
const remaining = [
|
|
89
|
+
{ prompt_tokens: 10, completion_tokens: 2, total_tokens: 12, cost: 0.01 },
|
|
90
|
+
{ prompt_tokens: 20, completion_tokens: 3, total_tokens: 23, cost: 0.02 },
|
|
91
|
+
];
|
|
92
|
+
const realFetch = globalThis.fetch;
|
|
93
|
+
globalThis.fetch = (async () => {
|
|
94
|
+
const usage = remaining.shift() ?? {
|
|
95
|
+
prompt_tokens: 0,
|
|
96
|
+
completion_tokens: 0,
|
|
97
|
+
total_tokens: 0,
|
|
98
|
+
cost: 0,
|
|
99
|
+
};
|
|
100
|
+
const body = [
|
|
101
|
+
`data: ${JSON.stringify({ choices: [{ delta: { content: "ok" } }] })}\n\n`,
|
|
102
|
+
`data: ${JSON.stringify({
|
|
103
|
+
choices: [{ delta: {}, finish_reason: "stop" }],
|
|
104
|
+
usage,
|
|
105
|
+
})}\n\n`,
|
|
106
|
+
"data: [DONE]\n\n",
|
|
107
|
+
].join("");
|
|
108
|
+
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
|
109
|
+
}) as unknown as typeof fetch;
|
|
110
|
+
try {
|
|
111
|
+
const provider = constructOpenRouterProvider({
|
|
112
|
+
apiKey: "sk-test",
|
|
113
|
+
model: "anthropic/claude-opus-4.5",
|
|
114
|
+
baseUrl: BASE_URL,
|
|
115
|
+
});
|
|
116
|
+
for (let i = 0; i < 2; i++) {
|
|
117
|
+
for await (const _event of provider.stream({
|
|
118
|
+
messages: [{ role: "user", content: "hi" }],
|
|
119
|
+
})) {
|
|
120
|
+
// drain
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const usage = await provider.takeUsage?.();
|
|
124
|
+
expect(usage).toEqual({
|
|
125
|
+
promptTokens: 30,
|
|
126
|
+
completionTokens: 5,
|
|
127
|
+
totalTokens: 35,
|
|
128
|
+
costUsd: 0.03,
|
|
129
|
+
});
|
|
130
|
+
expect(await provider.takeUsage?.()).toBeUndefined();
|
|
131
|
+
} finally {
|
|
132
|
+
globalThis.fetch = realFetch;
|
|
133
|
+
}
|
|
55
134
|
});
|
|
56
135
|
});
|
|
57
136
|
|
|
@@ -86,4 +165,29 @@ describe("createConstructAgent", () => {
|
|
|
86
165
|
});
|
|
87
166
|
expect(typeof agent.run).toBe("function");
|
|
88
167
|
});
|
|
168
|
+
|
|
169
|
+
it("asks the host for a context manager when constructing an agent", () => {
|
|
170
|
+
const seen: AgentConstructionInput[] = [];
|
|
171
|
+
const construct = createConstructAgent({
|
|
172
|
+
contextManager: (input) => {
|
|
173
|
+
seen.push(input);
|
|
174
|
+
return {
|
|
175
|
+
strategies: [Offload.drop("toolResults").when({ preserveRecent: 6 })],
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
const provider = constructOpenRouterProvider({
|
|
180
|
+
apiKey: "sk-test",
|
|
181
|
+
model: "m",
|
|
182
|
+
baseUrl: BASE_URL,
|
|
183
|
+
});
|
|
184
|
+
construct({
|
|
185
|
+
systemPrompt: "You are a test.",
|
|
186
|
+
tools: [],
|
|
187
|
+
provider,
|
|
188
|
+
messages: [],
|
|
189
|
+
});
|
|
190
|
+
expect(seen).toHaveLength(1);
|
|
191
|
+
expect(seen[0]?.systemPrompt).toBe("You are a test.");
|
|
192
|
+
});
|
|
89
193
|
});
|
package/src/core/strands.ts
CHANGED
|
@@ -2,8 +2,21 @@
|
|
|
2
2
|
* The only module that imports @strands-agents/sdk.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import type {
|
|
6
|
-
|
|
5
|
+
import type {
|
|
6
|
+
ContextManagerStrategy,
|
|
7
|
+
JSONSchema,
|
|
8
|
+
Model,
|
|
9
|
+
StreamOptions,
|
|
10
|
+
ToolSpec,
|
|
11
|
+
} from "@strands-agents/sdk";
|
|
12
|
+
import {
|
|
13
|
+
Agent,
|
|
14
|
+
Message,
|
|
15
|
+
type ModelStreamUpdateEvent,
|
|
16
|
+
Offload,
|
|
17
|
+
TextBlock,
|
|
18
|
+
tool,
|
|
19
|
+
} from "@strands-agents/sdk";
|
|
7
20
|
import { OpenAIModel } from "@strands-agents/sdk/models/openai";
|
|
8
21
|
import { PRODUCT_NAME } from "../product.ts";
|
|
9
22
|
import { withAutoRouterFetch } from "./auto-router.ts";
|
|
@@ -15,7 +28,8 @@ import type {
|
|
|
15
28
|
ProviderTurnRequest,
|
|
16
29
|
} from "./events.ts";
|
|
17
30
|
import type { ToolResult } from "./mcp.ts";
|
|
18
|
-
import {
|
|
31
|
+
import { DEFAULT_REASONING_EFFORT, type ReasoningEffort } from "./reasoning.ts";
|
|
32
|
+
import { addUsage, createUsageTrackingFetch, type TokenUsage } from "./usage.ts";
|
|
19
33
|
|
|
20
34
|
export const DEFAULT_MAIN_MODEL_MAX_TOKENS = 8192;
|
|
21
35
|
|
|
@@ -44,6 +58,14 @@ export interface ConstructedAgent {
|
|
|
44
58
|
|
|
45
59
|
export type ConstructAgent = (input: AgentConstructionInput) => ConstructedAgent;
|
|
46
60
|
|
|
61
|
+
export type { ContextManagerStrategy };
|
|
62
|
+
export { Offload };
|
|
63
|
+
|
|
64
|
+
export interface CreateConstructAgentOptions {
|
|
65
|
+
/** Strands context management, decided per turn (e.g. clear old tool results past a size). */
|
|
66
|
+
contextManager?: (input: AgentConstructionInput) => ContextManagerStrategy | undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
47
69
|
export interface StrandsBackedProvider extends MainModelProvider {
|
|
48
70
|
readonly sdkModel: Model;
|
|
49
71
|
setReasoningSink?(sink: ((text: string) => void) | undefined): void;
|
|
@@ -134,7 +156,7 @@ function wrapModelAsProvider(
|
|
|
134
156
|
model: Model,
|
|
135
157
|
kind: string,
|
|
136
158
|
modelId: string,
|
|
137
|
-
takeUsage?: () => TokenUsage | undefined
|
|
159
|
+
takeUsage?: () => TokenUsage | undefined | Promise<TokenUsage | undefined>,
|
|
138
160
|
): StrandsBackedProvider {
|
|
139
161
|
return {
|
|
140
162
|
kind,
|
|
@@ -152,6 +174,8 @@ export function constructOpenRouterProvider(options: {
|
|
|
152
174
|
model: string;
|
|
153
175
|
baseUrl: string;
|
|
154
176
|
maxTokens?: number;
|
|
177
|
+
/** OpenRouter reasoning effort. Defaults to low. */
|
|
178
|
+
reasoningEffort?: ReasoningEffort;
|
|
155
179
|
sessionId?: () => string | undefined;
|
|
156
180
|
/** `X-Title` sent to OpenRouter, so usage can be told apart by purpose. Defaults to the product name. */
|
|
157
181
|
title?: string;
|
|
@@ -166,7 +190,8 @@ export function constructOpenRouterProvider(options: {
|
|
|
166
190
|
},
|
|
167
191
|
};
|
|
168
192
|
}
|
|
169
|
-
let
|
|
193
|
+
let accumulated: TokenUsage | undefined;
|
|
194
|
+
const probes = new Set<Promise<void>>();
|
|
170
195
|
let reasoningSink: ((text: string) => void) | undefined;
|
|
171
196
|
const model = new OpenAIModel({
|
|
172
197
|
api: "chat",
|
|
@@ -174,7 +199,10 @@ export function constructOpenRouterProvider(options: {
|
|
|
174
199
|
modelId: options.model,
|
|
175
200
|
maxTokens: options.maxTokens ?? DEFAULT_MAIN_MODEL_MAX_TOKENS,
|
|
176
201
|
params: {
|
|
177
|
-
reasoning: {
|
|
202
|
+
reasoning: {
|
|
203
|
+
effort: options.reasoningEffort ?? DEFAULT_REASONING_EFFORT,
|
|
204
|
+
exclude: false,
|
|
205
|
+
},
|
|
178
206
|
},
|
|
179
207
|
clientConfig: {
|
|
180
208
|
baseURL: options.baseUrl.replace(/\/+$/, ""),
|
|
@@ -184,19 +212,24 @@ export function constructOpenRouterProvider(options: {
|
|
|
184
212
|
},
|
|
185
213
|
fetch: createUsageTrackingFetch(
|
|
186
214
|
(usage) => {
|
|
187
|
-
|
|
215
|
+
accumulated = addUsage(accumulated, usage);
|
|
188
216
|
},
|
|
189
217
|
withAutoRouterFetch(globalThis.fetch, {
|
|
190
218
|
model: options.model,
|
|
191
219
|
sessionId: options.sessionId,
|
|
192
220
|
}),
|
|
193
221
|
(text) => reasoningSink?.(text),
|
|
222
|
+
(done) => {
|
|
223
|
+
probes.add(done);
|
|
224
|
+
void done.finally(() => probes.delete(done));
|
|
225
|
+
},
|
|
194
226
|
),
|
|
195
227
|
},
|
|
196
228
|
});
|
|
197
|
-
const wrapped = wrapModelAsProvider(model, "openrouter", options.model, () => {
|
|
198
|
-
|
|
199
|
-
|
|
229
|
+
const wrapped = wrapModelAsProvider(model, "openrouter", options.model, async () => {
|
|
230
|
+
await Promise.all([...probes]);
|
|
231
|
+
const usage = accumulated;
|
|
232
|
+
accumulated = undefined;
|
|
200
233
|
return usage;
|
|
201
234
|
});
|
|
202
235
|
wrapped.setReasoningSink = (sink) => {
|
|
@@ -210,7 +243,7 @@ function toolResultToReturn(result: ToolResult): unknown {
|
|
|
210
243
|
return result.content.map((block) => block.text).join("\n");
|
|
211
244
|
}
|
|
212
245
|
|
|
213
|
-
export function createConstructAgent(): ConstructAgent {
|
|
246
|
+
export function createConstructAgent(options: CreateConstructAgentOptions = {}): ConstructAgent {
|
|
214
247
|
return (input: AgentConstructionInput): ConstructedAgent => {
|
|
215
248
|
if (!isStrandsBackedProvider(input.provider)) {
|
|
216
249
|
throw new Error("createConstructAgent requires a Strands-backed MainModelProvider.");
|
|
@@ -231,11 +264,13 @@ export function createConstructAgent(): ConstructAgent {
|
|
|
231
264
|
const seededMessages = input.messages.map(
|
|
232
265
|
(m) => new Message({ role: m.role, content: [new TextBlock(m.content)] }),
|
|
233
266
|
);
|
|
267
|
+
const contextManager = options.contextManager?.(input);
|
|
234
268
|
const agent = new Agent({
|
|
235
269
|
model,
|
|
236
270
|
systemPrompt: input.systemPrompt,
|
|
237
271
|
tools,
|
|
238
272
|
...(seededMessages.length > 0 ? { messages: seededMessages } : {}),
|
|
273
|
+
...(contextManager !== undefined ? { contextManager } : {}),
|
|
239
274
|
});
|
|
240
275
|
|
|
241
276
|
return {
|
package/src/core/usage.test.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
addUsage,
|
|
4
|
+
createUsageTrackingFetch,
|
|
5
|
+
formatUsage,
|
|
6
|
+
mergeRequestUsage,
|
|
7
|
+
parseTokenUsage,
|
|
8
|
+
reasoningTextFromChunk,
|
|
9
|
+
} from "./usage.ts";
|
|
3
10
|
|
|
4
11
|
describe("token usage", () => {
|
|
5
12
|
test("parses OpenAI and OpenRouter shapes", () => {
|
|
@@ -40,6 +47,20 @@ describe("token usage", () => {
|
|
|
40
47
|
});
|
|
41
48
|
});
|
|
42
49
|
|
|
50
|
+
test("mergeRequestUsage keeps billed cost when a later chunk reports zeros", () => {
|
|
51
|
+
expect(
|
|
52
|
+
mergeRequestUsage(
|
|
53
|
+
{ promptTokens: 80_000, completionTokens: 4_000, totalTokens: 84_000, costUsd: 5.4 },
|
|
54
|
+
{ promptTokens: 0, completionTokens: 0, totalTokens: 0, costUsd: 0 },
|
|
55
|
+
),
|
|
56
|
+
).toEqual({
|
|
57
|
+
promptTokens: 80_000,
|
|
58
|
+
completionTokens: 4_000,
|
|
59
|
+
totalTokens: 84_000,
|
|
60
|
+
costUsd: 5.4,
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
43
64
|
test("formatUsage does not invent a dollar amount", () => {
|
|
44
65
|
expect(formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15 })).toBe(
|
|
45
66
|
"12 in · 3 out",
|
|
@@ -47,6 +68,14 @@ describe("token usage", () => {
|
|
|
47
68
|
expect(
|
|
48
69
|
formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15, costUsd: 0.2 }),
|
|
49
70
|
).toBe("12 in · 3 out · $0.20");
|
|
71
|
+
expect(
|
|
72
|
+
formatUsage({
|
|
73
|
+
promptTokens: 80_000,
|
|
74
|
+
completionTokens: 4_000,
|
|
75
|
+
totalTokens: 84_000,
|
|
76
|
+
costUsd: 5.4,
|
|
77
|
+
}),
|
|
78
|
+
).toBe("80000 in · 4000 out · $5.40");
|
|
50
79
|
});
|
|
51
80
|
|
|
52
81
|
test("reads OpenRouter reasoning deltas from chat chunks", () => {
|
|
@@ -67,3 +96,53 @@ describe("token usage", () => {
|
|
|
67
96
|
).toBeUndefined();
|
|
68
97
|
});
|
|
69
98
|
});
|
|
99
|
+
|
|
100
|
+
function sseResponse(chunks: unknown[]): Response {
|
|
101
|
+
const body = chunks
|
|
102
|
+
.map((chunk) =>
|
|
103
|
+
chunk === "[DONE]" ? "data: [DONE]\n\n" : `data: ${JSON.stringify(chunk)}\n\n`,
|
|
104
|
+
)
|
|
105
|
+
.join("");
|
|
106
|
+
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
describe("createUsageTrackingFetch", () => {
|
|
110
|
+
test("reports billed cost once after the stream ends, not per chunk", async () => {
|
|
111
|
+
const seen: Array<{ promptTokens: number; costUsd?: number }> = [];
|
|
112
|
+
let probe: Promise<void> | undefined;
|
|
113
|
+
const tracked = createUsageTrackingFetch(
|
|
114
|
+
(usage) => seen.push({ promptTokens: usage.promptTokens, costUsd: usage.costUsd }),
|
|
115
|
+
async () =>
|
|
116
|
+
sseResponse([
|
|
117
|
+
{ choices: [{ delta: { content: "hi" } }] },
|
|
118
|
+
{
|
|
119
|
+
choices: [{ delta: {}, finish_reason: "stop" }],
|
|
120
|
+
usage: {
|
|
121
|
+
prompt_tokens: 0,
|
|
122
|
+
completion_tokens: 0,
|
|
123
|
+
total_tokens: 0,
|
|
124
|
+
cost: 0,
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
choices: [{ delta: {}, finish_reason: "stop" }],
|
|
129
|
+
usage: {
|
|
130
|
+
prompt_tokens: 80_000,
|
|
131
|
+
completion_tokens: 4_000,
|
|
132
|
+
total_tokens: 84_000,
|
|
133
|
+
cost: 5.4,
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
"[DONE]",
|
|
137
|
+
]),
|
|
138
|
+
undefined,
|
|
139
|
+
(done) => {
|
|
140
|
+
probe = done;
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
const res = await tracked("https://openrouter.ai/api/v1/chat/completions");
|
|
144
|
+
await res.text();
|
|
145
|
+
await probe;
|
|
146
|
+
expect(seen).toEqual([{ promptTokens: 80_000, costUsd: 5.4 }]);
|
|
147
|
+
});
|
|
148
|
+
});
|
package/src/core/usage.ts
CHANGED
|
@@ -31,6 +31,25 @@ export function parseTokenUsage(value: unknown): TokenUsage | undefined {
|
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/** Keep the richer snapshot from one streamed request. Later zero-token chunks must not wipe cost. */
|
|
35
|
+
export function mergeRequestUsage(prev: TokenUsage | undefined, next: TokenUsage): TokenUsage {
|
|
36
|
+
if (!prev) return next;
|
|
37
|
+
const nextCost = next.costUsd;
|
|
38
|
+
const prevCost = prev.costUsd;
|
|
39
|
+
const cost =
|
|
40
|
+
nextCost !== undefined && nextCost > 0
|
|
41
|
+
? nextCost
|
|
42
|
+
: prevCost !== undefined && prevCost > 0
|
|
43
|
+
? prevCost
|
|
44
|
+
: (nextCost ?? prevCost);
|
|
45
|
+
return {
|
|
46
|
+
promptTokens: Math.max(prev.promptTokens, next.promptTokens),
|
|
47
|
+
completionTokens: Math.max(prev.completionTokens, next.completionTokens),
|
|
48
|
+
totalTokens: Math.max(prev.totalTokens, next.totalTokens),
|
|
49
|
+
...(cost !== undefined ? { costUsd: cost } : {}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
34
53
|
export function addUsage(
|
|
35
54
|
a: TokenUsage | undefined,
|
|
36
55
|
b: TokenUsage | undefined,
|
|
@@ -119,21 +138,32 @@ async function pumpSse(
|
|
|
119
138
|
const reader = body.getReader();
|
|
120
139
|
const decoder = new TextDecoder();
|
|
121
140
|
let buf = "";
|
|
141
|
+
let requestUsage: TokenUsage | undefined;
|
|
142
|
+
const recordUsage = (usage: TokenUsage) => {
|
|
143
|
+
requestUsage = mergeRequestUsage(requestUsage, usage);
|
|
144
|
+
};
|
|
122
145
|
try {
|
|
123
146
|
while (true) {
|
|
124
147
|
const { done, value } = await reader.read();
|
|
125
148
|
if (value) buf += decoder.decode(value, { stream: !done });
|
|
126
149
|
const parts = buf.split("\n");
|
|
127
150
|
buf = done ? "" : (parts.pop() ?? "");
|
|
128
|
-
for (const line of parts) scanSseLine(line,
|
|
151
|
+
for (const line of parts) scanSseLine(line, recordUsage, onReasoning);
|
|
129
152
|
if (done) {
|
|
130
|
-
if (buf) scanSseLine(buf,
|
|
153
|
+
if (buf) scanSseLine(buf, recordUsage, onReasoning);
|
|
131
154
|
break;
|
|
132
155
|
}
|
|
133
156
|
}
|
|
134
157
|
} catch {
|
|
135
158
|
// probe side can fail independently of the model stream
|
|
136
159
|
}
|
|
160
|
+
if (requestUsage) {
|
|
161
|
+
try {
|
|
162
|
+
onUsage(requestUsage);
|
|
163
|
+
} catch {
|
|
164
|
+
// keep the probe settled even if the host callback throws
|
|
165
|
+
}
|
|
166
|
+
}
|
|
137
167
|
}
|
|
138
168
|
|
|
139
169
|
type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
@@ -143,6 +173,7 @@ export function createUsageTrackingFetch(
|
|
|
143
173
|
onUsage: (usage: TokenUsage) => void,
|
|
144
174
|
baseFetch: FetchFn = fetch,
|
|
145
175
|
onReasoning?: (text: string) => void,
|
|
176
|
+
onProbe?: (done: Promise<void>) => void,
|
|
146
177
|
): FetchFn {
|
|
147
178
|
return async (input, init) => {
|
|
148
179
|
const res = await baseFetch(input, init);
|
|
@@ -150,7 +181,8 @@ export function createUsageTrackingFetch(
|
|
|
150
181
|
if (!res.body) return res;
|
|
151
182
|
if (contentType.includes("text/event-stream")) {
|
|
152
183
|
const [out, probe] = res.body.tee();
|
|
153
|
-
|
|
184
|
+
const done = pumpSse(probe, onUsage, onReasoning);
|
|
185
|
+
onProbe?.(done);
|
|
154
186
|
return new Response(out, res);
|
|
155
187
|
}
|
|
156
188
|
if (contentType.includes("application/json")) {
|
|
@@ -128,6 +128,33 @@ describe("desktop bridge", () => {
|
|
|
128
128
|
expect(body.hasApiKey).toBe(true);
|
|
129
129
|
expect(body.apiKeyHint).toBe("••••tkey");
|
|
130
130
|
expect(JSON.stringify(body)).not.toContain("sk-or-v1-secretkey");
|
|
131
|
+
|
|
132
|
+
const settings = await fetch(`${ctx.ready.url}/settings`, { headers: ctx.headers });
|
|
133
|
+
const loaded = (await settings.json()) as { reasoningEffort: string };
|
|
134
|
+
expect(loaded.reasoningEffort).toBe("low");
|
|
135
|
+
const savedEffort = await fetch(`${ctx.ready.url}/settings`, {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers: ctx.headers,
|
|
138
|
+
body: JSON.stringify({ reasoningEffort: "high" }),
|
|
139
|
+
});
|
|
140
|
+
const after = (await savedEffort.json()) as {
|
|
141
|
+
reasoningEffort: string;
|
|
142
|
+
state: { reasoningEffort: string };
|
|
143
|
+
};
|
|
144
|
+
expect(after.reasoningEffort).toBe("high");
|
|
145
|
+
expect(after.state.reasoningEffort).toBe("high");
|
|
146
|
+
|
|
147
|
+
const combined = await fetch(`${ctx.ready.url}/settings`, {
|
|
148
|
+
method: "POST",
|
|
149
|
+
headers: ctx.headers,
|
|
150
|
+
body: JSON.stringify({ modelId: "x-ai/grok", reasoningEffort: "nope" }),
|
|
151
|
+
});
|
|
152
|
+
expect(combined.status).toBe(400);
|
|
153
|
+
const unchanged = (await (
|
|
154
|
+
await fetch(`${ctx.ready.url}/settings`, { headers: ctx.headers })
|
|
155
|
+
).json()) as { modelId: string; reasoningEffort: string };
|
|
156
|
+
expect(unchanged.modelId).not.toBe("x-ai/grok");
|
|
157
|
+
expect(unchanged.reasoningEffort).toBe("high");
|
|
131
158
|
} finally {
|
|
132
159
|
await ctx.close();
|
|
133
160
|
if (prevHome === undefined) delete process.env.HARNESS_HOME;
|
package/src/desktop/bridge.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type { ApprovalRequest } from "../core/approval.ts";
|
|
|
18
18
|
import { errorMessage } from "../core/errors.ts";
|
|
19
19
|
import type { AgentEvent } from "../core/events.ts";
|
|
20
20
|
import { tryParseAgentMode } from "../core/mode.ts";
|
|
21
|
+
import { REASONING_EFFORT_USAGE, tryParseReasoningEffort } from "../core/reasoning.ts";
|
|
21
22
|
import { normalizeSessionTitle, type Session, sessionTranscript } from "../core/session.ts";
|
|
22
23
|
import { formatUsage } from "../core/usage.ts";
|
|
23
24
|
import {
|
|
@@ -72,6 +73,7 @@ export interface DesktopState {
|
|
|
72
73
|
name: string;
|
|
73
74
|
cwd: string;
|
|
74
75
|
mode: string;
|
|
76
|
+
reasoningEffort: string;
|
|
75
77
|
modelId: string;
|
|
76
78
|
modelLabel: string;
|
|
77
79
|
modelTarget?: string;
|
|
@@ -144,6 +146,7 @@ function settingsPayload(harness: HarnessRuntime) {
|
|
|
144
146
|
hasApiKey: harness.hasApiKey,
|
|
145
147
|
apiKeyHint: harness.hasApiKey ? maskSecret(process.env.OPENROUTER_API_KEY ?? "") : "",
|
|
146
148
|
mode: harness.mode,
|
|
149
|
+
reasoningEffort: harness.reasoningEffort,
|
|
147
150
|
modelId: harness.modelId,
|
|
148
151
|
modelLabel: modelLabel(harness.modelId),
|
|
149
152
|
hasGoogleOAuth: Boolean(google?.clientId),
|
|
@@ -317,6 +320,7 @@ function snapshot(harness: HarnessRuntime, busy: boolean, title: string): Deskto
|
|
|
317
320
|
name: harness.config.name,
|
|
318
321
|
cwd: harness.cwd,
|
|
319
322
|
mode: harness.mode,
|
|
323
|
+
reasoningEffort: harness.reasoningEffort,
|
|
320
324
|
modelId: harness.modelId,
|
|
321
325
|
modelLabel: label,
|
|
322
326
|
...(target && target.toLowerCase() !== label.toLowerCase() ? { modelTarget: target } : {}),
|
|
@@ -699,19 +703,27 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
699
703
|
|
|
700
704
|
const route_post_settings = async (req: Request, _url: URL): Promise<Response> => {
|
|
701
705
|
const body = await readJson(req);
|
|
706
|
+
const nextMode = typeof body.mode === "string" ? tryParseAgentMode(body.mode) : undefined;
|
|
707
|
+
if (typeof body.mode === "string" && !nextMode) {
|
|
708
|
+
return json({ error: "Mode is ask, plan, or agent." }, 400);
|
|
709
|
+
}
|
|
710
|
+
const nextEffort =
|
|
711
|
+
typeof body.reasoningEffort === "string"
|
|
712
|
+
? tryParseReasoningEffort(body.reasoningEffort)
|
|
713
|
+
: undefined;
|
|
714
|
+
if (typeof body.reasoningEffort === "string" && !nextEffort) {
|
|
715
|
+
return json({ error: REASONING_EFFORT_USAGE }, 400);
|
|
716
|
+
}
|
|
702
717
|
if (typeof body.apiKey === "string") {
|
|
703
718
|
writeOpenRouterKey(body.apiKey);
|
|
704
719
|
harness.setApiKey(body.apiKey);
|
|
705
720
|
refreshLiveNames();
|
|
706
721
|
}
|
|
707
|
-
if (
|
|
708
|
-
const next = tryParseAgentMode(body.mode);
|
|
709
|
-
if (!next) return json({ error: "Mode is ask, plan, or agent." }, 400);
|
|
710
|
-
harness.setMode(next);
|
|
711
|
-
}
|
|
722
|
+
if (nextMode) harness.setMode(nextMode);
|
|
712
723
|
if (typeof body.modelId === "string" && body.modelId.trim()) {
|
|
713
724
|
harness.setModel(body.modelId.trim());
|
|
714
725
|
}
|
|
726
|
+
if (nextEffort) harness.setReasoningEffort(nextEffort);
|
|
715
727
|
saveProviderOAuth(body, "google");
|
|
716
728
|
saveProviderOAuth(body, "microsoft");
|
|
717
729
|
if (typeof body.memoryEnabled === "boolean") {
|
package/src/index.ts
CHANGED
|
@@ -75,6 +75,15 @@ export {
|
|
|
75
75
|
toolsAllowedInMode,
|
|
76
76
|
tryParseAgentMode,
|
|
77
77
|
} from "./core/mode.ts";
|
|
78
|
+
export {
|
|
79
|
+
DEFAULT_REASONING_EFFORT,
|
|
80
|
+
parseReasoningEffort,
|
|
81
|
+
REASONING_EFFORT_USAGE,
|
|
82
|
+
REASONING_EFFORTS,
|
|
83
|
+
type ReasoningEffort,
|
|
84
|
+
resolveReasoningEffort,
|
|
85
|
+
tryParseReasoningEffort,
|
|
86
|
+
} from "./core/reasoning.ts";
|
|
78
87
|
export {
|
|
79
88
|
buildSystemPrompt,
|
|
80
89
|
type RunTurnDeps,
|
|
@@ -102,8 +111,11 @@ export {
|
|
|
102
111
|
type AgentTool,
|
|
103
112
|
type ConstructAgent,
|
|
104
113
|
type ConstructedAgent,
|
|
114
|
+
type ContextManagerStrategy,
|
|
115
|
+
type CreateConstructAgentOptions,
|
|
105
116
|
constructOpenRouterProvider,
|
|
106
117
|
createConstructAgent,
|
|
118
|
+
Offload,
|
|
107
119
|
type StrandsBackedProvider,
|
|
108
120
|
} from "./core/strands.ts";
|
|
109
121
|
export { addUsage, formatUsage, parseTokenUsage, type TokenUsage } from "./core/usage.ts";
|
|
@@ -151,7 +163,42 @@ export { connectMcp } from "./integrations/connect.ts";
|
|
|
151
163
|
export { withOAuthLoopback } from "./integrations/loopback.ts";
|
|
152
164
|
export { openRemoteMcp } from "./integrations/remote-mcp.ts";
|
|
153
165
|
export { listStoredConnections } from "./integrations/store.ts";
|
|
154
|
-
export {
|
|
166
|
+
export {
|
|
167
|
+
DEFAULT_BRIEF_WORDS,
|
|
168
|
+
formatMemoryBriefs,
|
|
169
|
+
memoryBriefSystem,
|
|
170
|
+
synthesizeMemoryBrief,
|
|
171
|
+
} from "./memory/brief.ts";
|
|
172
|
+
export {
|
|
173
|
+
cosineSimilarity,
|
|
174
|
+
createOpenAICompatEmbedder,
|
|
175
|
+
DEFAULT_EMBEDDING_MODEL,
|
|
176
|
+
type Embedder,
|
|
177
|
+
fuseRankings,
|
|
178
|
+
} from "./memory/embeddings.ts";
|
|
179
|
+
export {
|
|
180
|
+
extractMemories,
|
|
181
|
+
MEMORY_EXTRACT_SYSTEM,
|
|
182
|
+
parseExtractedFacts,
|
|
183
|
+
turnMemorySource,
|
|
184
|
+
} from "./memory/extract.ts";
|
|
185
|
+
export {
|
|
186
|
+
createLayeredMemoryStore,
|
|
187
|
+
type LayeredMemoryStore,
|
|
188
|
+
type MemoryLayer,
|
|
189
|
+
} from "./memory/layered.ts";
|
|
190
|
+
export {
|
|
191
|
+
type CreateMemoryStoreOptions,
|
|
192
|
+
createFileMemoryBackend,
|
|
193
|
+
createFileMemoryStore,
|
|
194
|
+
createInMemoryMemoryBackend,
|
|
195
|
+
createMemoryStore,
|
|
196
|
+
type MemoryBackend,
|
|
197
|
+
type MemoryEmbeddingRow,
|
|
198
|
+
type MemoryRecord,
|
|
199
|
+
type MemoryStore,
|
|
200
|
+
type NewMemoryFact,
|
|
201
|
+
} from "./memory/memory-store.ts";
|
|
155
202
|
export { isMemoryEnabled, readMemoryPrefs, writeMemoryPrefs } from "./memory/prefs.ts";
|
|
156
203
|
export { formatMemoryList, formatRetrievedMemory } from "./memory/prompt.ts";
|
|
157
204
|
export {
|
|
@@ -161,6 +208,8 @@ export {
|
|
|
161
208
|
type MemoryFact,
|
|
162
209
|
type MemoryScope,
|
|
163
210
|
pinFact,
|
|
211
|
+
prepareFacts,
|
|
212
|
+
rankFacts,
|
|
164
213
|
searchFacts,
|
|
165
214
|
unpinFact,
|
|
166
215
|
} from "./memory/store.ts";
|
|
@@ -242,8 +291,35 @@ export {
|
|
|
242
291
|
} from "./skills/registry.ts";
|
|
243
292
|
export { parseSkillCommand, SKILL_COMMAND_USAGE, SKILL_FIND_HINT } from "./skills/skill-command.ts";
|
|
244
293
|
export { userSkillsDir } from "./skills/user-dir.ts";
|
|
294
|
+
export {
|
|
295
|
+
resolveStatusVerbPool,
|
|
296
|
+
statusVerbCategories,
|
|
297
|
+
statusVerbCategoryNames,
|
|
298
|
+
} from "./status/categories.ts";
|
|
299
|
+
export {
|
|
300
|
+
DEFAULT_STATUS_VERBS,
|
|
301
|
+
DEFAULT_STATUS_VERBS_PER_TURN,
|
|
302
|
+
FALLBACK_STATUS_VERB,
|
|
303
|
+
pickStatusVerbs,
|
|
304
|
+
type StatusVerbsConfig,
|
|
305
|
+
seededRandom,
|
|
306
|
+
statusVerbAt,
|
|
307
|
+
} from "./status/status-verbs.ts";
|
|
308
|
+
export {
|
|
309
|
+
BACKGROUND_AGENTS_PROMPT,
|
|
310
|
+
type BackgroundAgentRunInput,
|
|
311
|
+
type BackgroundAgentSnapshot,
|
|
312
|
+
type BackgroundAgentStatus,
|
|
313
|
+
type BackgroundAgents,
|
|
314
|
+
type BackgroundAgentsOptions,
|
|
315
|
+
createBackgroundAgents,
|
|
316
|
+
EXPLORE_INSTRUCTIONS,
|
|
317
|
+
readOnlyTools,
|
|
318
|
+
type SubagentKind,
|
|
319
|
+
} from "./tools/background.ts";
|
|
245
320
|
export { createGitTools } from "./tools/git.ts";
|
|
246
321
|
export { createLocalTools } from "./tools/local.ts";
|
|
322
|
+
export { createMemoryTools } from "./tools/memory.ts";
|
|
247
323
|
export { PathEscapeError, resolveUnderCwd } from "./tools/paths.ts";
|
|
248
324
|
export { createReadSkillTool } from "./tools/read-skill.ts";
|
|
249
325
|
export { createTaskTool } from "./tools/subagent.ts";
|