@useavalon/caelence-agent 0.3.0 → 0.4.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/src/runtime.ts CHANGED
@@ -8,6 +8,12 @@ import {
8
8
  mentionsBrowser,
9
9
  startBrowserTools,
10
10
  } from "./browser/browser-use.ts";
11
+ import {
12
+ hostsInText,
13
+ ownChromeFailureHint,
14
+ ownChromePrompt,
15
+ startOwnChromeTools,
16
+ } from "./browser/own-chrome.ts";
11
17
  import { resolveTheme, type Theme } from "./cli/theme.ts";
12
18
  import { type HarnessConfig, loadConfig, resolveOpenRouter } from "./config.ts";
13
19
  import {
@@ -32,6 +38,7 @@ import {
32
38
  defaultSummarizer,
33
39
  type RunTurnDeps,
34
40
  runTurn,
41
+ type TurnInterceptor,
35
42
  } from "./core/run-turn.ts";
36
43
  import {
37
44
  createFileSessionStore,
@@ -95,6 +102,42 @@ import { createReadSkillTool } from "./tools/read-skill.ts";
95
102
  import { createTaskTool } from "./tools/subagent.ts";
96
103
  import { createMemoryTodoStore, createTodoTool } from "./tools/todo.ts";
97
104
 
105
+ /** Per-turn options a host can pass to `runTurn`. */
106
+ export interface HarnessTurnOptions {
107
+ signal?: AbortSignal;
108
+ approvalAsk?: (req: ApprovalRequest) => Promise<boolean>;
109
+ editUserTurn?: number;
110
+ /**
111
+ * What the chat shows and stores, and what decisions and `@browser` read, when it differs from
112
+ * the `message` the model sees. Lets a host prefix instructions without them reaching the chat.
113
+ */
114
+ displayMessage?: string;
115
+ /** Appended to the system prompt for this turn only. */
116
+ systemAppend?: string;
117
+ /** Tool names hidden from the model for this turn only. */
118
+ excludeTools?: readonly string[];
119
+ /**
120
+ * Turn the browser tools on for this turn and the rest of the chat, as if the user had written
121
+ * `@browser`. Ignored when `browser.enabled` is false in the config or the mode is not `agent`.
122
+ */
123
+ browser?: boolean;
124
+ /**
125
+ * Sites the user asked for, as a host app resolved them from their words ("x" to x.com). The
126
+ * browser opens these without asking. Hosts written out in the message are trusted already.
127
+ */
128
+ trustedHosts?: readonly string[];
129
+ /**
130
+ * Data for this turn that the harness passes back to the host's `intercept` hook untouched, for
131
+ * example flags the host's UI sent with the request.
132
+ */
133
+ hostData?: Record<string, unknown>;
134
+ /**
135
+ * Ask the user only about requests this returns true for. Every other tool call runs without a
136
+ * prompt. The `deny` policy and the host denylist still apply to the calls it lets through.
137
+ */
138
+ promptOnly?: (req: ApprovalRequest) => boolean;
139
+ }
140
+
98
141
  export interface HarnessRuntime {
99
142
  cwd: string;
100
143
  config: HarnessConfig;
@@ -105,17 +148,15 @@ export interface HarnessRuntime {
105
148
  modelId: string;
106
149
  mode: AgentMode;
107
150
  activeSessionId?: string;
151
+ /** True when the browser tools are on for the current chat, by `@browser`, a turn option, or config. */
152
+ readonly browserActive: boolean;
108
153
  spend?: TokenUsage;
109
154
  hasApiKey: boolean;
110
155
  setApiKey(key: string): void;
111
156
  runTurn(
112
157
  message: string,
113
158
  emit: AgentEventEmitter,
114
- options?: {
115
- signal?: AbortSignal;
116
- approvalAsk?: (req: ApprovalRequest) => Promise<boolean>;
117
- editUserTurn?: number;
118
- },
159
+ options?: HarnessTurnOptions,
119
160
  ): Promise<Session | undefined>;
120
161
  setModel(modelId: string): void;
121
162
  setMode(mode: AgentMode): void;
@@ -161,6 +202,10 @@ export interface CreateHarnessOptions {
161
202
  decisions?: boolean;
162
203
  /** Host judgment of which messages are one direct tool call. See ShortcutPlanner. */
163
204
  shortcut?: ShortcutPlanner;
205
+ /** Host handler that can answer a whole turn without the chat model. See TurnInterceptor. */
206
+ intercept?: TurnInterceptor;
207
+ /** Appended to the system prompt on every turn, for example a host persona. */
208
+ systemAppend?: string;
164
209
  /** Replaces fetch for decision calls. Tests only. */
165
210
  decisionsFetch?: FetchImpl;
166
211
  }
@@ -191,8 +236,9 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
191
236
  let skills = loadActiveSkills();
192
237
  const layers = loadInstructionLayers({ cwd, projectFile: config.instructionsFile });
193
238
  let mode = parseAgentMode(options.mode ?? config.mode);
194
- const composePrompt = (nextMode: AgentMode) =>
195
- buildSystemPrompt({
239
+ const hostAppend = options.systemAppend?.trim();
240
+ const composePrompt = (nextMode: AgentMode) => {
241
+ const base = buildSystemPrompt({
196
242
  name: config.name,
197
243
  cwd,
198
244
  userInstructions: layers.user,
@@ -200,6 +246,8 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
200
246
  skillCatalog: skillCatalogPrompt(skills),
201
247
  mode: nextMode,
202
248
  });
249
+ return hostAppend ? `${base}\n\n${hostAppend}` : base;
250
+ };
203
251
  let systemPrompt = composePrompt(mode);
204
252
  const store = createFileSessionStore(cwd);
205
253
  const local = createLocalTools({
@@ -274,22 +322,49 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
274
322
  let browserSticky = false;
275
323
  let browserTools: McpToolDefinition[] = [];
276
324
  let browserNote = "";
277
- const resolveBrowser = async (message: string): Promise<void> => {
325
+ const ownChrome = config.browser?.backend === "chrome";
326
+ const resolveBrowser = async (
327
+ message: string,
328
+ requested = false,
329
+ trustedHosts: readonly string[] = [],
330
+ ): Promise<void> => {
278
331
  browserTools = [];
279
332
  browserNote = "";
280
333
  const access = browserAccess(config.browser);
281
334
  if (access === "off" || mode !== "agent") return;
282
- if (mentionsBrowser(message)) browserSticky = true;
335
+ if (requested || mentionsBrowser(message)) browserSticky = true;
283
336
  if (access !== "always" && !browserSticky) return;
284
337
  try {
285
- browserStart ??= startBrowserTools(config.browser, cwd, options.browserLoader);
286
- browserTools = (await browserStart).tools;
287
- browserNote = browserPrompt();
338
+ browserStart ??= ownChrome
339
+ ? startOwnChromeTools(config.browser, cwd, options.browserLoader)
340
+ : startBrowserTools(config.browser, cwd, options.browserLoader);
341
+ let started = await browserStart;
342
+ if (started.stale?.()) {
343
+ // The browser was not reachable last time and the server is fixed to the address it
344
+ // started with. The user may have set the browser up since, so start a fresh one.
345
+ started.close();
346
+ browserStart = startOwnChromeTools(config.browser, cwd, options.browserLoader);
347
+ started = await browserStart;
348
+ }
349
+ // Sites the user wrote, or the host app resolved from their words, open without asking.
350
+ started.trust?.([...hostsInText(message), ...trustedHosts]);
351
+ browserTools = started.tools;
352
+ browserNote = ownChrome ? ownChromePrompt() : browserPrompt();
288
353
  } catch (err) {
289
354
  browserStart = undefined;
290
- browserNote = browserFailurePrompt(browserSetupHint(err));
355
+ browserNote = browserFailurePrompt(
356
+ ownChrome ? ownChromeFailureHint(err) : browserSetupHint(err),
357
+ );
291
358
  }
292
359
  };
360
+ /** A new chat starts clean: the agent's tab, approvals, and trusted sites do not carry over. */
361
+ const resetBrowserChat = (): void => {
362
+ browserSticky = false;
363
+ void browserStart?.then(
364
+ (started) => started.reset?.(),
365
+ () => undefined,
366
+ );
367
+ };
293
368
 
294
369
  const or = resolveOpenRouter(config);
295
370
  let apiKey = or.apiKey;
@@ -302,13 +377,14 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
302
377
  : await createObservability({ enabled: config.observability?.enabled }));
303
378
  if (!options.observability) void syncPrompts({ prompts: harnessPromptRecords() });
304
379
  const agentVersion = resolveAgentVersion();
305
- const makeProvider = (id: string): MainModelProvider =>
380
+ const makeProvider = (id: string, title?: string): MainModelProvider =>
306
381
  options.provider ??
307
382
  constructOpenRouterProvider({
308
383
  apiKey,
309
384
  model: id,
310
385
  baseUrl: or.baseUrl,
311
386
  sessionId: () => activeSessionId,
387
+ ...(title ? { title } : {}),
312
388
  });
313
389
  let provider = makeProvider(modelId);
314
390
  const constructAgent = options.constructAgent ?? createConstructAgent();
@@ -365,8 +441,13 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
365
441
  get activeSessionId() {
366
442
  return activeSessionId;
367
443
  },
444
+ get browserActive() {
445
+ const access = browserAccess(config.browser);
446
+ if (access === "off" || mode !== "agent") return false;
447
+ return access === "always" || browserSticky;
448
+ },
368
449
  set activeSessionId(id: string | undefined) {
369
- if (id !== activeSessionId) browserSticky = false;
450
+ if (id !== activeSessionId) resetBrowserChat();
370
451
  activeSessionId = id;
371
452
  },
372
453
  get hasApiKey() {
@@ -388,7 +469,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
388
469
  systemPrompt = composePrompt(mode);
389
470
  },
390
471
  setSession(id) {
391
- if (id !== activeSessionId) browserSticky = false;
472
+ if (id !== activeSessionId) resetBrowserChat();
392
473
  activeSessionId = id;
393
474
  },
394
475
  allowExecAlways() {
@@ -502,6 +583,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
502
583
  return undefined;
503
584
  }
504
585
  const policy = options.approvalPolicy ?? config.tools.exec.approval;
586
+ const userText = turnOptions?.displayMessage ?? message;
505
587
  const decisions: ResolvedDecisions | undefined =
506
588
  options.provider && options.decisions !== true
507
589
  ? undefined
@@ -511,9 +593,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
511
593
  alwaysAllow,
512
594
  emit,
513
595
  assist: decisions?.approvals
514
- ? (req) => classifyToolApproval(decisions, req, message, turnOptions?.signal)
596
+ ? (req) => classifyToolApproval(decisions, req, userText, turnOptions?.signal)
515
597
  : undefined,
516
598
  resolveUploadEdit: (path) => matchUploadEdit(cwd, path),
599
+ promptOnly: turnOptions?.promptOnly,
517
600
  ask: async (req) => {
518
601
  if (turnOptions?.approvalAsk) return turnOptions.approvalAsk(req);
519
602
  if (policy === "prompt") return false;
@@ -522,7 +605,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
522
605
  });
523
606
  activeEmit = emit;
524
607
  activeApproval = approval;
525
- await resolveBrowser(message);
608
+ await resolveBrowser(userText, turnOptions?.browser === true, turnOptions?.trustedHosts);
526
609
  const tools = baseTools();
527
610
  if (subagentsEnabled && toolsAllowedInMode(mode, "task")) {
528
611
  tools.push(
@@ -558,7 +641,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
558
641
  const deps: RunTurnDeps = {
559
642
  cwd,
560
643
  name: config.name,
561
- systemPrompt: [systemPromptWithMemory(systemPrompt, cwd, message, memoryOn), browserNote]
644
+ systemPrompt: [systemPromptWithMemory(systemPrompt, cwd, userText, memoryOn), browserNote]
562
645
  .filter(Boolean)
563
646
  .join("\n\n"),
564
647
  tools,
@@ -566,7 +649,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
566
649
  store,
567
650
  provider,
568
651
  constructAgent,
569
- resolveProvider: options.provider ? undefined : (id) => makeProvider(id),
652
+ resolveProvider: options.provider ? undefined : (id, title) => makeProvider(id, title),
570
653
  summarize: defaultSummarizer(provider),
571
654
  observability,
572
655
  traceName: "agent_turn",
@@ -576,6 +659,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
576
659
  mode,
577
660
  decisions,
578
661
  shortcut: options.shortcut,
662
+ intercept: options.intercept,
579
663
  };
580
664
  const capture: AgentEventEmitter = (event) => {
581
665
  if (event.kind === "usage") {
@@ -597,6 +681,12 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
597
681
  ...(turnOptions?.editUserTurn !== undefined
598
682
  ? { editUserTurn: turnOptions.editUserTurn }
599
683
  : {}),
684
+ ...(turnOptions?.displayMessage !== undefined
685
+ ? { displayMessage: turnOptions.displayMessage }
686
+ : {}),
687
+ ...(turnOptions?.systemAppend ? { systemAppend: turnOptions.systemAppend } : {}),
688
+ ...(turnOptions?.excludeTools?.length ? { excludeTools: turnOptions.excludeTools } : {}),
689
+ ...(turnOptions?.hostData ? { hostData: turnOptions.hostData } : {}),
600
690
  },
601
691
  capture,
602
692
  { signal: turnOptions?.signal },