@useavalon/caelence-agent 0.1.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 +201 -0
- package/bin/harness.ts +10 -0
- package/package.json +75 -0
- package/skills/copy-editor/SKILL.md +74 -0
- package/skills/copy-editor/references/anti-slop.md +62 -0
- package/skills/copy-editor/references/ui-states.md +46 -0
- package/skills/copy-editor/scripts/lint-copy.py +78 -0
- package/skills/copy-harry-dry/SKILL.md +120 -0
- package/skills/copy-rmbc/SKILL.md +97 -0
- package/skills/copywriting/SKILL.md +73 -0
- package/skills/impeccable/SKILL.md +133 -0
- package/skills/impeccable/references/visual-slop.md +36 -0
- package/src/cli/main.test.ts +36 -0
- package/src/cli/main.ts +384 -0
- package/src/cli/media-models.ts +82 -0
- package/src/cli/models.ts +43 -0
- package/src/cli/openrouter-live.test.ts +35 -0
- package/src/cli/openrouter-live.ts +72 -0
- package/src/cli/openrouter-modality.test.ts +25 -0
- package/src/cli/openrouter-modality.ts +83 -0
- package/src/cli/picker.test.ts +53 -0
- package/src/cli/picker.ts +48 -0
- package/src/cli/plain-text.ts +15 -0
- package/src/cli/slash-dispatch.test.ts +213 -0
- package/src/cli/slash-dispatch.ts +298 -0
- package/src/cli/slash.test.ts +113 -0
- package/src/cli/slash.ts +119 -0
- package/src/cli/theme.test.ts +10 -0
- package/src/cli/theme.ts +44 -0
- package/src/cli/tui-layout.test.ts +33 -0
- package/src/cli/tui-layout.ts +33 -0
- package/src/cli/tui-screen.test.ts +33 -0
- package/src/cli/tui-screen.ts +13 -0
- package/src/cli/tui.tsx +735 -0
- package/src/config.ts +86 -0
- package/src/core/approval.test.ts +60 -0
- package/src/core/approval.ts +83 -0
- package/src/core/auto-router.test.ts +31 -0
- package/src/core/auto-router.ts +66 -0
- package/src/core/errors.ts +67 -0
- package/src/core/events.ts +85 -0
- package/src/core/hooks.test.ts +66 -0
- package/src/core/hooks.ts +94 -0
- package/src/core/ids.ts +6 -0
- package/src/core/instructions.test.ts +49 -0
- package/src/core/instructions.ts +44 -0
- package/src/core/logger.ts +45 -0
- package/src/core/mcp.ts +191 -0
- package/src/core/mode.test.ts +63 -0
- package/src/core/mode.ts +60 -0
- package/src/core/run-turn.test.ts +339 -0
- package/src/core/run-turn.ts +487 -0
- package/src/core/session.test.ts +203 -0
- package/src/core/session.ts +349 -0
- package/src/core/stdio-mcp.ts +143 -0
- package/src/core/strands.ts +262 -0
- package/src/core/usage.test.ts +69 -0
- package/src/core/usage.ts +171 -0
- package/src/desktop/bridge.test.ts +331 -0
- package/src/desktop/bridge.ts +729 -0
- package/src/desktop/open-local.test.ts +40 -0
- package/src/desktop/open-local.ts +52 -0
- package/src/desktop/preview-cache.test.ts +36 -0
- package/src/desktop/preview-cache.ts +63 -0
- package/src/desktop/secrets.test.ts +44 -0
- package/src/desktop/secrets.ts +60 -0
- package/src/evals/runner.test.ts +43 -0
- package/src/evals/runner.ts +225 -0
- package/src/index.ts +132 -0
- package/src/init.test.ts +54 -0
- package/src/init.ts +117 -0
- package/src/integrations/catalog-data.json +424 -0
- package/src/integrations/catalog.ts +81 -0
- package/src/integrations/connect.ts +231 -0
- package/src/integrations/integrations.test.ts +329 -0
- package/src/integrations/marks/airtable.svg +1 -0
- package/src/integrations/marks/algolia-mcp.svg +1 -0
- package/src/integrations/marks/canva.jpg +0 -0
- package/src/integrations/marks/cloudflare-mcp.svg +1 -0
- package/src/integrations/marks/contentful-mcp.svg +1 -0
- package/src/integrations/marks/craft.png +0 -0
- package/src/integrations/marks/dinero.png +0 -0
- package/src/integrations/marks/figma.svg +1 -0
- package/src/integrations/marks/gitlab.svg +1 -0
- package/src/integrations/marks/google-calendar.svg +1 -0
- package/src/integrations/marks/google-docs.svg +1 -0
- package/src/integrations/marks/google-drive.svg +1 -0
- package/src/integrations/marks/google-gmail.svg +1 -0
- package/src/integrations/marks/google-sheets.svg +1 -0
- package/src/integrations/marks/google-slides.svg +1 -0
- package/src/integrations/marks/granola.png +0 -0
- package/src/integrations/marks/jira.svg +1 -0
- package/src/integrations/marks/linear.svg +1 -0
- package/src/integrations/marks/microsoft-365.svg +7 -0
- package/src/integrations/marks/miro.svg +1 -0
- package/src/integrations/marks/mixpanel-mcp.svg +1 -0
- package/src/integrations/marks/monday.png +0 -0
- package/src/integrations/marks/mux-mcp.png +0 -0
- package/src/integrations/marks/neon-mcp.svg +1 -0
- package/src/integrations/marks/notion.svg +1 -0
- package/src/integrations/marks/paddle-mcp.svg +1 -0
- package/src/integrations/marks/posthog-mcp.svg +1 -0
- package/src/integrations/marks/prismic-mcp.svg +1 -0
- package/src/integrations/marks/replicate-mcp.svg +1 -0
- package/src/integrations/marks/resend-mcp.svg +1 -0
- package/src/integrations/marks/sanity-mcp.svg +1 -0
- package/src/integrations/marks/sceneplane.png +0 -0
- package/src/integrations/marks/sentry-mcp.svg +1 -0
- package/src/integrations/marks/stripe-mcp.svg +1 -0
- package/src/integrations/marks/supabase-mcp.svg +1 -0
- package/src/integrations/marks/upstash-mcp.svg +1 -0
- package/src/integrations/marks/vercel.svg +1 -0
- package/src/integrations/marks/webflow.svg +1 -0
- package/src/integrations/mcp-oauth.test.ts +39 -0
- package/src/integrations/mcp-oauth.ts +330 -0
- package/src/integrations/oauth-clients.test.ts +77 -0
- package/src/integrations/oauth-clients.ts +127 -0
- package/src/integrations/oauth.ts +145 -0
- package/src/integrations/remote-mcp.ts +307 -0
- package/src/integrations/store.ts +149 -0
- package/src/media/openrouter-generate.test.ts +80 -0
- package/src/media/openrouter-generate.ts +178 -0
- package/src/media/prefs.ts +54 -0
- package/src/observability/categories.ts +41 -0
- package/src/observability/create.test.ts +56 -0
- package/src/observability/create.ts +45 -0
- package/src/observability/experiments.ts +113 -0
- package/src/observability/fake.ts +191 -0
- package/src/observability/index.ts +57 -0
- package/src/observability/judges.ts +91 -0
- package/src/observability/langfuse.ts +275 -0
- package/src/observability/noop.ts +33 -0
- package/src/observability/observability.test.ts +113 -0
- package/src/observability/prompts.ts +98 -0
- package/src/observability/regression-items.ts +158 -0
- package/src/observability/sanitize.test.ts +26 -0
- package/src/observability/sanitize.ts +57 -0
- package/src/observability/types.ts +122 -0
- package/src/observability/version.ts +41 -0
- package/src/product.ts +2 -0
- package/src/runtime.test.ts +98 -0
- package/src/runtime.ts +438 -0
- package/src/skills/author-skill.ts +49 -0
- package/src/skills/create-skill.test.ts +108 -0
- package/src/skills/create-skill.ts +70 -0
- package/src/skills/loader.test.ts +122 -0
- package/src/skills/loader.ts +162 -0
- package/src/skills/registry.test.ts +190 -0
- package/src/skills/registry.ts +402 -0
- package/src/skills/skill-command.ts +53 -0
- package/src/skills/user-dir.ts +8 -0
- package/src/tools/git.test.ts +71 -0
- package/src/tools/git.ts +126 -0
- package/src/tools/local.ts +258 -0
- package/src/tools/paths.test.ts +24 -0
- package/src/tools/paths.ts +39 -0
- package/src/tools/read-skill.ts +43 -0
- package/src/tools/subagent.test.ts +77 -0
- package/src/tools/subagent.ts +74 -0
- package/src/tools/todo.test.ts +25 -0
- package/src/tools/todo.ts +70 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import { noopObservability } from "../observability/noop.ts";
|
|
2
|
+
import { sanitize } from "../observability/sanitize.ts";
|
|
3
|
+
import type { Observability } from "../observability/types.ts";
|
|
4
|
+
import type { ApprovalGate } from "./approval.ts";
|
|
5
|
+
import { isRiskyToolCall } from "./approval.ts";
|
|
6
|
+
import { errorMessage, isAbortError } from "./errors.ts";
|
|
7
|
+
import type { AgentEventEmitter, MainModelProvider } from "./events.ts";
|
|
8
|
+
import type { HookRunner } from "./hooks.ts";
|
|
9
|
+
import { newId } from "./ids.ts";
|
|
10
|
+
import {
|
|
11
|
+
errorResult,
|
|
12
|
+
type McpServer,
|
|
13
|
+
type McpToolDefinition,
|
|
14
|
+
type ToolResult,
|
|
15
|
+
toolResultText,
|
|
16
|
+
} from "./mcp.ts";
|
|
17
|
+
import type { AgentMode } from "./mode.ts";
|
|
18
|
+
import { modePrompt } from "./mode.ts";
|
|
19
|
+
import {
|
|
20
|
+
compactionSummaries,
|
|
21
|
+
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
22
|
+
replaceUserTurn,
|
|
23
|
+
type Session,
|
|
24
|
+
type SessionMessage,
|
|
25
|
+
type SessionStore,
|
|
26
|
+
type SummarizerFn,
|
|
27
|
+
sessionToProviderMessages,
|
|
28
|
+
titleFromUserMessage,
|
|
29
|
+
} from "./session.ts";
|
|
30
|
+
import type { AgentTool, ConstructAgent, ConstructedAgent } from "./strands.ts";
|
|
31
|
+
|
|
32
|
+
const REJECTED_TOOL_MESSAGE = "was denied approval and was not invoked";
|
|
33
|
+
|
|
34
|
+
export interface TurnRequest {
|
|
35
|
+
message: string;
|
|
36
|
+
sessionId?: string;
|
|
37
|
+
model?: string;
|
|
38
|
+
editUserTurn?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RunTurnDeps {
|
|
42
|
+
cwd: string;
|
|
43
|
+
name: string;
|
|
44
|
+
systemPrompt: string;
|
|
45
|
+
tools: McpToolDefinition[];
|
|
46
|
+
mcp?: McpServer;
|
|
47
|
+
approval: ApprovalGate;
|
|
48
|
+
store: SessionStore;
|
|
49
|
+
provider: MainModelProvider;
|
|
50
|
+
constructAgent: ConstructAgent;
|
|
51
|
+
resolveProvider?: (modelId: string) => MainModelProvider;
|
|
52
|
+
summarize?: SummarizerFn;
|
|
53
|
+
contextWindowTokens?: number;
|
|
54
|
+
maxTokens?: number;
|
|
55
|
+
observability?: Observability;
|
|
56
|
+
traceName?: string;
|
|
57
|
+
requestType?: string;
|
|
58
|
+
agentVersion?: string;
|
|
59
|
+
userId?: string;
|
|
60
|
+
hooks?: HookRunner;
|
|
61
|
+
mode?: AgentMode;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function runTurn(
|
|
65
|
+
deps: RunTurnDeps,
|
|
66
|
+
req: TurnRequest,
|
|
67
|
+
emit: AgentEventEmitter,
|
|
68
|
+
options: { signal?: AbortSignal } = {},
|
|
69
|
+
): Promise<Session | undefined> {
|
|
70
|
+
let session: Session | undefined;
|
|
71
|
+
try {
|
|
72
|
+
if (req.sessionId) session = await deps.store.get(req.sessionId);
|
|
73
|
+
if (req.editUserTurn !== undefined) {
|
|
74
|
+
if (!session) throw new Error("No session to edit.");
|
|
75
|
+
session = await deps.store.save(replaceUserTurn(session, req.editUserTurn, req.message));
|
|
76
|
+
} else {
|
|
77
|
+
if (!session) session = await deps.store.create(deps.systemPrompt, req.model);
|
|
78
|
+
session = await deps.store.append(session, {
|
|
79
|
+
kind: "turn",
|
|
80
|
+
role: "user",
|
|
81
|
+
content: req.message,
|
|
82
|
+
});
|
|
83
|
+
if (!session.title || session.title === "New chat") {
|
|
84
|
+
session = await deps.store.setTitle(session, titleFromUserMessage(req.message));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
emit({ kind: "session_meta", sessionId: session.id, title: session.title });
|
|
88
|
+
} catch (err) {
|
|
89
|
+
if (req.editUserTurn !== undefined) {
|
|
90
|
+
emit({ kind: "error", message: errorMessage(err) });
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
session = undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const obs = deps.observability ?? noopObservability;
|
|
97
|
+
const startedAt = Date.now();
|
|
98
|
+
return obs.startTurn(
|
|
99
|
+
{
|
|
100
|
+
name: deps.traceName ?? "agent_turn",
|
|
101
|
+
input: { message: req.message },
|
|
102
|
+
sessionId: session?.id,
|
|
103
|
+
userId: deps.userId,
|
|
104
|
+
metadata: {
|
|
105
|
+
model: req.model ?? deps.provider.modelId,
|
|
106
|
+
agentVersion: deps.agentVersion,
|
|
107
|
+
requestType: deps.requestType ?? "chat",
|
|
108
|
+
mode: deps.mode ?? "agent",
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
async (root) => {
|
|
112
|
+
let assistantText = "";
|
|
113
|
+
let thoughtText = "";
|
|
114
|
+
const openTools = new Map<string, { name: string; preview: string }>();
|
|
115
|
+
let persistChain = Promise.resolve();
|
|
116
|
+
const persistMessage = (message: SessionMessage) => {
|
|
117
|
+
persistChain = persistChain
|
|
118
|
+
.then(async () => {
|
|
119
|
+
if (!session) return;
|
|
120
|
+
session = await deps.store.append(session, message);
|
|
121
|
+
})
|
|
122
|
+
.catch(() => undefined);
|
|
123
|
+
};
|
|
124
|
+
const capture: AgentEventEmitter = (event) => {
|
|
125
|
+
if (event.kind === "text_delta") assistantText += event.text;
|
|
126
|
+
if (event.kind === "reasoning_delta") thoughtText += event.text;
|
|
127
|
+
if (event.kind === "tool_call_start") {
|
|
128
|
+
openTools.set(event.callId, {
|
|
129
|
+
name: event.toolName,
|
|
130
|
+
preview: previewToolInput(event.input),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (event.kind === "tool_call_end") {
|
|
134
|
+
const started = openTools.get(event.callId);
|
|
135
|
+
openTools.delete(event.callId);
|
|
136
|
+
persistMessage({
|
|
137
|
+
kind: "tool",
|
|
138
|
+
name: event.toolName,
|
|
139
|
+
callId: event.callId,
|
|
140
|
+
status: event.success ? "ok" : "fail",
|
|
141
|
+
preview: started?.preview ?? "",
|
|
142
|
+
...(event.error ? { error: event.error } : {}),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
emit(event);
|
|
146
|
+
};
|
|
147
|
+
const closeOpenTools = (reason: string) => {
|
|
148
|
+
for (const [callId, tool] of openTools) {
|
|
149
|
+
capture({
|
|
150
|
+
kind: "tool_call_end",
|
|
151
|
+
toolName: tool.name,
|
|
152
|
+
callId,
|
|
153
|
+
success: false,
|
|
154
|
+
error: reason,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
let history: Array<{ role: "user" | "assistant"; content: string }> = [];
|
|
160
|
+
let systemPrompt = deps.systemPrompt;
|
|
161
|
+
if (session) {
|
|
162
|
+
history = sessionToProviderMessages(session).slice(0, -1);
|
|
163
|
+
const summaries = compactionSummaries(session);
|
|
164
|
+
if (summaries.length > 0) {
|
|
165
|
+
systemPrompt += `\n\n## Earlier conversation (summarized)\n${summaries.join("\n\n")}`;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const toolDefs = deps.mcp ? deps.mcp.listTools() : deps.tools;
|
|
170
|
+
const tools: AgentTool[] = toolDefs.map((def) =>
|
|
171
|
+
guardTool(def, deps.approval, capture, obs, deps.hooks),
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
let agent: ConstructedAgent;
|
|
175
|
+
const provider =
|
|
176
|
+
req.model && deps.resolveProvider ? deps.resolveProvider(req.model) : deps.provider;
|
|
177
|
+
try {
|
|
178
|
+
agent = deps.constructAgent({
|
|
179
|
+
systemPrompt,
|
|
180
|
+
tools,
|
|
181
|
+
provider,
|
|
182
|
+
messages: history,
|
|
183
|
+
maxTokens: deps.maxTokens,
|
|
184
|
+
});
|
|
185
|
+
} catch (err) {
|
|
186
|
+
closeOpenTools("Turn stopped before this tool finished.");
|
|
187
|
+
await persistChain;
|
|
188
|
+
if (session) await finalize(deps, session, assistantText, thoughtText);
|
|
189
|
+
capture({ kind: "error", message: errorMessage(err) });
|
|
190
|
+
root.update({
|
|
191
|
+
level: "ERROR",
|
|
192
|
+
statusMessage: errorMessage(err),
|
|
193
|
+
metadata: { status: "failed", generation_duration: Date.now() - startedAt },
|
|
194
|
+
});
|
|
195
|
+
await obs.flush();
|
|
196
|
+
return session;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
await obs.generation(
|
|
201
|
+
"llm",
|
|
202
|
+
async (gen) => {
|
|
203
|
+
gen.update({ model: provider.modelId, input: { message: req.message } });
|
|
204
|
+
await agent.run(req.message, capture, { signal: options.signal });
|
|
205
|
+
const usage = provider.takeUsage?.();
|
|
206
|
+
gen.update({
|
|
207
|
+
output: assistantText,
|
|
208
|
+
...(usage
|
|
209
|
+
? {
|
|
210
|
+
usage: {
|
|
211
|
+
promptTokens: usage.promptTokens,
|
|
212
|
+
completionTokens: usage.completionTokens,
|
|
213
|
+
totalTokens: usage.totalTokens,
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
: {}),
|
|
217
|
+
});
|
|
218
|
+
if (usage) {
|
|
219
|
+
capture({
|
|
220
|
+
kind: "usage",
|
|
221
|
+
promptTokens: usage.promptTokens,
|
|
222
|
+
completionTokens: usage.completionTokens,
|
|
223
|
+
totalTokens: usage.totalTokens,
|
|
224
|
+
...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),
|
|
225
|
+
});
|
|
226
|
+
if (usage.costUsd !== undefined) {
|
|
227
|
+
obs.score({ name: "cost_usd", value: usage.costUsd });
|
|
228
|
+
}
|
|
229
|
+
obs.score({ name: "prompt_tokens", value: usage.promptTokens });
|
|
230
|
+
obs.score({ name: "completion_tokens", value: usage.completionTokens });
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
{ model: provider.modelId },
|
|
234
|
+
);
|
|
235
|
+
await persistChain;
|
|
236
|
+
if (session) session = await finalize(deps, session, assistantText, thoughtText);
|
|
237
|
+
capture({ kind: "completion" });
|
|
238
|
+
root.update({
|
|
239
|
+
output: assistantText,
|
|
240
|
+
metadata: { status: "success", generation_duration: Date.now() - startedAt },
|
|
241
|
+
});
|
|
242
|
+
obs.score({ name: "generation_duration", value: Date.now() - startedAt });
|
|
243
|
+
} catch (err) {
|
|
244
|
+
closeOpenTools("Turn stopped before this tool finished.");
|
|
245
|
+
await persistChain;
|
|
246
|
+
if (session) session = await finalize(deps, session, assistantText, thoughtText);
|
|
247
|
+
if (options.signal?.aborted || isAbortError(err)) {
|
|
248
|
+
capture({ kind: "completion" });
|
|
249
|
+
root.update({
|
|
250
|
+
metadata: { status: "aborted", generation_duration: Date.now() - startedAt },
|
|
251
|
+
});
|
|
252
|
+
await obs.flush();
|
|
253
|
+
return session;
|
|
254
|
+
}
|
|
255
|
+
capture({ kind: "error", message: errorMessage(err) });
|
|
256
|
+
root.update({
|
|
257
|
+
level: "ERROR",
|
|
258
|
+
statusMessage: errorMessage(err),
|
|
259
|
+
metadata: { status: "failed", generation_duration: Date.now() - startedAt },
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
await obs.flush();
|
|
263
|
+
return session;
|
|
264
|
+
},
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function finalize(
|
|
269
|
+
deps: RunTurnDeps,
|
|
270
|
+
session: Session,
|
|
271
|
+
assistantText: string,
|
|
272
|
+
thoughtText = "",
|
|
273
|
+
): Promise<Session> {
|
|
274
|
+
let next = session;
|
|
275
|
+
const thought = thoughtText.trim();
|
|
276
|
+
if (thought) {
|
|
277
|
+
next = await deps.store.append(next, { kind: "thought", text: thought });
|
|
278
|
+
}
|
|
279
|
+
next = await deps.store.append(next, {
|
|
280
|
+
kind: "turn",
|
|
281
|
+
role: "assistant",
|
|
282
|
+
content: assistantText,
|
|
283
|
+
});
|
|
284
|
+
if (deps.summarize) {
|
|
285
|
+
try {
|
|
286
|
+
next = await deps.store.maybeCompact(
|
|
287
|
+
next,
|
|
288
|
+
deps.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
289
|
+
deps.summarize,
|
|
290
|
+
);
|
|
291
|
+
} catch {
|
|
292
|
+
// fail-soft
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return next;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function guardTool(
|
|
299
|
+
def: McpToolDefinition,
|
|
300
|
+
approval: ApprovalGate,
|
|
301
|
+
emit: AgentEventEmitter,
|
|
302
|
+
obs: Observability,
|
|
303
|
+
hooks?: HookRunner,
|
|
304
|
+
): AgentTool {
|
|
305
|
+
return {
|
|
306
|
+
name: def.name,
|
|
307
|
+
description: def.description,
|
|
308
|
+
inputSchema: def.inputSchema,
|
|
309
|
+
invoke: (rawInput) => invokeGuarded(def, approval, emit, obs, rawInput ?? {}, hooks),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function invokeGuarded(
|
|
314
|
+
def: McpToolDefinition,
|
|
315
|
+
approval: ApprovalGate,
|
|
316
|
+
emit: AgentEventEmitter,
|
|
317
|
+
obs: Observability,
|
|
318
|
+
rawInput: Record<string, unknown>,
|
|
319
|
+
hooks?: HookRunner,
|
|
320
|
+
): Promise<ToolResult> {
|
|
321
|
+
const callId = newId("call");
|
|
322
|
+
const input = rawInput ?? {};
|
|
323
|
+
return obs.tool(
|
|
324
|
+
def.name,
|
|
325
|
+
async (span) => {
|
|
326
|
+
span.update({ input: sanitize(input) });
|
|
327
|
+
const result = await invokeGuardedBody(def, approval, emit, callId, input, hooks);
|
|
328
|
+
const success = !result.isError;
|
|
329
|
+
span.update({
|
|
330
|
+
output: sanitize(
|
|
331
|
+
success ? (result.structuredContent ?? toolResultText(result)) : toolResultText(result),
|
|
332
|
+
),
|
|
333
|
+
metadata: { success, callId },
|
|
334
|
+
...(success ? {} : { level: "ERROR" as const, statusMessage: toolResultText(result) }),
|
|
335
|
+
});
|
|
336
|
+
return result;
|
|
337
|
+
},
|
|
338
|
+
{ input: sanitize(input) },
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function invokeGuardedBody(
|
|
343
|
+
def: McpToolDefinition,
|
|
344
|
+
approval: ApprovalGate,
|
|
345
|
+
emit: AgentEventEmitter,
|
|
346
|
+
callId: string,
|
|
347
|
+
input: Record<string, unknown>,
|
|
348
|
+
hooks?: HookRunner,
|
|
349
|
+
): Promise<ToolResult> {
|
|
350
|
+
let result: ToolResult | undefined;
|
|
351
|
+
let success = false;
|
|
352
|
+
let errorText: string | undefined;
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
emit({ kind: "tool_call_start", toolName: def.name, callId, input });
|
|
356
|
+
const hook = await hooks?.preTool(def.name, input);
|
|
357
|
+
if (hook && !hook.allow) {
|
|
358
|
+
errorText = hook.reason ?? `Tool call "${def.name}" was blocked by a pre_tool hook.`;
|
|
359
|
+
result = errorResult(errorText);
|
|
360
|
+
}
|
|
361
|
+
let approved = true;
|
|
362
|
+
if (!result && isRiskyToolCall(def.name)) {
|
|
363
|
+
approved = await approval.request({ callId, toolName: def.name, input });
|
|
364
|
+
}
|
|
365
|
+
if (result) {
|
|
366
|
+
// hook already denied
|
|
367
|
+
} else if (!approved) {
|
|
368
|
+
errorText = `Tool call "${def.name}" ${REJECTED_TOOL_MESSAGE}.`;
|
|
369
|
+
result = errorResult(errorText);
|
|
370
|
+
} else {
|
|
371
|
+
try {
|
|
372
|
+
const handlerResult = await def.handler(input);
|
|
373
|
+
if (handlerResult.isError) {
|
|
374
|
+
errorText = toolResultText(handlerResult);
|
|
375
|
+
result = handlerResult;
|
|
376
|
+
} else {
|
|
377
|
+
result = handlerResult;
|
|
378
|
+
success = true;
|
|
379
|
+
}
|
|
380
|
+
} catch (handlerErr) {
|
|
381
|
+
errorText = errorMessage(handlerErr);
|
|
382
|
+
result = errorResult(errorText);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
} catch (dispatchErr) {
|
|
386
|
+
errorText = errorMessage(dispatchErr);
|
|
387
|
+
result = errorResult(errorText);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const finalResult = result ?? errorResult("tool produced no result");
|
|
391
|
+
void hooks?.postTool(def.name, input, success);
|
|
392
|
+
if (success && def.name === "todo_write") {
|
|
393
|
+
const items = (finalResult.structuredContent as { items?: unknown } | undefined)?.items;
|
|
394
|
+
if (Array.isArray(items)) {
|
|
395
|
+
emit({
|
|
396
|
+
kind: "todos",
|
|
397
|
+
items: items.filter(
|
|
398
|
+
(item): item is { id: string; content: string; status: string } =>
|
|
399
|
+
!!item &&
|
|
400
|
+
typeof item === "object" &&
|
|
401
|
+
typeof (item as { id?: unknown }).id === "string" &&
|
|
402
|
+
typeof (item as { content?: unknown }).content === "string" &&
|
|
403
|
+
typeof (item as { status?: unknown }).status === "string",
|
|
404
|
+
),
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
emit({
|
|
409
|
+
kind: "tool_call_end",
|
|
410
|
+
toolName: def.name,
|
|
411
|
+
callId,
|
|
412
|
+
success,
|
|
413
|
+
...(success ? { result: finalResult.structuredContent } : {}),
|
|
414
|
+
...(errorText !== undefined ? { error: errorText } : {}),
|
|
415
|
+
});
|
|
416
|
+
return finalResult;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function previewToolInput(input: Record<string, unknown>): string {
|
|
420
|
+
const cmd = typeof input.command === "string" ? input.command : undefined;
|
|
421
|
+
const path = typeof input.path === "string" ? input.path : undefined;
|
|
422
|
+
const pattern = typeof input.pattern === "string" ? input.pattern : undefined;
|
|
423
|
+
const prompt = typeof input.prompt === "string" ? input.prompt : undefined;
|
|
424
|
+
const label = typeof input.label === "string" ? input.label : undefined;
|
|
425
|
+
const raw = label ?? cmd ?? path ?? pattern ?? prompt ?? JSON.stringify(input);
|
|
426
|
+
return raw.length > 80 ? `${raw.slice(0, 79)}…` : raw;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export function buildSystemPrompt(input: {
|
|
430
|
+
name: string;
|
|
431
|
+
cwd: string;
|
|
432
|
+
instructions?: string;
|
|
433
|
+
userInstructions?: string;
|
|
434
|
+
projectInstructions?: string;
|
|
435
|
+
skillCatalog?: string;
|
|
436
|
+
mode?: AgentMode;
|
|
437
|
+
}): string {
|
|
438
|
+
const parts = [
|
|
439
|
+
"You are a coding agent in this project.",
|
|
440
|
+
`Project root: ${input.cwd}.`,
|
|
441
|
+
"Prefer small, targeted edits. Use edit_file for snippets, write_file for new files.",
|
|
442
|
+
"Use read_file, glob, and grep to inspect the repo. Do not use exec to read or search files.",
|
|
443
|
+
"Use git_status, git_diff, and git_log for git. git_commit requires approval and does not push.",
|
|
444
|
+
"Read skills with read_skill when a task matches a skill name. Spawn a subagent with task for a focused job.",
|
|
445
|
+
"Use todo_write for multi-step work.",
|
|
446
|
+
"Reply in plain text for a terminal. Do not use markdown.",
|
|
447
|
+
"Do not introduce yourself. Do not list skills, tools, or capabilities unless the user asks.",
|
|
448
|
+
"Do not invent metrics, testimonials, or sample numbers.",
|
|
449
|
+
];
|
|
450
|
+
if (input.mode) parts.push(modePrompt(input.mode));
|
|
451
|
+
if (input.userInstructions?.trim()) {
|
|
452
|
+
parts.push("## User instructions", input.userInstructions.trim());
|
|
453
|
+
}
|
|
454
|
+
if (input.projectInstructions?.trim()) {
|
|
455
|
+
parts.push("## Project instructions", input.projectInstructions.trim());
|
|
456
|
+
} else if (input.instructions?.trim()) {
|
|
457
|
+
parts.push("## Instructions", input.instructions.trim());
|
|
458
|
+
}
|
|
459
|
+
if (input.skillCatalog?.trim()) parts.push(input.skillCatalog.trim());
|
|
460
|
+
return parts.join("\n\n");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export function defaultSummarizer(provider: MainModelProvider): SummarizerFn {
|
|
464
|
+
return async ({ messages }) => {
|
|
465
|
+
const text = messages
|
|
466
|
+
.map((m) => {
|
|
467
|
+
if (m.kind === "turn") return `${m.role}: ${m.content}`;
|
|
468
|
+
if (m.kind === "system") return `system: ${m.text}`;
|
|
469
|
+
if (m.kind === "tool") return `tool ${m.name}: ${m.preview}`;
|
|
470
|
+
if (m.kind === "thought") return `thought: ${m.text}`;
|
|
471
|
+
return `summary: ${m.summary}`;
|
|
472
|
+
})
|
|
473
|
+
.join("\n")
|
|
474
|
+
.slice(0, 24_000);
|
|
475
|
+
let out = "";
|
|
476
|
+
for await (const event of provider.stream({
|
|
477
|
+
system:
|
|
478
|
+
"Summarize this conversation span in a few short paragraphs. Keep facts. No preamble.",
|
|
479
|
+
messages: [{ role: "user", content: text }],
|
|
480
|
+
maxTokens: 800,
|
|
481
|
+
})) {
|
|
482
|
+
if (event.type === "text_delta") out += event.text;
|
|
483
|
+
if (event.type === "error") throw new Error(event.message);
|
|
484
|
+
}
|
|
485
|
+
return out.trim() || "Earlier turns were compacted.";
|
|
486
|
+
};
|
|
487
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
createFileSessionStore,
|
|
7
|
+
estimateTokens,
|
|
8
|
+
latestCompactionCover,
|
|
9
|
+
liveContextTokens,
|
|
10
|
+
normalizeSessionTitle,
|
|
11
|
+
replaceUserTurn,
|
|
12
|
+
sessionToProviderMessages,
|
|
13
|
+
sessionTranscript,
|
|
14
|
+
titleFromUserMessage,
|
|
15
|
+
} from "./session.ts";
|
|
16
|
+
|
|
17
|
+
describe("session store", () => {
|
|
18
|
+
test("titles collapse whitespace", () => {
|
|
19
|
+
expect(titleFromUserMessage(" hello world ")).toBe("hello world");
|
|
20
|
+
expect(titleFromUserMessage("x".repeat(80)).endsWith("…")).toBe(true);
|
|
21
|
+
expect(normalizeSessionTitle(" ")).toBe("");
|
|
22
|
+
expect(normalizeSessionTitle(" billing copy ")).toBe("billing copy");
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("append-only file store", async () => {
|
|
26
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-ses-"));
|
|
27
|
+
try {
|
|
28
|
+
const store = createFileSessionStore(cwd);
|
|
29
|
+
let session = await store.create("system");
|
|
30
|
+
expect(session.messages[0]?.kind).toBe("system");
|
|
31
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "hi" });
|
|
32
|
+
session = await store.append(session, { kind: "turn", role: "assistant", content: "hello" });
|
|
33
|
+
const loaded = await store.get(session.id);
|
|
34
|
+
expect(loaded?.messages.length).toBe(3);
|
|
35
|
+
const list = await store.list();
|
|
36
|
+
expect(list[0]?.id).toBe(session.id);
|
|
37
|
+
} finally {
|
|
38
|
+
await rm(cwd, { recursive: true, force: true });
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("transcript keeps tool calls between turns", async () => {
|
|
43
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-transcript-"));
|
|
44
|
+
try {
|
|
45
|
+
const store = createFileSessionStore(cwd);
|
|
46
|
+
let session = await store.create("system");
|
|
47
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "list pages" });
|
|
48
|
+
session = await store.append(session, {
|
|
49
|
+
kind: "thought",
|
|
50
|
+
text: "I should look this up.",
|
|
51
|
+
});
|
|
52
|
+
session = await store.append(session, {
|
|
53
|
+
kind: "tool",
|
|
54
|
+
name: "notion__notion_fetch",
|
|
55
|
+
callId: "call-1",
|
|
56
|
+
status: "ok",
|
|
57
|
+
preview: '{"id":"abc"}',
|
|
58
|
+
});
|
|
59
|
+
session = await store.append(session, { kind: "turn", role: "assistant", content: "done" });
|
|
60
|
+
expect(sessionTranscript(session).map((line) => line.kind)).toEqual([
|
|
61
|
+
"user",
|
|
62
|
+
"thought",
|
|
63
|
+
"tool",
|
|
64
|
+
"assistant",
|
|
65
|
+
]);
|
|
66
|
+
expect(sessionToProviderMessages(session).map((line) => line.role)).toEqual([
|
|
67
|
+
"user",
|
|
68
|
+
"assistant",
|
|
69
|
+
]);
|
|
70
|
+
} finally {
|
|
71
|
+
await rm(cwd, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("compaction inserts a non-overlapping checkpoint", async () => {
|
|
76
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-cmp-"));
|
|
77
|
+
try {
|
|
78
|
+
const store = createFileSessionStore(cwd);
|
|
79
|
+
let session = await store.create("system");
|
|
80
|
+
session = await store.append(session, {
|
|
81
|
+
kind: "turn",
|
|
82
|
+
role: "user",
|
|
83
|
+
content: "a".repeat(400),
|
|
84
|
+
});
|
|
85
|
+
session = await store.append(session, {
|
|
86
|
+
kind: "turn",
|
|
87
|
+
role: "assistant",
|
|
88
|
+
content: "b".repeat(400),
|
|
89
|
+
});
|
|
90
|
+
expect(estimateTokens(session.messages)).toBeGreaterThan(10);
|
|
91
|
+
session = await store.maybeCompact(session, 20, async () => "summary of earlier turns");
|
|
92
|
+
const last = session.messages[session.messages.length - 1];
|
|
93
|
+
expect(last?.kind).toBe("compaction_checkpoint");
|
|
94
|
+
if (last?.kind === "compaction_checkpoint") {
|
|
95
|
+
expect(last.coversFromSeq).toBe(0);
|
|
96
|
+
expect(last.summary).toBe("summary of earlier turns");
|
|
97
|
+
}
|
|
98
|
+
} finally {
|
|
99
|
+
await rm(cwd, { recursive: true, force: true });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("provider messages omit turns already covered by a checkpoint", async () => {
|
|
104
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-cover-"));
|
|
105
|
+
try {
|
|
106
|
+
const store = createFileSessionStore(cwd);
|
|
107
|
+
let session = await store.create("system");
|
|
108
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "old" });
|
|
109
|
+
session = await store.append(session, {
|
|
110
|
+
kind: "turn",
|
|
111
|
+
role: "assistant",
|
|
112
|
+
content: "old reply",
|
|
113
|
+
});
|
|
114
|
+
session = await store.maybeCompact(session, 1, async () => "earlier work");
|
|
115
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "new" });
|
|
116
|
+
session = await store.append(session, {
|
|
117
|
+
kind: "turn",
|
|
118
|
+
role: "assistant",
|
|
119
|
+
content: "new reply",
|
|
120
|
+
});
|
|
121
|
+
expect(latestCompactionCover(session)).toBe(2);
|
|
122
|
+
expect(sessionToProviderMessages(session)).toEqual([
|
|
123
|
+
{ role: "user", content: "new" },
|
|
124
|
+
{ role: "assistant", content: "new reply" },
|
|
125
|
+
]);
|
|
126
|
+
expect(liveContextTokens(session)).toBeLessThan(estimateTokens(session.messages));
|
|
127
|
+
} finally {
|
|
128
|
+
await rm(cwd, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("auto-compact does not fire again until live context grows", async () => {
|
|
133
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-live-"));
|
|
134
|
+
try {
|
|
135
|
+
const store = createFileSessionStore(cwd);
|
|
136
|
+
let session = await store.create("system");
|
|
137
|
+
session = await store.append(session, {
|
|
138
|
+
kind: "turn",
|
|
139
|
+
role: "user",
|
|
140
|
+
content: "a".repeat(400),
|
|
141
|
+
});
|
|
142
|
+
session = await store.append(session, {
|
|
143
|
+
kind: "turn",
|
|
144
|
+
role: "assistant",
|
|
145
|
+
content: "b".repeat(400),
|
|
146
|
+
});
|
|
147
|
+
session = await store.maybeCompact(session, 20, async () => "summary of earlier turns");
|
|
148
|
+
const after = session.messages.length;
|
|
149
|
+
session = await store.maybeCompact(session, 20, async () => {
|
|
150
|
+
throw new Error("should not summarize again");
|
|
151
|
+
});
|
|
152
|
+
expect(session.messages.length).toBe(after);
|
|
153
|
+
} finally {
|
|
154
|
+
await rm(cwd, { recursive: true, force: true });
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("replaceUserTurn drops later turns and checkpoints", async () => {
|
|
159
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-edit-"));
|
|
160
|
+
try {
|
|
161
|
+
const store = createFileSessionStore(cwd);
|
|
162
|
+
let session = await store.create("system");
|
|
163
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "first" });
|
|
164
|
+
session = await store.append(session, {
|
|
165
|
+
kind: "turn",
|
|
166
|
+
role: "assistant",
|
|
167
|
+
content: "reply one",
|
|
168
|
+
});
|
|
169
|
+
session = await store.append(session, { kind: "turn", role: "user", content: "second" });
|
|
170
|
+
session = await store.append(session, {
|
|
171
|
+
kind: "turn",
|
|
172
|
+
role: "assistant",
|
|
173
|
+
content: "reply two",
|
|
174
|
+
});
|
|
175
|
+
session = await store.save(replaceUserTurn(session, 0, "first edited"));
|
|
176
|
+
expect(sessionToProviderMessages(session)).toEqual([
|
|
177
|
+
{ role: "user", content: "first edited" },
|
|
178
|
+
]);
|
|
179
|
+
expect(session.title).toBe("first edited");
|
|
180
|
+
} finally {
|
|
181
|
+
await rm(cwd, { recursive: true, force: true });
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("renames and deletes a chat", async () => {
|
|
186
|
+
const cwd = await mkdtemp(join(tmpdir(), "harness-ses-edit-"));
|
|
187
|
+
try {
|
|
188
|
+
const store = createFileSessionStore(cwd);
|
|
189
|
+
let session = await store.create("system");
|
|
190
|
+
const updatedAt = session.updatedAt;
|
|
191
|
+
session = await store.setTitle(session, "Billing copy");
|
|
192
|
+
expect(session.title).toBe("Billing copy");
|
|
193
|
+
expect(session.updatedAt).toBe(updatedAt);
|
|
194
|
+
expect((await store.get(session.id))?.title).toBe("Billing copy");
|
|
195
|
+
expect(await store.remove(session.id)).toBe(true);
|
|
196
|
+
expect(await store.get(session.id)).toBeUndefined();
|
|
197
|
+
expect(await store.list()).toEqual([]);
|
|
198
|
+
expect(await store.remove(session.id)).toBe(false);
|
|
199
|
+
} finally {
|
|
200
|
+
await rm(cwd, { recursive: true, force: true });
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
});
|