@useavalon/caelence-agent 0.3.0 → 0.5.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 +46 -8
- package/desktop/src/api.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/package.json +12 -4
- package/src/browser/browser-use.test.ts +54 -2
- package/src/browser/browser-use.ts +75 -3
- package/src/browser/own-chrome.test.ts +593 -0
- package/src/browser/own-chrome.ts +542 -0
- package/src/cli/tui-progress.ts +15 -3
- package/src/cli/tui.tsx +7 -0
- package/src/config.ts +31 -2
- package/src/core/approval.test.ts +126 -0
- package/src/core/approval.ts +17 -0
- package/src/core/events.ts +12 -1
- package/src/core/host-extensions.test.ts +605 -0
- package/src/core/mcp.ts +7 -0
- package/src/core/mode.ts +5 -0
- package/src/core/run-turn.test.ts +85 -0
- package/src/core/run-turn.ts +145 -28
- package/src/core/strands.test.ts +89 -0
- package/src/core/strands.ts +3 -1
- package/src/decisions/shortcuts.ts +5 -0
- package/src/desktop/bridge.ts +66 -12
- package/src/desktop/host.test.ts +244 -0
- package/src/desktop/host.ts +59 -0
- package/src/index.ts +122 -4
- 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.ts +253 -53
- 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
|
@@ -340,3 +340,88 @@ describe("runTurn", () => {
|
|
|
340
340
|
}
|
|
341
341
|
});
|
|
342
342
|
});
|
|
343
|
+
|
|
344
|
+
describe("tool confirm", () => {
|
|
345
|
+
function confirmTool(reason: (input: Record<string, unknown>) => string | undefined) {
|
|
346
|
+
const ran: Array<Record<string, unknown>> = [];
|
|
347
|
+
return {
|
|
348
|
+
ran,
|
|
349
|
+
tool: {
|
|
350
|
+
name: "web_click",
|
|
351
|
+
description: "click",
|
|
352
|
+
inputSchema: { type: "object", properties: {} },
|
|
353
|
+
annotations: {
|
|
354
|
+
readOnlyHint: false,
|
|
355
|
+
destructiveHint: false,
|
|
356
|
+
idempotentHint: false,
|
|
357
|
+
openWorldHint: false,
|
|
358
|
+
},
|
|
359
|
+
confirm: reason,
|
|
360
|
+
async handler(input: Record<string, unknown>) {
|
|
361
|
+
ran.push(input);
|
|
362
|
+
return { content: [{ type: "text" as const, text: "clicked" }] };
|
|
363
|
+
},
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function run(
|
|
369
|
+
tool: ReturnType<typeof confirmTool>["tool"],
|
|
370
|
+
ask: (req: { reason?: string }) => Promise<boolean>,
|
|
371
|
+
) {
|
|
372
|
+
const constructAgent: ConstructAgent = (input) => ({
|
|
373
|
+
async run() {
|
|
374
|
+
await input.tools[0]?.invoke({ element: "Post" });
|
|
375
|
+
await input.tools[0]?.invoke({ element: "Cancel" });
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
const events: AgentEvent[] = [];
|
|
379
|
+
const deps: RunTurnDeps = {
|
|
380
|
+
cwd: "/tmp",
|
|
381
|
+
name: "t",
|
|
382
|
+
systemPrompt: "s",
|
|
383
|
+
tools: [tool],
|
|
384
|
+
approval: createExecApprovalGate({ policy: "prompt", emit: (e) => events.push(e), ask }),
|
|
385
|
+
store: createFileSessionStore(await mkdtemp(join(tmpdir(), "confirm-"))),
|
|
386
|
+
provider: fakeProvider,
|
|
387
|
+
constructAgent,
|
|
388
|
+
};
|
|
389
|
+
await runTurn(deps, { message: "go" }, (e) => events.push(e));
|
|
390
|
+
return events;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
test("asks only for calls the tool flags, and runs the rest", async () => {
|
|
394
|
+
const { tool, ran } = confirmTool((input) =>
|
|
395
|
+
input.element === "Post" ? "Click Post" : undefined,
|
|
396
|
+
);
|
|
397
|
+
const reasons: Array<string | undefined> = [];
|
|
398
|
+
await run(tool, async (req) => {
|
|
399
|
+
reasons.push(req.reason);
|
|
400
|
+
return true;
|
|
401
|
+
});
|
|
402
|
+
expect(reasons).toEqual(["Click Post"]);
|
|
403
|
+
expect(ran).toEqual([{ element: "Post" }, { element: "Cancel" }]);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
test("a refused call is not run, and the next call is still judged on its own", async () => {
|
|
407
|
+
const { tool, ran } = confirmTool((input) =>
|
|
408
|
+
input.element === "Post" ? "Click Post" : undefined,
|
|
409
|
+
);
|
|
410
|
+
const events = await run(tool, async () => false);
|
|
411
|
+
expect(ran).toEqual([{ element: "Cancel" }]);
|
|
412
|
+
const ends = events.filter((e) => e.kind === "tool_call_end") as Array<{ success: boolean }>;
|
|
413
|
+
expect(ends.map((e) => e.success)).toEqual([false, true]);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
test("a tool without confirm is unchanged", async () => {
|
|
417
|
+
const { tool, ran } = confirmTool(() => undefined);
|
|
418
|
+
delete (tool as { confirm?: unknown }).confirm;
|
|
419
|
+
let asked = 0;
|
|
420
|
+
await run(tool, async () => {
|
|
421
|
+
asked += 1;
|
|
422
|
+
return true;
|
|
423
|
+
});
|
|
424
|
+
expect(asked).toBe(0);
|
|
425
|
+
expect(ran).toHaveLength(2);
|
|
426
|
+
});
|
|
427
|
+
});
|
package/src/core/run-turn.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { ShortcutPlanner } from "../decisions/shortcuts.ts";
|
|
|
3
3
|
import { noopObservability } from "../observability/noop.ts";
|
|
4
4
|
import { sanitize } from "../observability/sanitize.ts";
|
|
5
5
|
import type { Observability } from "../observability/types.ts";
|
|
6
|
+
import { pickStatusVerbs } from "../status/status-verbs.ts";
|
|
6
7
|
import type { ApprovalGate } from "./approval.ts";
|
|
7
8
|
import { isFileWriteTool, isRiskyToolCall } from "./approval.ts";
|
|
8
9
|
import { errorMessage, isAbortError } from "./errors.ts";
|
|
@@ -35,12 +36,48 @@ import type { AgentTool, ConstructAgent, ConstructedAgent } from "./strands.ts";
|
|
|
35
36
|
const REJECTED_TOOL_MESSAGE = "was denied approval and was not invoked";
|
|
36
37
|
|
|
37
38
|
export interface TurnRequest {
|
|
39
|
+
/** What the model sees as the user's message. */
|
|
38
40
|
message: string;
|
|
39
41
|
sessionId?: string;
|
|
40
42
|
model?: string;
|
|
41
43
|
editUserTurn?: number;
|
|
44
|
+
/**
|
|
45
|
+
* What the transcript stores and titles the chat with, when it differs from `message`. A host
|
|
46
|
+
* can prefix instructions to `message` for the model without them showing up in the chat.
|
|
47
|
+
*/
|
|
48
|
+
displayMessage?: string;
|
|
49
|
+
/** Appended to the system prompt for this turn only. */
|
|
50
|
+
systemAppend?: string;
|
|
51
|
+
/** Tool names hidden from the model for this turn only. */
|
|
52
|
+
excludeTools?: readonly string[];
|
|
53
|
+
/** Host data for this turn, passed to `intercept` untouched. */
|
|
54
|
+
hostData?: Record<string, unknown>;
|
|
42
55
|
}
|
|
43
56
|
|
|
57
|
+
/** What a host `intercept` hook can do with a turn. */
|
|
58
|
+
export interface TurnInterceptContext {
|
|
59
|
+
/** What the user typed, without any host prefix. */
|
|
60
|
+
message: string;
|
|
61
|
+
/**
|
|
62
|
+
* A model provider for `modelId`, for hosts that run their own model calls. `title` labels the
|
|
63
|
+
* calls in OpenRouter usage. When the harness was given a fixed provider, every call returns it.
|
|
64
|
+
*/
|
|
65
|
+
provider: (modelId: string, title?: string) => MainModelProvider;
|
|
66
|
+
/** The `hostData` the host set for this turn. */
|
|
67
|
+
hostData: Record<string, unknown>;
|
|
68
|
+
history: Array<{ role: "user" | "assistant"; content: string }>;
|
|
69
|
+
toolNames: ReadonlySet<string>;
|
|
70
|
+
emit: AgentEventEmitter;
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Handle a whole turn without the chat model, for example a computer-use agent. Return a reply
|
|
76
|
+
* to end the turn with it, or undefined to let the normal agent answer. Text sent through
|
|
77
|
+
* `emit` is part of the reply. Throwing falls through to the normal agent.
|
|
78
|
+
*/
|
|
79
|
+
export type TurnInterceptor = (ctx: TurnInterceptContext) => Promise<{ reply: string } | undefined>;
|
|
80
|
+
|
|
44
81
|
export interface RunTurnDeps {
|
|
45
82
|
cwd: string;
|
|
46
83
|
name: string;
|
|
@@ -51,7 +88,7 @@ export interface RunTurnDeps {
|
|
|
51
88
|
store: SessionStore;
|
|
52
89
|
provider: MainModelProvider;
|
|
53
90
|
constructAgent: ConstructAgent;
|
|
54
|
-
resolveProvider?: (modelId: string) => MainModelProvider;
|
|
91
|
+
resolveProvider?: (modelId: string, title?: string) => MainModelProvider;
|
|
55
92
|
summarize?: SummarizerFn;
|
|
56
93
|
contextWindowTokens?: number;
|
|
57
94
|
maxTokens?: number;
|
|
@@ -66,6 +103,13 @@ export interface RunTurnDeps {
|
|
|
66
103
|
decisions?: ResolvedDecisions;
|
|
67
104
|
/** Host judgment of which messages are a direct tool call. Needs `decisions`. */
|
|
68
105
|
shortcut?: ShortcutPlanner;
|
|
106
|
+
/** Host handler that can answer a whole turn without the chat model. */
|
|
107
|
+
intercept?: TurnInterceptor;
|
|
108
|
+
/**
|
|
109
|
+
* Verbs to pick from for this turn's `status` event. Leave it out for a nested turn, or to
|
|
110
|
+
* send no verbs at all.
|
|
111
|
+
*/
|
|
112
|
+
statusVerbs?: { pool: readonly string[]; perTurn?: number };
|
|
69
113
|
}
|
|
70
114
|
|
|
71
115
|
export async function runTurn(
|
|
@@ -75,20 +119,21 @@ export async function runTurn(
|
|
|
75
119
|
options: { signal?: AbortSignal } = {},
|
|
76
120
|
): Promise<Session | undefined> {
|
|
77
121
|
let session: Session | undefined;
|
|
122
|
+
const stored = req.displayMessage ?? req.message;
|
|
78
123
|
try {
|
|
79
124
|
if (req.sessionId) session = await deps.store.get(req.sessionId);
|
|
80
125
|
if (req.editUserTurn !== undefined) {
|
|
81
126
|
if (!session) throw new Error("No session to edit.");
|
|
82
|
-
session = await deps.store.save(replaceUserTurn(session, req.editUserTurn,
|
|
127
|
+
session = await deps.store.save(replaceUserTurn(session, req.editUserTurn, stored));
|
|
83
128
|
} else {
|
|
84
129
|
session ??= await deps.store.create(deps.systemPrompt, req.model);
|
|
85
130
|
session = await deps.store.append(session, {
|
|
86
131
|
kind: "turn",
|
|
87
132
|
role: "user",
|
|
88
|
-
content:
|
|
133
|
+
content: stored,
|
|
89
134
|
});
|
|
90
135
|
if (!session.title || session.title === "New chat") {
|
|
91
|
-
session = await deps.store.setTitle(session, titleFromUserMessage(
|
|
136
|
+
session = await deps.store.setTitle(session, titleFromUserMessage(stored));
|
|
92
137
|
}
|
|
93
138
|
}
|
|
94
139
|
emit({ kind: "session_meta", sessionId: session.id, title: session.title });
|
|
@@ -100,6 +145,11 @@ export async function runTurn(
|
|
|
100
145
|
session = undefined;
|
|
101
146
|
}
|
|
102
147
|
|
|
148
|
+
if (deps.statusVerbs && deps.statusVerbs.pool.length > 0) {
|
|
149
|
+
const verbs = pickStatusVerbs(deps.statusVerbs.pool, deps.statusVerbs.perTurn);
|
|
150
|
+
if (verbs.length > 0) emit({ kind: "status", verbs });
|
|
151
|
+
}
|
|
152
|
+
|
|
103
153
|
const obs = deps.observability ?? noopObservability;
|
|
104
154
|
const startedAt = Date.now();
|
|
105
155
|
return obs.startTurn(
|
|
@@ -174,40 +224,82 @@ export async function runTurn(
|
|
|
174
224
|
}
|
|
175
225
|
}
|
|
176
226
|
|
|
177
|
-
const
|
|
227
|
+
const appended = req.systemAppend?.trim();
|
|
228
|
+
if (appended) systemPrompt += `\n\n${appended}`;
|
|
229
|
+
const allDefs = deps.mcp ? deps.mcp.listTools() : deps.tools;
|
|
230
|
+
const hidden = new Set(req.excludeTools ?? []);
|
|
231
|
+
const toolDefs = hidden.size > 0 ? allDefs.filter((def) => !hidden.has(def.name)) : allDefs;
|
|
178
232
|
const tools: AgentTool[] = toolDefs.map((def) =>
|
|
179
233
|
guardTool(def, deps.approval, capture, obs, deps.hooks),
|
|
180
234
|
);
|
|
181
235
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
236
|
+
// End the turn with a reply the chat model did not write. A storage failure while saving it
|
|
237
|
+
// ends the turn with an error instead of rejecting out of the trace callback.
|
|
238
|
+
const finishWithReply = async (decision: string): Promise<Session | undefined> => {
|
|
239
|
+
await persistChain;
|
|
240
|
+
try {
|
|
241
|
+
if (session) session = await finalize(deps, session, assistantText, thoughtText);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
capture({ kind: "error", message: errorMessage(err) });
|
|
244
|
+
root.update({
|
|
245
|
+
level: "ERROR",
|
|
246
|
+
statusMessage: errorMessage(err),
|
|
247
|
+
metadata: { status: "failed", generation_duration: Date.now() - startedAt },
|
|
248
|
+
});
|
|
249
|
+
await obs.flush();
|
|
250
|
+
return session;
|
|
251
|
+
}
|
|
252
|
+
capture({ kind: "completion" });
|
|
253
|
+
root.update({
|
|
254
|
+
output: assistantText,
|
|
255
|
+
metadata: { status: "success", generation_duration: Date.now() - startedAt, decision },
|
|
256
|
+
});
|
|
257
|
+
await obs.flush();
|
|
258
|
+
return session;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
if (session && req.editUserTurn === undefined && deps.intercept) {
|
|
262
|
+
const outcome = await tryIntercept(
|
|
263
|
+
deps.intercept,
|
|
264
|
+
{
|
|
265
|
+
message: stored,
|
|
266
|
+
provider: (modelId, title) =>
|
|
267
|
+
deps.resolveProvider ? deps.resolveProvider(modelId, title) : deps.provider,
|
|
268
|
+
hostData: req.hostData ?? {},
|
|
269
|
+
history,
|
|
270
|
+
toolNames: new Set(toolDefs.map((def) => def.name)),
|
|
271
|
+
emit: capture,
|
|
272
|
+
signal: options.signal,
|
|
273
|
+
},
|
|
274
|
+
() => assistantText.length > 0,
|
|
275
|
+
);
|
|
276
|
+
if (outcome.kind === "reply") {
|
|
277
|
+
if (!assistantText) capture({ kind: "text_delta", text: outcome.reply });
|
|
278
|
+
return finishWithReply("intercept");
|
|
279
|
+
}
|
|
280
|
+
if (outcome.kind === "failed") {
|
|
186
281
|
await persistChain;
|
|
187
|
-
|
|
188
|
-
session = await finalize(deps, session, assistantText, thoughtText)
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
level: "ERROR",
|
|
193
|
-
statusMessage: errorMessage(err),
|
|
194
|
-
metadata: { status: "failed", generation_duration: Date.now() - startedAt },
|
|
195
|
-
});
|
|
196
|
-
await obs.flush();
|
|
197
|
-
return session;
|
|
198
|
-
}
|
|
199
|
-
capture({ kind: "completion" });
|
|
282
|
+
if (session)
|
|
283
|
+
session = await finalize(deps, session, assistantText, thoughtText).catch(
|
|
284
|
+
() => session,
|
|
285
|
+
);
|
|
286
|
+
capture({ kind: "error", message: errorMessage(outcome.error) });
|
|
200
287
|
root.update({
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
generation_duration: Date.now() - startedAt,
|
|
205
|
-
decision: "shortcut",
|
|
206
|
-
},
|
|
288
|
+
level: "ERROR",
|
|
289
|
+
statusMessage: errorMessage(outcome.error),
|
|
290
|
+
metadata: { status: "failed", generation_duration: Date.now() - startedAt },
|
|
207
291
|
});
|
|
208
292
|
await obs.flush();
|
|
209
293
|
return session;
|
|
210
294
|
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (session && req.editUserTurn === undefined && deps.shortcut && deps.decisions?.shortcuts) {
|
|
298
|
+
const outcome = await tryShortcut(deps, stored, toolDefs, tools, options.signal);
|
|
299
|
+
if (outcome?.kind === "answered") {
|
|
300
|
+
capture({ kind: "text_delta", text: outcome.reply });
|
|
301
|
+
return finishWithReply("shortcut");
|
|
302
|
+
}
|
|
211
303
|
if (outcome?.kind === "continue" && outcome.agentNote) {
|
|
212
304
|
systemPrompt += `\n\n${outcome.agentNote}`;
|
|
213
305
|
}
|
|
@@ -307,6 +399,29 @@ export async function runTurn(
|
|
|
307
399
|
);
|
|
308
400
|
}
|
|
309
401
|
|
|
402
|
+
type InterceptOutcome =
|
|
403
|
+
| { kind: "reply"; reply: string }
|
|
404
|
+
| { kind: "pass" }
|
|
405
|
+
| { kind: "failed"; error: unknown };
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Run the host interceptor. A throw before it produced any output passes the turn to the normal
|
|
409
|
+
* agent. A throw after output has already reached the user is a failure, because answering again
|
|
410
|
+
* would show two answers glued together.
|
|
411
|
+
*/
|
|
412
|
+
async function tryIntercept(
|
|
413
|
+
intercept: TurnInterceptor,
|
|
414
|
+
ctx: TurnInterceptContext,
|
|
415
|
+
producedOutput: () => boolean,
|
|
416
|
+
): Promise<InterceptOutcome> {
|
|
417
|
+
try {
|
|
418
|
+
const result = await intercept(ctx);
|
|
419
|
+
return result ? { kind: "reply", reply: result.reply } : { kind: "pass" };
|
|
420
|
+
} catch (err) {
|
|
421
|
+
return producedOutput() ? { kind: "failed", error: err } : { kind: "pass" };
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
310
425
|
type ShortcutOutcome =
|
|
311
426
|
| { kind: "answered"; reply: string }
|
|
312
427
|
| { kind: "continue"; agentNote?: string };
|
|
@@ -436,6 +551,8 @@ async function approvalGranted(
|
|
|
436
551
|
callId: string,
|
|
437
552
|
input: Record<string, unknown>,
|
|
438
553
|
): Promise<boolean> {
|
|
554
|
+
const reason = def.confirm?.(input);
|
|
555
|
+
if (reason) return approval.request({ callId, toolName: def.name, input, reason });
|
|
439
556
|
if (!isRiskyToolCall(def.name) && !isFileWriteTool(def.name)) return true;
|
|
440
557
|
return approval.request({ callId, toolName: def.name, input });
|
|
441
558
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
type ConstructAgent,
|
|
4
|
+
constructOpenRouterProvider,
|
|
5
|
+
createConstructAgent,
|
|
6
|
+
type StrandsBackedProvider,
|
|
7
|
+
} from "../index.ts";
|
|
8
|
+
|
|
9
|
+
const BASE_URL = "https://openrouter.ai/api/v1";
|
|
10
|
+
|
|
11
|
+
describe("strands exports", () => {
|
|
12
|
+
it("exposes the agent constructor and OpenRouter provider from the package entry", () => {
|
|
13
|
+
expect(typeof createConstructAgent).toBe("function");
|
|
14
|
+
expect(typeof constructOpenRouterProvider).toBe("function");
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("constructOpenRouterProvider", () => {
|
|
19
|
+
it("returns a provider that reports a missing key instead of calling the network", async () => {
|
|
20
|
+
const provider = constructOpenRouterProvider({
|
|
21
|
+
apiKey: " ",
|
|
22
|
+
model: "x-ai/grok",
|
|
23
|
+
baseUrl: BASE_URL,
|
|
24
|
+
});
|
|
25
|
+
expect(provider.modelId).toBe("x-ai/grok");
|
|
26
|
+
const events = [];
|
|
27
|
+
for await (const event of provider.stream({ messages: [{ role: "user", content: "hi" }] })) {
|
|
28
|
+
events.push(event);
|
|
29
|
+
}
|
|
30
|
+
expect(events).toEqual([
|
|
31
|
+
{ type: "error", message: "OPENROUTER_API_KEY is not set." },
|
|
32
|
+
{ type: "done" },
|
|
33
|
+
]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("builds a Strands-backed provider for a real key", () => {
|
|
37
|
+
const provider = constructOpenRouterProvider({
|
|
38
|
+
apiKey: "sk-test",
|
|
39
|
+
model: "x-ai/grok",
|
|
40
|
+
baseUrl: `${BASE_URL}/`,
|
|
41
|
+
}) as StrandsBackedProvider;
|
|
42
|
+
expect(provider.kind).toBe("openrouter");
|
|
43
|
+
expect(provider.sdkModel).toBeDefined();
|
|
44
|
+
expect(typeof provider.takeUsage).toBe("function");
|
|
45
|
+
expect(typeof provider.setReasoningSink).toBe("function");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("reports no usage before any request has completed", () => {
|
|
49
|
+
const provider = constructOpenRouterProvider({
|
|
50
|
+
apiKey: "sk-test",
|
|
51
|
+
model: "x-ai/grok",
|
|
52
|
+
baseUrl: BASE_URL,
|
|
53
|
+
});
|
|
54
|
+
expect(provider.takeUsage?.()).toBeUndefined();
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("createConstructAgent", () => {
|
|
59
|
+
it("refuses a provider that is not backed by the Strands SDK", () => {
|
|
60
|
+
const construct: ConstructAgent = createConstructAgent();
|
|
61
|
+
const plain = constructOpenRouterProvider({ apiKey: "", model: "m", baseUrl: BASE_URL });
|
|
62
|
+
expect(() =>
|
|
63
|
+
construct({ systemPrompt: "s", tools: [], provider: plain, messages: [] }),
|
|
64
|
+
).toThrow("Strands-backed");
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("constructs an agent for a Strands-backed provider without running it", () => {
|
|
68
|
+
const construct = createConstructAgent();
|
|
69
|
+
const provider = constructOpenRouterProvider({
|
|
70
|
+
apiKey: "sk-test",
|
|
71
|
+
model: "m",
|
|
72
|
+
baseUrl: BASE_URL,
|
|
73
|
+
});
|
|
74
|
+
const agent = construct({
|
|
75
|
+
systemPrompt: "You are a test.",
|
|
76
|
+
tools: [
|
|
77
|
+
{
|
|
78
|
+
name: "echo",
|
|
79
|
+
description: "Echo input.",
|
|
80
|
+
inputSchema: { type: "object", properties: {} },
|
|
81
|
+
invoke: async () => ({ content: [{ type: "text", text: "ok" }] }),
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
provider,
|
|
85
|
+
messages: [{ role: "user", content: "earlier" }],
|
|
86
|
+
});
|
|
87
|
+
expect(typeof agent.run).toBe("function");
|
|
88
|
+
});
|
|
89
|
+
});
|
package/src/core/strands.ts
CHANGED
|
@@ -153,6 +153,8 @@ export function constructOpenRouterProvider(options: {
|
|
|
153
153
|
baseUrl: string;
|
|
154
154
|
maxTokens?: number;
|
|
155
155
|
sessionId?: () => string | undefined;
|
|
156
|
+
/** `X-Title` sent to OpenRouter, so usage can be told apart by purpose. Defaults to the product name. */
|
|
157
|
+
title?: string;
|
|
156
158
|
}): MainModelProvider {
|
|
157
159
|
if (!options.apiKey.trim()) {
|
|
158
160
|
return {
|
|
@@ -178,7 +180,7 @@ export function constructOpenRouterProvider(options: {
|
|
|
178
180
|
baseURL: options.baseUrl.replace(/\/+$/, ""),
|
|
179
181
|
defaultHeaders: {
|
|
180
182
|
"HTTP-Referer": "https://caelence.com",
|
|
181
|
-
"X-Title": PRODUCT_NAME,
|
|
183
|
+
"X-Title": options.title?.trim() || PRODUCT_NAME,
|
|
182
184
|
},
|
|
183
185
|
fetch: createUsageTrackingFetch(
|
|
184
186
|
(usage) => {
|
|
@@ -5,6 +5,11 @@ import type { ResolvedDecisions } from "./config.ts";
|
|
|
5
5
|
* ("open example.com"). The harness owns the mechanism: it checks approval, runs the tool,
|
|
6
6
|
* records the turn, and falls back to the agent on any failure. The host owns the judgment
|
|
7
7
|
* of which messages qualify, usually with a Jev choice question via {@link decide}.
|
|
8
|
+
*
|
|
9
|
+
* Shortcuts only run when decisions are on (an OpenRouter key, not disabled), since the planner
|
|
10
|
+
* receives the resolved decision settings. A host that does not use a decision model, or must
|
|
11
|
+
* run even when decisions are off, should use `intercept` instead, which has no such gate.
|
|
12
|
+
* `message` is what the user typed, without any host prefix.
|
|
8
13
|
*/
|
|
9
14
|
export interface ShortcutPlan {
|
|
10
15
|
toolName: string;
|
package/src/desktop/bridge.ts
CHANGED
|
@@ -39,7 +39,7 @@ import { readMediaPrefs } from "../media/prefs.ts";
|
|
|
39
39
|
import { isMemoryEnabled, writeMemoryPrefs } from "../memory/prefs.ts";
|
|
40
40
|
import { deleteFact, isFactPinned, listFacts, pinFact, unpinFact } from "../memory/store.ts";
|
|
41
41
|
import { PRODUCT_NAME } from "../product.ts";
|
|
42
|
-
import { createHarness, type HarnessRuntime } from "../runtime.ts";
|
|
42
|
+
import { type CreateHarnessOptions, createHarness, type HarnessRuntime } from "../runtime.ts";
|
|
43
43
|
import {
|
|
44
44
|
buildSkillsPage,
|
|
45
45
|
cachedPopularSkills,
|
|
@@ -55,6 +55,7 @@ import {
|
|
|
55
55
|
skillNameFromCatalogId,
|
|
56
56
|
} from "../skills/registry.ts";
|
|
57
57
|
import { resolveUnderCwd, toProjectRel } from "../tools/paths.ts";
|
|
58
|
+
import type { BridgeHost, BridgeHostContext, BridgeTurnPlan } from "./host.ts";
|
|
58
59
|
import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
|
|
59
60
|
import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
|
|
60
61
|
import { filePreviewKind, filePreviewMime } from "./preview-kind.ts";
|
|
@@ -101,6 +102,10 @@ export interface StartDesktopBridgeOptions {
|
|
|
101
102
|
port?: number;
|
|
102
103
|
token?: string;
|
|
103
104
|
harness?: HarnessRuntime;
|
|
105
|
+
/** Options for the harness the bridge creates. Ignored when `harness` is given. */
|
|
106
|
+
harnessOptions?: Omit<CreateHarnessOptions, "cwd">;
|
|
107
|
+
/** Extension points for a host app. See {@link BridgeHost}. */
|
|
108
|
+
extensions?: BridgeHost;
|
|
104
109
|
openUrl?: (url: string) => void;
|
|
105
110
|
openPath?: (path: string, reveal: boolean) => void;
|
|
106
111
|
}
|
|
@@ -174,8 +179,11 @@ function saveProviderOAuth(body: Record<string, unknown>, kind: "google" | "micr
|
|
|
174
179
|
});
|
|
175
180
|
}
|
|
176
181
|
|
|
177
|
-
function chatMessages(session: Session | undefined) {
|
|
178
|
-
|
|
182
|
+
function chatMessages(session: Session | undefined, shown: (text: string) => string = (t) => t) {
|
|
183
|
+
if (!session) return [];
|
|
184
|
+
return sessionTranscript(session).map((line) =>
|
|
185
|
+
line.kind === "user" || line.kind === "assistant" ? { ...line, text: shown(line.text) } : line,
|
|
186
|
+
);
|
|
179
187
|
}
|
|
180
188
|
|
|
181
189
|
function json(data: unknown, status = 200, extra?: HeadersInit): Response {
|
|
@@ -343,7 +351,11 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
343
351
|
const token = options.token ?? randomBytes(24).toString("hex");
|
|
344
352
|
const openUrl = options.openUrl ?? openSystemBrowser;
|
|
345
353
|
if (!options.harness) applyStoredOpenRouterKey();
|
|
346
|
-
const harness =
|
|
354
|
+
const harness =
|
|
355
|
+
options.harness ?? (await createHarness({ ...options.harnessOptions, cwd: options.cwd }));
|
|
356
|
+
const ext: BridgeHost = options.extensions ?? {};
|
|
357
|
+
const hostCtx: BridgeHostContext = { harness };
|
|
358
|
+
const shown = (text: string): string => (ext.displayText ? ext.displayText(text) : text);
|
|
347
359
|
const openPath =
|
|
348
360
|
options.openPath ??
|
|
349
361
|
((path: string, reveal: boolean) => {
|
|
@@ -420,11 +432,16 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
420
432
|
};
|
|
421
433
|
|
|
422
434
|
const route_get_models = async (_req: Request, _url: URL): Promise<Response> => {
|
|
423
|
-
|
|
435
|
+
const extra = (ext.modelItems?.(hostCtx) ?? []).filter(
|
|
436
|
+
(row) => !HARNESS_MODELS.some((model) => model.id === row.id),
|
|
437
|
+
);
|
|
438
|
+
return json({
|
|
439
|
+
items: [...extra, ...modelPickerItems(harness.modelId, cachedLiveTargetNames())],
|
|
440
|
+
});
|
|
424
441
|
};
|
|
425
442
|
|
|
426
443
|
const route_get_settings = async (_req: Request, _url: URL): Promise<Response> => {
|
|
427
|
-
return json(settingsPayload(harness));
|
|
444
|
+
return json({ ...settingsPayload(harness), ...ext.settings?.(hostCtx) });
|
|
428
445
|
};
|
|
429
446
|
|
|
430
447
|
const route_get_integrations = async (_req: Request, _url: URL): Promise<Response> => {
|
|
@@ -700,9 +717,12 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
700
717
|
if (typeof body.memoryEnabled === "boolean") {
|
|
701
718
|
writeMemoryPrefs({ enabled: body.memoryEnabled });
|
|
702
719
|
}
|
|
720
|
+
const hostError = await ext.applySettings?.(hostCtx, body);
|
|
721
|
+
if (hostError) return json({ error: hostError }, 400);
|
|
703
722
|
return json({
|
|
704
723
|
ok: true,
|
|
705
724
|
...settingsPayload(harness),
|
|
725
|
+
...ext.settings?.(hostCtx),
|
|
706
726
|
state: snapshot(harness, busy, title),
|
|
707
727
|
});
|
|
708
728
|
};
|
|
@@ -765,7 +785,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
765
785
|
return json({
|
|
766
786
|
ok: true,
|
|
767
787
|
state: snapshot(harness, busy, title),
|
|
768
|
-
messages: chatMessages(session),
|
|
788
|
+
messages: chatMessages(session, shown),
|
|
769
789
|
});
|
|
770
790
|
};
|
|
771
791
|
|
|
@@ -842,7 +862,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
842
862
|
return json({
|
|
843
863
|
ok: true,
|
|
844
864
|
state: snapshot(harness, busy, title),
|
|
845
|
-
messages: chatMessages(session),
|
|
865
|
+
messages: chatMessages(session, shown),
|
|
846
866
|
});
|
|
847
867
|
}
|
|
848
868
|
return json({
|
|
@@ -890,7 +910,27 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
890
910
|
if (editUserTurn === undefined && incoming.trim().startsWith("/")) {
|
|
891
911
|
return runSlashTurn(incoming);
|
|
892
912
|
}
|
|
893
|
-
|
|
913
|
+
let plan: BridgeTurnPlan | undefined;
|
|
914
|
+
try {
|
|
915
|
+
plan = await ext.beforeTurn?.(hostCtx, { message, body });
|
|
916
|
+
} catch (err) {
|
|
917
|
+
return json({ error: errorMessage(err) || "Could not start the turn." }, 500);
|
|
918
|
+
}
|
|
919
|
+
if (plan?.reply !== undefined) return replyWithoutModel(plan.reply);
|
|
920
|
+
return startTurnStream(message, editUserTurn, plan);
|
|
921
|
+
};
|
|
922
|
+
/** Stream a host-written reply as a finished turn. Nothing is saved to the chat. */
|
|
923
|
+
const replyWithoutModel = (text: string): Response => {
|
|
924
|
+
const encoder = new TextEncoder();
|
|
925
|
+
const events: AgentEvent[] = [{ kind: "text_delta", text }, { kind: "completion" }];
|
|
926
|
+
const body = events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("");
|
|
927
|
+
return new Response(encoder.encode(body), {
|
|
928
|
+
headers: {
|
|
929
|
+
"content-type": "text/event-stream",
|
|
930
|
+
"cache-control": "no-cache",
|
|
931
|
+
...CORS_HEADERS,
|
|
932
|
+
},
|
|
933
|
+
});
|
|
894
934
|
};
|
|
895
935
|
|
|
896
936
|
const parseEditUserTurn = (value: unknown): number | undefined => {
|
|
@@ -909,7 +949,11 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
909
949
|
return json({ outcome, state: snapshot(harness, busy, title) });
|
|
910
950
|
};
|
|
911
951
|
|
|
912
|
-
const startTurnStream = (
|
|
952
|
+
const startTurnStream = (
|
|
953
|
+
message: string,
|
|
954
|
+
editUserTurn?: number,
|
|
955
|
+
plan?: BridgeTurnPlan,
|
|
956
|
+
): Response => {
|
|
913
957
|
busy = true;
|
|
914
958
|
abort = new AbortController();
|
|
915
959
|
const encoder = new TextEncoder();
|
|
@@ -932,7 +976,14 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
932
976
|
}
|
|
933
977
|
}, 4_000);
|
|
934
978
|
void harness
|
|
935
|
-
.runTurn(message, send, {
|
|
979
|
+
.runTurn(plan?.message ?? message, send, {
|
|
980
|
+
...plan?.options,
|
|
981
|
+
// What the user typed is what the chat stores, whatever the model was shown.
|
|
982
|
+
...(plan?.displayMessage !== undefined
|
|
983
|
+
? { displayMessage: plan.displayMessage }
|
|
984
|
+
: plan?.message !== undefined
|
|
985
|
+
? { displayMessage: message }
|
|
986
|
+
: {}),
|
|
936
987
|
signal: abort?.signal,
|
|
937
988
|
approvalAsk: (req: ApprovalRequest) => waitForApproval(pending, req),
|
|
938
989
|
...(editUserTurn !== undefined ? { editUserTurn } : {}),
|
|
@@ -1022,7 +1073,10 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
|
|
|
1022
1073
|
if (readToken(req) !== token) {
|
|
1023
1074
|
return json({ error: `Unauthorized. Restart ${PRODUCT_NAME}.` }, 401);
|
|
1024
1075
|
}
|
|
1025
|
-
const
|
|
1076
|
+
const key = `${req.method} ${url.pathname}`;
|
|
1077
|
+
const hostRoute = ext.routes?.[key];
|
|
1078
|
+
if (hostRoute) return hostRoute(hostCtx, req, url);
|
|
1079
|
+
const matched = bridgeRoutes[key];
|
|
1026
1080
|
if (!matched) return json({ error: "Not found." }, 404);
|
|
1027
1081
|
return matched(req, url);
|
|
1028
1082
|
},
|