@useavalon/caelence-agent 0.4.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 +23 -0
- 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 +7 -4
- package/src/cli/tui-progress.ts +15 -3
- package/src/cli/tui.tsx +7 -0
- package/src/config.ts +31 -2
- package/src/core/events.ts +5 -0
- package/src/core/mode.ts +5 -0
- package/src/core/run-turn.ts +11 -0
- package/src/index.ts +65 -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.ts +144 -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/README.md
CHANGED
|
@@ -234,10 +234,33 @@ Because the agent acts as you on every site you are signed in to, this backend i
|
|
|
234
234
|
|
|
235
235
|
These checks stand in front of a model. They are not a security boundary, and a page can still try to talk the agent into something. Playwright is pinned to 0.0.83.
|
|
236
236
|
|
|
237
|
+
## Background agents
|
|
238
|
+
|
|
239
|
+
The agent can start subagents that run while it keeps working. `spawn_agent` returns an id at once, `await_agents` collects the reports, and `cancel_agent` stops one. Explore agents get only the tools that declare themselves read-only, and are the default; in ask and plan mode they are the only kind. An agent never outlives the turn that started it.
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
export default {
|
|
243
|
+
subagents: {
|
|
244
|
+
exploreModel: "z-ai/glm-5.2", // a small fast model for search; defaults to the chat model
|
|
245
|
+
maxConcurrent: 4,
|
|
246
|
+
maxPerTurn: 12,
|
|
247
|
+
// background: false turns spawn_agent off and keeps the blocking `task` tool
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
`HARNESS_EXPLORE_MODEL` and `HARNESS_SUBAGENT_MODEL` override the models. A host that calls `runTurn` itself builds the same tools with `createBackgroundAgents`.
|
|
253
|
+
|
|
237
254
|
## Memory
|
|
238
255
|
|
|
239
256
|
Turn it on from the Memory tab or `/memory on` if you want later chats to keep prefs and project decisions. After a turn the model adds a few of those to `~/.harness/memory` and `.harness/memory`, and the next session only sees the ones that fit what you asked. `/memory` lists them, `/memory delete 1` removes a line, and `/memory pin 1` copies it into `AGENTS.md`.
|
|
240
257
|
|
|
258
|
+
Recall matches on words by default. Set `memory.embeddings.enabled` (or `HARNESS_MEMORY_EMBEDDINGS=<model>`) to also match on meaning; fact text is then sent to the embeddings endpoint of your OpenRouter base URL, and the vectors are kept in `vectors.json` beside the facts. When memory is on the agent also gets `memory_search` and `memory_save`.
|
|
259
|
+
|
|
260
|
+
A host keeps memory in its own database by passing a `MemoryStore` to `createHarness`, or by implementing `MemoryBackend` (load, insert, remove, and optionally a vector index) and wrapping it with `createMemoryStore`.
|
|
261
|
+
|
|
262
|
+
For shared context across a team, `createLayeredMemoryStore` reads several stores as one, narrowest first (a project, then its workspace). The agent writes to the narrowest layer only; `promote` moves a fact wider, which a host does when a person asks. `synthesizeMemoryBrief` turns a scope's facts into a short brief to put in the prompt.
|
|
263
|
+
|
|
241
264
|
## Library
|
|
242
265
|
|
|
243
266
|
The desktop, the terminal UI, and `caelence chat -m` all call `createHarness`, so you can drive the same runtime from a bot, a script, or another host UI.
|
package/desktop/src/api.ts
CHANGED
|
@@ -87,6 +87,7 @@ export type AgentEvent =
|
|
|
87
87
|
}
|
|
88
88
|
| { kind: "approval_request"; callId: string; toolName: string; input: Record<string, unknown> }
|
|
89
89
|
| { kind: "session_meta"; sessionId: string; title: string }
|
|
90
|
+
| { kind: "status"; verbs: string[] }
|
|
90
91
|
| {
|
|
91
92
|
kind: "usage";
|
|
92
93
|
promptTokens: number;
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
type StreamLine,
|
|
24
24
|
truncateAfterUserTurn,
|
|
25
25
|
} from "./stream";
|
|
26
|
+
import { setTurnVerbs } from "./turn-verbs";
|
|
26
27
|
|
|
27
28
|
export function applyDesktopTurnEvent(
|
|
28
29
|
event: AgentEvent,
|
|
@@ -42,6 +43,12 @@ export function applyDesktopTurnEvent(
|
|
|
42
43
|
});
|
|
43
44
|
setStatus("approval");
|
|
44
45
|
}
|
|
46
|
+
if (event.kind === "status") {
|
|
47
|
+
setTurnVerbs(event.verbs);
|
|
48
|
+
// A new array so the thinking label renders again with the verbs.
|
|
49
|
+
setLines((prev) => [...prev]);
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
45
52
|
setLines((prev) => applyEvent(prev, event));
|
|
46
53
|
return event.kind === "completion" || event.kind === "error";
|
|
47
54
|
}
|
package/desktop/src/stream.ts
CHANGED
|
@@ -140,4 +140,20 @@ describe("thought fold", () => {
|
|
|
140
140
|
expect(blocks[1].entries[0]).toEqual({ type: "note", text: "I should look this up." });
|
|
141
141
|
expect(blocks[1].entries[1]?.type).toBe("tool");
|
|
142
142
|
});
|
|
143
|
+
|
|
144
|
+
test("the turn's verbs replace the plain phrases", () => {
|
|
145
|
+
const verbs = ["Brewing", "Baking", "Kneading"];
|
|
146
|
+
expect(liveStatusPhrases([], true, verbs)).toEqual(verbs);
|
|
147
|
+
const reading = liveStatusPhrases(
|
|
148
|
+
[
|
|
149
|
+
{ key: "t", type: "tool", name: "read_file", label: "Reading a.ts", status: "running" },
|
|
150
|
+
] as never,
|
|
151
|
+
false,
|
|
152
|
+
verbs,
|
|
153
|
+
);
|
|
154
|
+
expect(reading[0]).toBe("Reading a.ts");
|
|
155
|
+
expect(reading).toContain("Brewing");
|
|
156
|
+
expect(reading).toContain("Baking");
|
|
157
|
+
expect(reading).not.toContain("Thinking");
|
|
158
|
+
});
|
|
143
159
|
});
|
package/desktop/src/thought.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { pipelineProgress } from "./pipeline";
|
|
|
2
2
|
import { isPlatformTool } from "./platform";
|
|
3
3
|
import type { StreamLine } from "./stream";
|
|
4
4
|
import { eventCountSuffix } from "./tool-label";
|
|
5
|
+
import { turnVerbs } from "./turn-verbs";
|
|
5
6
|
|
|
6
7
|
export type ToolLine = Extract<StreamLine, { type: "tool" }>;
|
|
7
8
|
|
|
@@ -66,8 +67,16 @@ export function warmupHeadline(seed: number): string {
|
|
|
66
67
|
return WARMUP_PHRASES[Math.abs(seed) % WARMUP_PHRASES.length] ?? "Thinking";
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
|
|
70
|
-
|
|
70
|
+
/**
|
|
71
|
+
* The phrases the thinking label rotates through. `verbs` are the turn's verbs from its `status`
|
|
72
|
+
* event; without them the plain phrases are used.
|
|
73
|
+
*/
|
|
74
|
+
export function liveStatusPhrases(
|
|
75
|
+
tools: ToolLine[],
|
|
76
|
+
warmup = false,
|
|
77
|
+
verbs: readonly string[] = turnVerbs(),
|
|
78
|
+
): string[] {
|
|
79
|
+
if (warmup || tools.length === 0) return verbs.length > 0 ? [...verbs] : [...WARMUP_PHRASES];
|
|
71
80
|
const pipe = pipelineProgress(tools);
|
|
72
81
|
const out: string[] = [];
|
|
73
82
|
if (pipe) {
|
|
@@ -86,8 +95,10 @@ export function liveStatusPhrases(tools: ToolLine[], warmup = false): string[] {
|
|
|
86
95
|
}
|
|
87
96
|
if (isWriteTool(current)) pushPhrase(out, "Editing");
|
|
88
97
|
}
|
|
89
|
-
|
|
90
|
-
|
|
98
|
+
// The tool label stays first; a couple of verbs fill the pauses between steps.
|
|
99
|
+
const [first, second] = verbs;
|
|
100
|
+
pushPhrase(out, first ?? "Thinking");
|
|
101
|
+
pushPhrase(out, second ?? "Looking this over");
|
|
91
102
|
return out;
|
|
92
103
|
}
|
|
93
104
|
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The verbs the current turn's `status` event carried. The thinking label reads them while it
|
|
3
|
+
* renders. They live outside React state because the label sits several layers below the place
|
|
4
|
+
* events arrive, and they change once per turn.
|
|
5
|
+
*/
|
|
6
|
+
let verbs: readonly string[] = [];
|
|
7
|
+
|
|
8
|
+
export function setTurnVerbs(next: readonly string[]): void {
|
|
9
|
+
verbs = next.filter((verb) => verb.trim().length > 0);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function turnVerbs(): readonly string[] {
|
|
13
|
+
return verbs;
|
|
14
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@useavalon/caelence-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"exports": {
|
|
27
27
|
".": "./src/index.ts",
|
|
28
28
|
"./cli": "./src/cli/main.ts",
|
|
29
|
-
"./observability": "./src/observability/index.ts"
|
|
29
|
+
"./observability": "./src/observability/index.ts",
|
|
30
|
+
"./status-verbs": "./src/status/status-verbs.ts"
|
|
30
31
|
},
|
|
31
32
|
"files": [
|
|
32
33
|
"bin",
|
|
@@ -38,7 +39,7 @@
|
|
|
38
39
|
],
|
|
39
40
|
"scripts": {
|
|
40
41
|
"start": "bun bin/harness.ts",
|
|
41
|
-
"test": "bun test src/browser src/decisions src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/memory src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts desktop/src/tool-label.test.ts desktop/src/reply-sources.test.ts desktop/src/pipeline.test.ts desktop/src/preview-render.test.ts desktop/src/session-search.test.ts desktop/src/session-select.test.ts",
|
|
42
|
+
"test": "bun test src/status src/browser src/decisions src/core src/tools src/skills src/evals src/cli src/observability src/desktop src/integrations src/media src/memory src/init.test.ts src/runtime.test.ts desktop/src/rich-text.test.ts desktop/src/stream.test.ts desktop/src/dictation.test.ts desktop/src/thought.test.ts desktop/src/queue.test.ts desktop/src/composer-files.test.ts desktop/src/tool-label.test.ts desktop/src/reply-sources.test.ts desktop/src/pipeline.test.ts desktop/src/preview-render.test.ts desktop/src/session-search.test.ts desktop/src/session-select.test.ts",
|
|
42
43
|
"typecheck": "bunx tsc --noEmit -p tsconfig.json",
|
|
43
44
|
"lint": "biome ci .",
|
|
44
45
|
"format": "biome format --write .",
|
|
@@ -66,7 +67,9 @@
|
|
|
66
67
|
"@langfuse/client": "^5.11.1",
|
|
67
68
|
"@langfuse/otel": "^5.11.1",
|
|
68
69
|
"@langfuse/tracing": "^5.11.1",
|
|
69
|
-
"@opentelemetry/
|
|
70
|
+
"@opentelemetry/exporter-trace-otlp-http": ">=0.202.0 <0.300.0",
|
|
71
|
+
"@opentelemetry/otlp-exporter-base": ">=0.202.0 <0.300.0",
|
|
72
|
+
"@opentelemetry/sdk-node": ">=0.202.0 <0.300.0"
|
|
70
73
|
},
|
|
71
74
|
"devDependencies": {
|
|
72
75
|
"@biomejs/biome": "^2.5.2",
|
package/src/cli/tui-progress.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { statusVerbAt } from "../status/status-verbs.ts";
|
|
1
2
|
import { clipLabel } from "./tui-layout.ts";
|
|
2
3
|
import type { TurnToolLine } from "./tui-stream.ts";
|
|
3
4
|
|
|
@@ -5,7 +6,15 @@ export const WARMUP_PHRASES = ["Thinking", "Looking this over", "Working it out"
|
|
|
5
6
|
|
|
6
7
|
const TICK_FRAMES = ["", ".", "..", "..."] as const;
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
/** Progress ticks a verb stays up before the next one. A tick is 450 ms, so about 3 seconds. */
|
|
10
|
+
const TICKS_PER_VERB = 7;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What to show while the agent is thinking. With the turn's verbs it walks through them; without
|
|
14
|
+
* (verbs turned off, or the event has not arrived) it is one of the plain phrases.
|
|
15
|
+
*/
|
|
16
|
+
export function warmupHeadline(seed: number, verbs: readonly string[] = [], tick = 0): string {
|
|
17
|
+
if (verbs.length > 0) return statusVerbAt(verbs, tick, TICKS_PER_VERB);
|
|
9
18
|
return WARMUP_PHRASES[Math.abs(seed) % WARMUP_PHRASES.length] ?? "Thinking";
|
|
10
19
|
}
|
|
11
20
|
|
|
@@ -37,6 +46,8 @@ export function turnProgressLabel(input: {
|
|
|
37
46
|
assistantStarted: boolean;
|
|
38
47
|
tick: number;
|
|
39
48
|
warmupSeed: number;
|
|
49
|
+
/** The turn's verbs from its `status` event. */
|
|
50
|
+
verbs?: readonly string[];
|
|
40
51
|
}): string {
|
|
41
52
|
if (input.assistantStarted) {
|
|
42
53
|
const frame = TICK_FRAMES[input.tick % TICK_FRAMES.length] ?? "";
|
|
@@ -47,9 +58,10 @@ export function turnProgressLabel(input: {
|
|
|
47
58
|
const frame = TICK_FRAMES[input.tick % TICK_FRAMES.length] ?? "";
|
|
48
59
|
return `${toolActivityLabel(running)}${frame}`;
|
|
49
60
|
}
|
|
61
|
+
const headline = warmupHeadline(input.warmupSeed, input.verbs, input.tick);
|
|
50
62
|
if (input.tools.length > 0) {
|
|
51
|
-
return `${
|
|
63
|
+
return `${headline}…`;
|
|
52
64
|
}
|
|
53
65
|
const frame = TICK_FRAMES[input.tick % TICK_FRAMES.length] ?? "";
|
|
54
|
-
return `${
|
|
66
|
+
return `${headline}${frame}`;
|
|
55
67
|
}
|
package/src/cli/tui.tsx
CHANGED
|
@@ -95,6 +95,7 @@ function applyEvent(lines: StreamLine[], event: AgentEvent): StreamLine[] {
|
|
|
95
95
|
case "usage":
|
|
96
96
|
case "completion":
|
|
97
97
|
case "approval_request":
|
|
98
|
+
case "status":
|
|
98
99
|
return lines;
|
|
99
100
|
}
|
|
100
101
|
}
|
|
@@ -656,6 +657,7 @@ function App(props: Readonly<{ harness: HarnessRuntime; theme: Theme }>): React.
|
|
|
656
657
|
const [lines, setLines] = useState<StreamLine[]>([]);
|
|
657
658
|
const [turnTools, setTurnTools] = useState<TurnToolLine[]>([]);
|
|
658
659
|
const [progressTick, setProgressTick] = useState(0);
|
|
660
|
+
const [turnVerbs, setTurnVerbs] = useState<string[]>([]);
|
|
659
661
|
const [value, setValue] = useState("");
|
|
660
662
|
const [status, setStatus] = useState<UiStatus>("idle");
|
|
661
663
|
const [title, setTitle] = useState("New chat");
|
|
@@ -892,6 +894,10 @@ function App(props: Readonly<{ harness: HarnessRuntime; theme: Theme }>): React.
|
|
|
892
894
|
trimmed,
|
|
893
895
|
(event) => {
|
|
894
896
|
if (event.kind === "session_meta") setTitle(event.title);
|
|
897
|
+
if (event.kind === "status") {
|
|
898
|
+
setTurnVerbs(event.verbs);
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
895
901
|
if (event.kind === "usage") setSpend(harness.spend);
|
|
896
902
|
if (event.kind === "completion") {
|
|
897
903
|
setTurnTools((tools) => {
|
|
@@ -960,6 +966,7 @@ function App(props: Readonly<{ harness: HarnessRuntime; theme: Theme }>): React.
|
|
|
960
966
|
assistantStarted,
|
|
961
967
|
tick: progressTick,
|
|
962
968
|
warmupSeed,
|
|
969
|
+
verbs: turnVerbs,
|
|
963
970
|
});
|
|
964
971
|
const showProgress = status === "running";
|
|
965
972
|
const chrome = tuiChromeRows({
|
package/src/config.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { ExecApprovalPolicy } from "./core/approval.ts";
|
|
|
7
7
|
import type { HookConfig } from "./core/hooks.ts";
|
|
8
8
|
import type { AgentMode } from "./core/mode.ts";
|
|
9
9
|
import type { HarnessDecisionsConfig } from "./decisions/config.ts";
|
|
10
|
+
import type { StatusVerbsConfig } from "./status/status-verbs.ts";
|
|
10
11
|
|
|
11
12
|
export interface ExtraMcpServerConfig {
|
|
12
13
|
command: string;
|
|
@@ -24,10 +25,38 @@ export interface HarnessConfig {
|
|
|
24
25
|
tools: { exec: { approval: ExecApprovalPolicy } };
|
|
25
26
|
mcp: ExtraMcpServerConfig[];
|
|
26
27
|
openrouterBaseUrl?: string;
|
|
27
|
-
subagents?: {
|
|
28
|
+
subagents?: {
|
|
29
|
+
enabled?: boolean;
|
|
30
|
+
/** Background agents (spawn_agent / await_agents). On unless this is false. */
|
|
31
|
+
background?: boolean;
|
|
32
|
+
/** Model for subagents. Defaults to the chat model. HARNESS_SUBAGENT_MODEL overrides it. */
|
|
33
|
+
model?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Model for read-only explore agents. A small fast one makes search fan-out quick and cheap.
|
|
36
|
+
* Defaults to `model`. HARNESS_EXPLORE_MODEL overrides it.
|
|
37
|
+
*/
|
|
38
|
+
exploreModel?: string;
|
|
39
|
+
/** Background agents running at once (default 4). */
|
|
40
|
+
maxConcurrent?: number;
|
|
41
|
+
/** Background agents one turn may start (default 12). */
|
|
42
|
+
maxPerTurn?: number;
|
|
43
|
+
};
|
|
28
44
|
observability?: { enabled?: boolean };
|
|
29
45
|
/** Cross-session memory. Off unless this is true or ~/.harness/memory.json enables it. */
|
|
30
|
-
memory?: {
|
|
46
|
+
memory?: {
|
|
47
|
+
enabled?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Semantic recall. Fact text is sent to the embeddings endpoint of the OpenRouter base URL,
|
|
50
|
+
* so this is off unless enabled here or HARNESS_MEMORY_EMBEDDINGS names a model.
|
|
51
|
+
*/
|
|
52
|
+
embeddings?: { enabled?: boolean; model?: string };
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* The verbs shown while the agent is thinking ("Pondering", "Brewing"). The built-in list is
|
|
56
|
+
* on by default; add themed `categories` or your own `custom` ones, or set `enabled: false`
|
|
57
|
+
* for a plain "Thinking".
|
|
58
|
+
*/
|
|
59
|
+
statusVerbs?: StatusVerbsConfig;
|
|
31
60
|
/** Default agent. ask = read only. plan = read + todos. */
|
|
32
61
|
mode?: AgentMode;
|
|
33
62
|
hooks?: HookConfig[];
|
package/src/core/events.ts
CHANGED
|
@@ -23,6 +23,11 @@ export type AgentEvent =
|
|
|
23
23
|
reason?: string;
|
|
24
24
|
}
|
|
25
25
|
| { kind: "session_meta"; sessionId: string; title: string }
|
|
26
|
+
/**
|
|
27
|
+
* Sent once at the start of a turn: the verbs a UI rotates through while the agent is thinking
|
|
28
|
+
* ("Pondering", "Brewing"). A UI that ignores it shows its own plain label.
|
|
29
|
+
*/
|
|
30
|
+
| { kind: "status"; verbs: string[] }
|
|
26
31
|
| {
|
|
27
32
|
kind: "usage";
|
|
28
33
|
promptTokens: number;
|
package/src/core/mode.ts
CHANGED
|
@@ -11,6 +11,11 @@ const READ_TOOLS = new Set([
|
|
|
11
11
|
"git_status",
|
|
12
12
|
"git_diff",
|
|
13
13
|
"git_log",
|
|
14
|
+
"memory_search",
|
|
15
|
+
// Background agents are limited to read-only explorers outside agent mode.
|
|
16
|
+
"spawn_agent",
|
|
17
|
+
"await_agents",
|
|
18
|
+
"cancel_agent",
|
|
14
19
|
]);
|
|
15
20
|
|
|
16
21
|
const PLAN_TOOLS = new Set([...READ_TOOLS, "todo_write"]);
|
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";
|
|
@@ -104,6 +105,11 @@ export interface RunTurnDeps {
|
|
|
104
105
|
shortcut?: ShortcutPlanner;
|
|
105
106
|
/** Host handler that can answer a whole turn without the chat model. */
|
|
106
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 };
|
|
107
113
|
}
|
|
108
114
|
|
|
109
115
|
export async function runTurn(
|
|
@@ -139,6 +145,11 @@ export async function runTurn(
|
|
|
139
145
|
session = undefined;
|
|
140
146
|
}
|
|
141
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
|
+
|
|
142
153
|
const obs = deps.observability ?? noopObservability;
|
|
143
154
|
const startedAt = Date.now();
|
|
144
155
|
return obs.startTurn(
|
package/src/index.ts
CHANGED
|
@@ -151,7 +151,42 @@ export { connectMcp } from "./integrations/connect.ts";
|
|
|
151
151
|
export { withOAuthLoopback } from "./integrations/loopback.ts";
|
|
152
152
|
export { openRemoteMcp } from "./integrations/remote-mcp.ts";
|
|
153
153
|
export { listStoredConnections } from "./integrations/store.ts";
|
|
154
|
-
export {
|
|
154
|
+
export {
|
|
155
|
+
DEFAULT_BRIEF_WORDS,
|
|
156
|
+
formatMemoryBriefs,
|
|
157
|
+
memoryBriefSystem,
|
|
158
|
+
synthesizeMemoryBrief,
|
|
159
|
+
} from "./memory/brief.ts";
|
|
160
|
+
export {
|
|
161
|
+
cosineSimilarity,
|
|
162
|
+
createOpenAICompatEmbedder,
|
|
163
|
+
DEFAULT_EMBEDDING_MODEL,
|
|
164
|
+
type Embedder,
|
|
165
|
+
fuseRankings,
|
|
166
|
+
} from "./memory/embeddings.ts";
|
|
167
|
+
export {
|
|
168
|
+
extractMemories,
|
|
169
|
+
MEMORY_EXTRACT_SYSTEM,
|
|
170
|
+
parseExtractedFacts,
|
|
171
|
+
turnMemorySource,
|
|
172
|
+
} from "./memory/extract.ts";
|
|
173
|
+
export {
|
|
174
|
+
createLayeredMemoryStore,
|
|
175
|
+
type LayeredMemoryStore,
|
|
176
|
+
type MemoryLayer,
|
|
177
|
+
} from "./memory/layered.ts";
|
|
178
|
+
export {
|
|
179
|
+
type CreateMemoryStoreOptions,
|
|
180
|
+
createFileMemoryBackend,
|
|
181
|
+
createFileMemoryStore,
|
|
182
|
+
createInMemoryMemoryBackend,
|
|
183
|
+
createMemoryStore,
|
|
184
|
+
type MemoryBackend,
|
|
185
|
+
type MemoryEmbeddingRow,
|
|
186
|
+
type MemoryRecord,
|
|
187
|
+
type MemoryStore,
|
|
188
|
+
type NewMemoryFact,
|
|
189
|
+
} from "./memory/memory-store.ts";
|
|
155
190
|
export { isMemoryEnabled, readMemoryPrefs, writeMemoryPrefs } from "./memory/prefs.ts";
|
|
156
191
|
export { formatMemoryList, formatRetrievedMemory } from "./memory/prompt.ts";
|
|
157
192
|
export {
|
|
@@ -161,6 +196,8 @@ export {
|
|
|
161
196
|
type MemoryFact,
|
|
162
197
|
type MemoryScope,
|
|
163
198
|
pinFact,
|
|
199
|
+
prepareFacts,
|
|
200
|
+
rankFacts,
|
|
164
201
|
searchFacts,
|
|
165
202
|
unpinFact,
|
|
166
203
|
} from "./memory/store.ts";
|
|
@@ -242,8 +279,35 @@ export {
|
|
|
242
279
|
} from "./skills/registry.ts";
|
|
243
280
|
export { parseSkillCommand, SKILL_COMMAND_USAGE, SKILL_FIND_HINT } from "./skills/skill-command.ts";
|
|
244
281
|
export { userSkillsDir } from "./skills/user-dir.ts";
|
|
282
|
+
export {
|
|
283
|
+
resolveStatusVerbPool,
|
|
284
|
+
statusVerbCategories,
|
|
285
|
+
statusVerbCategoryNames,
|
|
286
|
+
} from "./status/categories.ts";
|
|
287
|
+
export {
|
|
288
|
+
DEFAULT_STATUS_VERBS,
|
|
289
|
+
DEFAULT_STATUS_VERBS_PER_TURN,
|
|
290
|
+
FALLBACK_STATUS_VERB,
|
|
291
|
+
pickStatusVerbs,
|
|
292
|
+
type StatusVerbsConfig,
|
|
293
|
+
seededRandom,
|
|
294
|
+
statusVerbAt,
|
|
295
|
+
} from "./status/status-verbs.ts";
|
|
296
|
+
export {
|
|
297
|
+
BACKGROUND_AGENTS_PROMPT,
|
|
298
|
+
type BackgroundAgentRunInput,
|
|
299
|
+
type BackgroundAgentSnapshot,
|
|
300
|
+
type BackgroundAgentStatus,
|
|
301
|
+
type BackgroundAgents,
|
|
302
|
+
type BackgroundAgentsOptions,
|
|
303
|
+
createBackgroundAgents,
|
|
304
|
+
EXPLORE_INSTRUCTIONS,
|
|
305
|
+
readOnlyTools,
|
|
306
|
+
type SubagentKind,
|
|
307
|
+
} from "./tools/background.ts";
|
|
245
308
|
export { createGitTools } from "./tools/git.ts";
|
|
246
309
|
export { createLocalTools } from "./tools/local.ts";
|
|
310
|
+
export { createMemoryTools } from "./tools/memory.ts";
|
|
247
311
|
export { PathEscapeError, resolveUnderCwd } from "./tools/paths.ts";
|
|
248
312
|
export { createReadSkillTool } from "./tools/read-skill.ts";
|
|
249
313
|
export { createTaskTool } from "./tools/subagent.ts";
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { MainModelProvider } from "../core/events.ts";
|
|
2
|
+
import type { MemoryFact } from "./store.ts";
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_BRIEF_WORDS = 180;
|
|
5
|
+
/** Facts handed to the model for one brief. The newest are kept when there are more. */
|
|
6
|
+
export const MAX_BRIEF_FACTS = 200;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The system prompt that turns a pile of remembered facts into one short brief. A brief is what
|
|
10
|
+
* a new chat, or a new project in the same workspace, starts from.
|
|
11
|
+
*/
|
|
12
|
+
export function memoryBriefSystem(subject: string, maxWords = DEFAULT_BRIEF_WORDS): string {
|
|
13
|
+
return [
|
|
14
|
+
`Write a short brief of what is known about ${subject}, from the remembered facts below.`,
|
|
15
|
+
"The facts are listed oldest first. When two disagree, the later one is right; leave the earlier one out.",
|
|
16
|
+
"Group related points and say each thing once. Use plain sentences or short bullets.",
|
|
17
|
+
"Use only what the facts say. Do not add advice, guesses, or anything they do not state.",
|
|
18
|
+
`Stay under ${maxWords} words. Reply with the brief only, no heading and no preamble.`,
|
|
19
|
+
].join(" ");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Consolidate facts into a brief with one model call. Returns an empty string when there are no
|
|
24
|
+
* facts or the model fails, so the caller keeps whatever brief it already had.
|
|
25
|
+
*/
|
|
26
|
+
export async function synthesizeMemoryBrief(input: {
|
|
27
|
+
facts: readonly MemoryFact[];
|
|
28
|
+
provider: MainModelProvider;
|
|
29
|
+
/** What the facts are about: "this project", "the Acme workspace". */
|
|
30
|
+
subject: string;
|
|
31
|
+
maxWords?: number;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}): Promise<string> {
|
|
34
|
+
const facts = input.facts.slice(-MAX_BRIEF_FACTS);
|
|
35
|
+
if (facts.length === 0) return "";
|
|
36
|
+
const maxWords = input.maxWords ?? DEFAULT_BRIEF_WORDS;
|
|
37
|
+
let raw = "";
|
|
38
|
+
for await (const event of input.provider.stream(
|
|
39
|
+
{
|
|
40
|
+
system: memoryBriefSystem(input.subject, maxWords),
|
|
41
|
+
messages: [{ role: "user", content: facts.map((fact) => `- ${fact.text}`).join("\n") }],
|
|
42
|
+
maxTokens: Math.ceil(maxWords * 2.5),
|
|
43
|
+
},
|
|
44
|
+
input.signal ? { signal: input.signal } : undefined,
|
|
45
|
+
)) {
|
|
46
|
+
if (event.type === "text_delta") raw += event.text;
|
|
47
|
+
if (event.type === "error") return "";
|
|
48
|
+
}
|
|
49
|
+
const words = raw.trim().split(/\s+/).filter(Boolean);
|
|
50
|
+
// A model that ignores the limit is cut rather than trusted with the whole prompt budget.
|
|
51
|
+
if (words.length > maxWords * 1.5)
|
|
52
|
+
return `${words.slice(0, Math.floor(maxWords * 1.5)).join(" ")} …`;
|
|
53
|
+
return raw.trim();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The briefs as system-prompt sections, widest first so the narrower one has the last word. */
|
|
57
|
+
export function formatMemoryBriefs(briefs: ReadonlyArray<{ title: string; text: string }>): string {
|
|
58
|
+
return briefs
|
|
59
|
+
.filter((brief) => brief.text.trim())
|
|
60
|
+
.map((brief) => `### ${brief.title}\n${brief.text.trim()}`)
|
|
61
|
+
.join("\n\n");
|
|
62
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
|
|
2
|
+
import { PRODUCT_NAME } from "../product.ts";
|
|
3
|
+
|
|
4
|
+
/** Turns text into vectors. One vector per input, in the same order. */
|
|
5
|
+
export interface Embedder {
|
|
6
|
+
/** Names the vector space. Vectors from two models are never compared. */
|
|
7
|
+
readonly model: string;
|
|
8
|
+
embed(texts: string[]): Promise<number[][]>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
|
|
12
|
+
|
|
13
|
+
const EMBED_BATCH = 96;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* An embedder for any OpenAI-compatible `/embeddings` endpoint. OpenRouter is the default.
|
|
17
|
+
* The texts are sent to that provider, so a host turns this on deliberately.
|
|
18
|
+
*/
|
|
19
|
+
export function createOpenAICompatEmbedder(options: {
|
|
20
|
+
apiKey: string | (() => string);
|
|
21
|
+
baseUrl?: string;
|
|
22
|
+
model?: string;
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
}): Embedder {
|
|
25
|
+
const baseUrl = (options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
26
|
+
const model = options.model?.trim() || DEFAULT_EMBEDDING_MODEL;
|
|
27
|
+
const doFetch = options.fetch ?? fetch;
|
|
28
|
+
const embedBatch = async (texts: string[]): Promise<number[][]> => {
|
|
29
|
+
const apiKey = typeof options.apiKey === "function" ? options.apiKey() : options.apiKey;
|
|
30
|
+
if (!apiKey.trim()) throw new Error("No API key for embeddings.");
|
|
31
|
+
const res = await doFetch(`${baseUrl}/embeddings`, {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: {
|
|
34
|
+
Authorization: `Bearer ${apiKey}`,
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
"HTTP-Referer": "https://caelence.com",
|
|
37
|
+
"X-Title": `${PRODUCT_NAME} memory`,
|
|
38
|
+
},
|
|
39
|
+
body: JSON.stringify({ model, input: texts }),
|
|
40
|
+
});
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
const body = await res.text();
|
|
43
|
+
throw new Error(`Embeddings ${res.status}: ${body.slice(0, 300)}`);
|
|
44
|
+
}
|
|
45
|
+
const json = (await res.json()) as {
|
|
46
|
+
data?: Array<{ index?: number; embedding?: unknown }>;
|
|
47
|
+
};
|
|
48
|
+
const rows = json.data ?? [];
|
|
49
|
+
const out: number[][] = new Array(texts.length);
|
|
50
|
+
rows.forEach((row, position) => {
|
|
51
|
+
const index = typeof row.index === "number" ? row.index : position;
|
|
52
|
+
if (Array.isArray(row.embedding) && index >= 0 && index < texts.length) {
|
|
53
|
+
out[index] = row.embedding as number[];
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
57
|
+
if (!Array.isArray(out[i])) throw new Error("Embeddings reply was missing a vector.");
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
model,
|
|
63
|
+
async embed(texts) {
|
|
64
|
+
const out: number[][] = [];
|
|
65
|
+
for (let i = 0; i < texts.length; i += EMBED_BATCH) {
|
|
66
|
+
out.push(...(await embedBatch(texts.slice(i, i + EMBED_BATCH))));
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function cosineSimilarity(a: readonly number[], b: readonly number[]): number {
|
|
74
|
+
if (a.length === 0 || a.length !== b.length) return 0;
|
|
75
|
+
let dot = 0;
|
|
76
|
+
let normA = 0;
|
|
77
|
+
let normB = 0;
|
|
78
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
79
|
+
const x = a[i] ?? 0;
|
|
80
|
+
const y = b[i] ?? 0;
|
|
81
|
+
dot += x * y;
|
|
82
|
+
normA += x * x;
|
|
83
|
+
normB += y * y;
|
|
84
|
+
}
|
|
85
|
+
if (normA === 0 || normB === 0) return 0;
|
|
86
|
+
return dot / Math.sqrt(normA * normB);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Merge ranked lists into one. An item's score is the sum of 1 / (k + rank) over the lists it
|
|
91
|
+
* appears in, so something both lists like beats something one list loves.
|
|
92
|
+
*/
|
|
93
|
+
export function fuseRankings<T>(lists: T[][], keyOf: (item: T) => string, k = 60): T[] {
|
|
94
|
+
const scores = new Map<string, { item: T; score: number }>();
|
|
95
|
+
for (const list of lists) {
|
|
96
|
+
list.forEach((item, rank) => {
|
|
97
|
+
const key = keyOf(item);
|
|
98
|
+
const row = scores.get(key) ?? { item, score: 0 };
|
|
99
|
+
row.score += 1 / (k + rank + 1);
|
|
100
|
+
scores.set(key, row);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return [...scores.values()].sort((a, b) => b.score - a.score).map((row) => row.item);
|
|
104
|
+
}
|
package/src/memory/extract.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { MainModelProvider } from "../core/events.ts";
|
|
2
2
|
import type { Session } from "../core/session.ts";
|
|
3
|
+
import type { MemoryStore } from "./memory-store.ts";
|
|
3
4
|
import { addFacts, type MemoryScope } from "./store.ts";
|
|
4
5
|
|
|
5
6
|
export const MEMORY_EXTRACT_SYSTEM = [
|
|
@@ -65,6 +66,8 @@ export async function extractMemories(input: {
|
|
|
65
66
|
session: Session;
|
|
66
67
|
provider: MainModelProvider;
|
|
67
68
|
env?: Record<string, string | undefined>;
|
|
69
|
+
/** Where to keep the facts. Defaults to the facts files under `cwd` and the harness home. */
|
|
70
|
+
store?: MemoryStore;
|
|
68
71
|
}): Promise<number> {
|
|
69
72
|
const source = turnMemorySource(input.session);
|
|
70
73
|
if (!source.trim()) return 0;
|
|
@@ -77,12 +80,10 @@ export async function extractMemories(input: {
|
|
|
77
80
|
if (event.type === "text_delta") raw += event.text;
|
|
78
81
|
if (event.type === "error") return 0;
|
|
79
82
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
input.env,
|
|
87
|
-
).length;
|
|
83
|
+
const facts = parseExtractedFacts(raw).map((fact) => ({
|
|
84
|
+
...fact,
|
|
85
|
+
sessionId: input.session.id,
|
|
86
|
+
}));
|
|
87
|
+
if (input.store) return (await input.store.add(facts)).length;
|
|
88
|
+
return addFacts(input.cwd, facts, input.env).length;
|
|
88
89
|
}
|