@wraith-ai/core 0.1.0 → 0.1.1
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 +1 -1
- package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
- package/dist/attempt-HgararU3.d.mts.map +1 -0
- package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
- package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -0
- package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
- package/dist/methods-7Ryz6zbd.mjs.map +1 -0
- package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
- package/dist/model-C16NUwXW.mjs.map +1 -0
- package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
- package/dist/model-_wqePNTL.d.mts.map +1 -0
- package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
- package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
- package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
- package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
- package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
- package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
- package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
- package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
- package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
- package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
- package/dist/providers/openai-codex.d.mts +4 -3
- package/dist/providers/openai-codex.d.mts.map +1 -0
- package/dist/providers/openai-codex.mjs +1 -1
- package/dist/providers/openai-compatible.d.mts +3 -2
- package/dist/providers/openai-compatible.d.mts.map +1 -0
- package/dist/providers/openai-compatible.mjs +1 -1
- package/dist/providers/openrouter.d.mts +3 -2
- package/dist/providers/openrouter.d.mts.map +1 -0
- package/dist/providers/openrouter.mjs +1 -1
- package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
- package/dist/shared-BIJaPhMm.mjs.map +1 -0
- package/dist/snapshot.d.mts +3 -2
- package/dist/snapshot.d.mts.map +1 -0
- package/dist/snapshot.mjs +4999 -4977
- package/dist/snapshot.mjs.map +1 -0
- package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
- package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
- package/package.json +3 -2
- package/src/agent/agent.ts +90 -0
- package/src/agent/attachments.ts +195 -0
- package/src/agent/classifier.ts +525 -0
- package/src/agent/compact.ts +384 -0
- package/src/agent/conversation.ts +300 -0
- package/src/agent/cost.ts +164 -0
- package/src/agent/inbox.ts +80 -0
- package/src/agent/instructions.ts +62 -0
- package/src/agent/loop.ts +675 -0
- package/src/agent/messages.ts +252 -0
- package/src/agent/on-demand.ts +58 -0
- package/src/agent/prompts.ts +35 -0
- package/src/agent/request-images.ts +94 -0
- package/src/agent/stop.ts +37 -0
- package/src/agent/title.ts +122 -0
- package/src/agent/tool-groups.ts +186 -0
- package/src/agent/tools.ts +106 -0
- package/src/app.ts +67 -0
- package/src/config/credential-file-store.ts +66 -0
- package/src/config/environment.ts +105 -0
- package/src/config/instructions.ts +157 -0
- package/src/config/load.ts +667 -0
- package/src/config/locked-file.ts +85 -0
- package/src/config/paths.ts +368 -0
- package/src/config/schema.ts +363 -0
- package/src/config/subagents.ts +156 -0
- package/src/config/trust.ts +53 -0
- package/src/config/write.ts +241 -0
- package/src/errors.ts +85 -0
- package/src/events/types.ts +258 -0
- package/src/glob.ts +161 -0
- package/src/index.ts +681 -0
- package/src/logger.ts +47 -0
- package/src/paths.ts +143 -0
- package/src/permissions/chain.ts +42 -0
- package/src/permissions/command.ts +233 -0
- package/src/permissions/layered.ts +77 -0
- package/src/permissions/match.ts +80 -0
- package/src/permissions/modes.ts +48 -0
- package/src/permissions/policy.ts +160 -0
- package/src/permissions/types.ts +159 -0
- package/src/providers/cache.ts +107 -0
- package/src/providers/capabilities.ts +77 -0
- package/src/providers/catalog-view.ts +91 -0
- package/src/providers/catalog.ts +65 -0
- package/src/providers/errors.ts +108 -0
- package/src/providers/factories/index.ts +15 -0
- package/src/providers/factories/openai-codex.ts +382 -0
- package/src/providers/factories/openai-compatible.ts +81 -0
- package/src/providers/factories/openrouter.ts +165 -0
- package/src/providers/factories/shared.ts +22 -0
- package/src/providers/model.ts +197 -0
- package/src/providers/models-dev.ts +355 -0
- package/src/providers/oauth/methods.ts +10 -0
- package/src/providers/oauth/openai-codex.ts +228 -0
- package/src/providers/oauth.ts +177 -0
- package/src/providers/openai-codex.ts +7 -0
- package/src/providers/openai-compatible.ts +2 -0
- package/src/providers/openrouter.ts +2 -0
- package/src/providers/registry.ts +464 -0
- package/src/providers/turn-effort.ts +156 -0
- package/src/providers/types.ts +83 -0
- package/src/session/backend.ts +44 -0
- package/src/session/file-store.ts +278 -0
- package/src/session/format.ts +1037 -0
- package/src/session/memory-store.ts +73 -0
- package/src/session/session.ts +153 -0
- package/src/session/store.ts +219 -0
- package/src/sign-in/attempt.ts +166 -0
- package/src/sign-in/loopback.ts +74 -0
- package/src/snapshot/data.json +8936 -0
- package/src/snapshot/index.ts +37 -0
- package/src/tools/bin.ts +364 -0
- package/src/tools/builtin.ts +48 -0
- package/src/tools/change.ts +88 -0
- package/src/tools/define.ts +267 -0
- package/src/tools/describe.ts +96 -0
- package/src/tools/fs/edit-file.ts +129 -0
- package/src/tools/fs/glob.ts +75 -0
- package/src/tools/fs/grep.ts +212 -0
- package/src/tools/fs/line-endings.ts +17 -0
- package/src/tools/fs/list-dir.ts +85 -0
- package/src/tools/fs/read-file.ts +230 -0
- package/src/tools/fs/ripgrep.ts +211 -0
- package/src/tools/fs/write-file.ts +97 -0
- package/src/tools/job.ts +252 -0
- package/src/tools/mcp/auth-store.ts +127 -0
- package/src/tools/mcp/command.ts +151 -0
- package/src/tools/mcp/config.ts +168 -0
- package/src/tools/mcp/servers.ts +463 -0
- package/src/tools/mcp/sign-in.ts +226 -0
- package/src/tools/mcp/stdio.ts +204 -0
- package/src/tools/mcp/tools.ts +173 -0
- package/src/tools/on-demand.ts +184 -0
- package/src/tools/registry.ts +935 -0
- package/src/tools/shell/bash.ts +217 -0
- package/src/tools/shell/find-bash.ts +162 -0
- package/src/tools/source.ts +35 -0
- package/src/tools/spill.ts +127 -0
- package/src/tools/subagents.ts +597 -0
- package/src/tools/tasks.ts +603 -0
- package/src/tools/to-model.ts +33 -0
- package/src/tools/web/address.ts +95 -0
- package/src/tools/web/exa.ts +163 -0
- package/src/tools/web/fetch.ts +373 -0
- package/src/tools/web/html.ts +173 -0
- package/src/tools/web/search.ts +111 -0
- package/src/tools/web/source.ts +51 -0
- package/src/units.ts +18 -0
- package/src/version.ts +23 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import type { ModelMessage } from "ai";
|
|
2
|
+
import { type Attachment, type Prompt, type UserInput, toUserInput } from "./attachments";
|
|
3
|
+
import type { ToolOutcome } from "./tools";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The one SDK type that leaks into our contracts: `ModelMessage`, re-exported
|
|
7
|
+
* here. The rest of the core, sessions included, imports it from this module,
|
|
8
|
+
* never from the SDK, so the layer guard holds and one file changes if the
|
|
9
|
+
* representation moves.
|
|
10
|
+
*/
|
|
11
|
+
export type { ModelMessage };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Assembles the conversation the loop sends: the user turn, the tool results,
|
|
15
|
+
* their order, and each result paired with its call by `toolCallId`. The
|
|
16
|
+
* assistant message comes from `response.messages`, never hand-built.
|
|
17
|
+
*
|
|
18
|
+
* A mistake here does not throw; it makes the model behave strangely.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export type UserMessage = Extract<ModelMessage, { role: "user" }>;
|
|
22
|
+
|
|
23
|
+
/** Throws `attachment/*` for an attachment that is not an image the vendors take. */
|
|
24
|
+
export function userMessage(prompt: Prompt): UserMessage {
|
|
25
|
+
const { text, attachments } = toUserInput(prompt);
|
|
26
|
+
// No images: the message as it always was, so old logs and the prompt cache stay as they are.
|
|
27
|
+
if (attachments.length === 0) return { role: "user", content: text };
|
|
28
|
+
// Images first, the order Anthropic recommends.
|
|
29
|
+
const parts = attachments.map(filePart);
|
|
30
|
+
return { role: "user", content: text === "" ? parts : [...parts, { type: "text", text }] };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The prompt a user message was made from: `userMessage` read backwards. */
|
|
34
|
+
export function userInputOf(message: ModelMessage): UserInput {
|
|
35
|
+
if (typeof message.content === "string") return { text: message.content, attachments: [] };
|
|
36
|
+
const texts: string[] = [];
|
|
37
|
+
const attachments: Attachment[] = [];
|
|
38
|
+
for (const part of message.content as readonly unknown[]) {
|
|
39
|
+
const record = part as { type?: unknown; text?: unknown };
|
|
40
|
+
if (record.type === "text" && typeof record.text === "string") texts.push(record.text);
|
|
41
|
+
const attachment = attachmentOf(part);
|
|
42
|
+
if (attachment !== undefined) attachments.push(attachment);
|
|
43
|
+
}
|
|
44
|
+
return { text: texts.join("\n"), attachments };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The part an attachment travels in, in a user message or a tool result alike. */
|
|
48
|
+
export function filePart(attachment: Attachment): {
|
|
49
|
+
type: "file";
|
|
50
|
+
mediaType: string;
|
|
51
|
+
data: { type: "data"; data: string };
|
|
52
|
+
} {
|
|
53
|
+
return { type: "file", mediaType: attachment.mediaType, data: { type: "data", data: attachment.data } };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The image a stored part carries, if it is one of ours. */
|
|
57
|
+
export function attachmentOf(part: unknown): Attachment | undefined {
|
|
58
|
+
if (part === null || typeof part !== "object") return undefined;
|
|
59
|
+
const record = part as { type?: unknown; mediaType?: unknown; data?: unknown };
|
|
60
|
+
if (record.type !== "file" || typeof record.mediaType !== "string") return undefined;
|
|
61
|
+
if (!record.mediaType.startsWith("image/")) return undefined;
|
|
62
|
+
const data = record.data as { type?: unknown; data?: unknown } | string | undefined;
|
|
63
|
+
if (typeof data === "string") return { data, mediaType: record.mediaType };
|
|
64
|
+
if (data?.type === "data" && typeof data.data === "string") return { data: data.data, mediaType: record.mediaType };
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Where we mark who wrote a user-role message that the user did not. A fixed
|
|
70
|
+
* format name, not the product's: a rename must not orphan stored logs. No
|
|
71
|
+
* vendor reads this key, so it stays in the log and is never sent.
|
|
72
|
+
*/
|
|
73
|
+
export const ORIGIN_OPTIONS_KEY = "origin";
|
|
74
|
+
|
|
75
|
+
/** Who wrote a user-role message, when it was not the user. */
|
|
76
|
+
type Author = "host" | "summary";
|
|
77
|
+
|
|
78
|
+
function writtenBy(author: Author, text: string): UserMessage {
|
|
79
|
+
return {
|
|
80
|
+
role: "user",
|
|
81
|
+
content: text,
|
|
82
|
+
providerOptions: { [ORIGIN_OPTIONS_KEY]: { by: author } },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function authorOf(message: ModelMessage): unknown {
|
|
87
|
+
if (message.role !== "user") return undefined;
|
|
88
|
+
const options = message.providerOptions as
|
|
89
|
+
| Record<string, Record<string, unknown> | undefined>
|
|
90
|
+
| undefined;
|
|
91
|
+
return options?.[ORIGIN_OPTIONS_KEY]?.["by"];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A user-role message that is not the user's words, such as a task ending.
|
|
96
|
+
* The stamp keeps it out of the classifier's transcript.
|
|
97
|
+
*/
|
|
98
|
+
export function hostMessage(text: string): UserMessage {
|
|
99
|
+
return writtenBy("host", text);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function isHostMessage(message: ModelMessage): boolean {
|
|
103
|
+
return authorOf(message) === "host";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The summary re-enters the conversation as a user turn, labelled so the model
|
|
108
|
+
* reads it as a briefing. A model wrote it, so the stamp tells the classifier
|
|
109
|
+
* it is not the user giving permission.
|
|
110
|
+
*/
|
|
111
|
+
export function summaryMessage(summary: string): UserMessage {
|
|
112
|
+
return writtenBy(
|
|
113
|
+
"summary",
|
|
114
|
+
`[Summary of the earlier conversation, which has been compacted away]\n\n${summary}`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function isSummaryMessage(message: ModelMessage): boolean {
|
|
119
|
+
return authorOf(message) === "summary";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The SDK's reply without the results it wrote for calls we answer. Our tools
|
|
124
|
+
* have no `execute`, so the SDK writes a result only for a call it judged
|
|
125
|
+
* invalid, and the registry answers those too. Two results for one call is a
|
|
126
|
+
* 400 at Anthropic, and the log would keep both.
|
|
127
|
+
*/
|
|
128
|
+
export function withoutResultsFor(
|
|
129
|
+
messages: readonly ModelMessage[],
|
|
130
|
+
answered: ReadonlySet<string>,
|
|
131
|
+
): ModelMessage[] {
|
|
132
|
+
const kept: ModelMessage[] = [];
|
|
133
|
+
for (const message of messages) {
|
|
134
|
+
if (message.role !== "tool") {
|
|
135
|
+
kept.push(message);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const content = message.content.filter(
|
|
139
|
+
(part) => !("toolCallId" in part && answered.has(part.toolCallId)),
|
|
140
|
+
);
|
|
141
|
+
if (content.length > 0) kept.push({ ...message, content });
|
|
142
|
+
}
|
|
143
|
+
return kept;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Calls of the history's last assistant message that no result follows. The
|
|
148
|
+
* loop writes a step's calls and results back to back, so a gap can only be
|
|
149
|
+
* at the end, where a run stopped between the two.
|
|
150
|
+
*/
|
|
151
|
+
export function unansweredCalls(
|
|
152
|
+
messages: readonly ModelMessage[],
|
|
153
|
+
): { toolCallId: string; toolName: string }[] {
|
|
154
|
+
const answered = new Set<string>();
|
|
155
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
156
|
+
const message = messages[index] as ModelMessage;
|
|
157
|
+
if (message.role === "tool") {
|
|
158
|
+
for (const part of message.content) {
|
|
159
|
+
if (part.type === "tool-result") answered.add(part.toolCallId);
|
|
160
|
+
}
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (message.role !== "assistant" || typeof message.content === "string") return [];
|
|
164
|
+
|
|
165
|
+
// A provider-executed tool carries its result in the same message.
|
|
166
|
+
for (const part of message.content) {
|
|
167
|
+
if (part.type === "tool-result") answered.add(part.toolCallId);
|
|
168
|
+
}
|
|
169
|
+
return message.content.flatMap((part) =>
|
|
170
|
+
part.type === "tool-call" && !answered.has(part.toolCallId)
|
|
171
|
+
? [{ toolCallId: part.toolCallId, toolName: part.toolName }]
|
|
172
|
+
: [],
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
return [];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* One tool message carrying every result of a step. Parallel calls belong in a
|
|
180
|
+
* single message: splitting them teaches the model to stop calling tools in
|
|
181
|
+
* parallel.
|
|
182
|
+
*/
|
|
183
|
+
export function toolResultMessage(outcomes: readonly ToolOutcome[]): ModelMessage {
|
|
184
|
+
return {
|
|
185
|
+
role: "tool",
|
|
186
|
+
content: outcomes.map((outcome) => ({
|
|
187
|
+
type: "tool-result" as const,
|
|
188
|
+
toolCallId: outcome.toolCallId,
|
|
189
|
+
toolName: outcome.toolName,
|
|
190
|
+
output: resultOutput(outcome),
|
|
191
|
+
})),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function resultOutput(outcome: ToolOutcome) {
|
|
196
|
+
if (outcome.error !== undefined) return { type: "error-text" as const, value: outcome.error.message };
|
|
197
|
+
const text = renderOutput(outcome.output);
|
|
198
|
+
const attachments = outcome.attachments ?? [];
|
|
199
|
+
if (attachments.length === 0) return { type: "text" as const, value: text };
|
|
200
|
+
return {
|
|
201
|
+
type: "content" as const,
|
|
202
|
+
value: [{ type: "text" as const, text }, ...attachments.map(filePart)],
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The value a stored tool result had before `renderOutput` flattened it. A live
|
|
208
|
+
* `tool-result` event carries the tool's own value; the stored copy is wrapped
|
|
209
|
+
* as `{ type: "text", value: "<json>" }`, because that is what a model reads.
|
|
210
|
+
* Anything describing both must undo the wrapper: a describer handed the
|
|
211
|
+
* wrapper gives wrong output without throwing.
|
|
212
|
+
*/
|
|
213
|
+
export function toolResultValue(output: unknown): unknown {
|
|
214
|
+
if (output === null || typeof output !== "object") return output;
|
|
215
|
+
|
|
216
|
+
const part = output as { type?: unknown; value?: unknown };
|
|
217
|
+
// An error has its own line and its own colour; describing it as a result
|
|
218
|
+
// would say the call succeeded.
|
|
219
|
+
if (part.type === "error-text") return undefined;
|
|
220
|
+
if (part.type === "json") return part.value;
|
|
221
|
+
// A result with images: its value is the text part; the images are beside it.
|
|
222
|
+
if (part.type === "content" && Array.isArray(part.value)) {
|
|
223
|
+
const text = (part.value as { type?: unknown; text?: unknown }[]).find((item) => item.type === "text");
|
|
224
|
+
return toolResultValue({ type: "text", value: text?.text ?? "" });
|
|
225
|
+
}
|
|
226
|
+
if (part.type !== "text" || typeof part.value !== "string") return output;
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
return JSON.parse(part.value);
|
|
230
|
+
} catch {
|
|
231
|
+
// A tool that returned a plain string round-trips as itself.
|
|
232
|
+
return part.value;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Tools return data; the model reads text. Objects go over as JSON. */
|
|
237
|
+
function renderOutput(output: unknown): string {
|
|
238
|
+
if (typeof output === "string") return output;
|
|
239
|
+
if (output === undefined) return "";
|
|
240
|
+
try {
|
|
241
|
+
return JSON.stringify(output);
|
|
242
|
+
} catch {
|
|
243
|
+
return String(output);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function withUserPrompt(
|
|
248
|
+
history: readonly ModelMessage[],
|
|
249
|
+
prompt: Prompt,
|
|
250
|
+
): ModelMessage[] {
|
|
251
|
+
return [...history, userMessage(prompt)];
|
|
252
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ModelMessage } from "ai";
|
|
2
|
+
import { CALL_TOOL_NAME, SEARCH_TOOLS_NAME } from "../tools/on-demand";
|
|
3
|
+
import { isHostMessage } from "./messages";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What the model is told about tools kept off its list.
|
|
7
|
+
*
|
|
8
|
+
* A host message at the end of the conversation, never a change to the tool
|
|
9
|
+
* list or the system prompt, which open every request: either would cost the
|
|
10
|
+
* whole prompt cache. The last such message in the history is the model's
|
|
11
|
+
* current knowledge, so a compaction, which drops it, brings a fresh one.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const OPEN = "<on_demand_tools>";
|
|
15
|
+
const CLOSE = "</on_demand_tools>";
|
|
16
|
+
// The model sees a user turn without the host stamp; unsaid, it thanks the user for the list.
|
|
17
|
+
const SENDER = "This notice comes from the harness, not from the user.";
|
|
18
|
+
|
|
19
|
+
export function onDemandNotice(names: readonly string[]): string {
|
|
20
|
+
const body =
|
|
21
|
+
names.length === 0
|
|
22
|
+
? `No tools are reachable through ${CALL_TOOL_NAME} now.`
|
|
23
|
+
: [
|
|
24
|
+
"These tools are not in your tool list. Get a tool's description and parameters with " +
|
|
25
|
+
`${SEARCH_TOOLS_NAME}, then call it with ${CALL_TOOL_NAME}:`,
|
|
26
|
+
...names,
|
|
27
|
+
].join("\n");
|
|
28
|
+
return `${OPEN}\n${SENDER}\n${body}\n${CLOSE}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The last notice the model was given, or nothing when this history holds none. */
|
|
32
|
+
export function lastOnDemandNotice(messages: readonly ModelMessage[]): string | undefined {
|
|
33
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
34
|
+
const message = messages[index];
|
|
35
|
+
if (message === undefined || !isHostMessage(message)) continue;
|
|
36
|
+
if (typeof message.content === "string" && message.content.startsWith(OPEN)) {
|
|
37
|
+
return message.content;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Whether a host message is this notice, for a front end that draws it as one line. */
|
|
44
|
+
export function isOnDemandNotice(message: ModelMessage): boolean {
|
|
45
|
+
return (
|
|
46
|
+
isHostMessage(message) && typeof message.content === "string" && message.content.startsWith(OPEN)
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The names a notice gave, or nothing for a message that is not one. */
|
|
51
|
+
export function onDemandNames(message: ModelMessage): string[] | undefined {
|
|
52
|
+
if (!isOnDemandNotice(message) || typeof message.content !== "string") return undefined;
|
|
53
|
+
// The names are the lines with no spaces between the opening sentence and the frame's end.
|
|
54
|
+
return message.content
|
|
55
|
+
.split("\n")
|
|
56
|
+
.slice(1, -1)
|
|
57
|
+
.filter((line) => line !== "" && !/\s/.test(line));
|
|
58
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt fragments the core owns, because behaviour depends on them. The
|
|
3
|
+
* product prompt belongs to the application: whoever builds an agent on this
|
|
4
|
+
* package writes their own. What stays is what the permission model relies on,
|
|
5
|
+
* such as the instruction not to retry a refused call.
|
|
6
|
+
*
|
|
7
|
+
* These are TypeScript constants, never files read at runtime: `node:fs` is
|
|
8
|
+
* banned in `agent/`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Splice this into the system prompt of any agent that runs tools behind a permission policy. */
|
|
12
|
+
export const TOOL_POLICY_GUIDANCE = `Tool calls run behind a permission policy. Some are allowed outright, some are
|
|
13
|
+
refused, and some require a person to approve them before they run.
|
|
14
|
+
|
|
15
|
+
When a tool call comes back refused:
|
|
16
|
+
- Do not call it again with the same arguments. The refusal will not change on
|
|
17
|
+
its own, and a retry costs a step without producing anything.
|
|
18
|
+
- Read the reason. "Nobody was available to approve it" is different from "the
|
|
19
|
+
user said no": the first is worth telling the user about, so they can rerun
|
|
20
|
+
with approvals available; the second means they already decided.
|
|
21
|
+
- Take a different route if one exists, or stop and say plainly what you would
|
|
22
|
+
need in order to continue.
|
|
23
|
+
|
|
24
|
+
The file tools work inside the workspace root and refuse paths outside it. The
|
|
25
|
+
shell starts in the workspace root. A command that reaches outside it is not
|
|
26
|
+
refused for that alone; like any command, it may need a person's approval.
|
|
27
|
+
Stay inside the workspace unless the task needs otherwise.`;
|
|
28
|
+
|
|
29
|
+
/** Joins the fragments a host supplies with the ones behaviour depends on. */
|
|
30
|
+
export function composeSystemPrompt(...parts: readonly (string | undefined)[]): string {
|
|
31
|
+
return parts
|
|
32
|
+
.map((part) => part?.trim())
|
|
33
|
+
.filter((part): part is string => part !== undefined && part !== "")
|
|
34
|
+
.join("\n\n");
|
|
35
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { Model } from "../providers/model";
|
|
2
|
+
import { attachmentOf, filePart, type ModelMessage } from "./messages";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The history as one model can take its images. The log keeps a single form,
|
|
6
|
+
* images where they arrived; this rewrites only what one request sends.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** What the catalog says about images; `undefined` when it says nothing. */
|
|
10
|
+
export function takesImages(model: Pick<Model, "info">): boolean | undefined {
|
|
11
|
+
const input = model.info?.input;
|
|
12
|
+
return input === undefined ? undefined : input.includes("image");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What a host tells the user before images go out, when there is anything to
|
|
17
|
+
* tell: the catalog's "no", or that it does not know. Nothing on its "yes".
|
|
18
|
+
*/
|
|
19
|
+
export function imagesNote(model: Pick<Model, "info" | "modelId">): string | undefined {
|
|
20
|
+
const takes = takesImages(model);
|
|
21
|
+
if (takes === true) return undefined;
|
|
22
|
+
return takes === false
|
|
23
|
+
? `${model.modelId} does not take images, by the catalog; it will be told where each one was left out.`
|
|
24
|
+
: `The catalog does not say whether ${model.modelId} takes images; some servers drop them without a word.`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Said in place of an image, so the model knows one was there and was not seen. */
|
|
28
|
+
export function imageLeftOut(modelId: string): string {
|
|
29
|
+
return `[An image was left out here: ${modelId} does not take images.]`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const MOVED = "(The image follows in the next message.)";
|
|
33
|
+
const MOVED_HEADER = "Images from the tool results above:";
|
|
34
|
+
|
|
35
|
+
export function imagesForModel(messages: ModelMessage[], model: Model): ModelMessage[] {
|
|
36
|
+
if (!messages.some(hasImage)) return messages;
|
|
37
|
+
// Only on the catalog's word: a model it does not know may well see them.
|
|
38
|
+
if (takesImages(model) === false) return messages.map((message) => withoutImages(message, imageLeftOut(model.modelId)));
|
|
39
|
+
if (model.imagesInToolResults === false) return movedOutOfToolResults(messages);
|
|
40
|
+
return messages;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function hasImage(message: ModelMessage): boolean {
|
|
44
|
+
if (typeof message.content === "string") return false;
|
|
45
|
+
return (message.content as readonly unknown[]).some(
|
|
46
|
+
(part) => attachmentOf(part) !== undefined || resultParts(part).some((item) => attachmentOf(item) !== undefined),
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The parts of a tool result that carries images; empty for any other part. */
|
|
51
|
+
function resultParts(part: unknown): readonly unknown[] {
|
|
52
|
+
const record = part as { type?: unknown; output?: { type?: unknown; value?: unknown } };
|
|
53
|
+
if (record.type !== "tool-result" || record.output?.type !== "content") return [];
|
|
54
|
+
return Array.isArray(record.output.value) ? record.output.value : [];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function withoutImages(message: ModelMessage, note: string): ModelMessage {
|
|
58
|
+
if (typeof message.content === "string") return message;
|
|
59
|
+
const content = (message.content as readonly unknown[]).map((part) =>
|
|
60
|
+
attachmentOf(part) === undefined ? withResultText(part, note) : { type: "text", text: note },
|
|
61
|
+
);
|
|
62
|
+
return { ...message, content } as ModelMessage;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A result's images replaced by `note`, and the result made plain text again. */
|
|
66
|
+
function withResultText(part: unknown, note: string): unknown {
|
|
67
|
+
const items = resultParts(part);
|
|
68
|
+
if (!items.some((item) => attachmentOf(item) !== undefined)) return part;
|
|
69
|
+
const text = items
|
|
70
|
+
.map((item) => (attachmentOf(item) === undefined ? String((item as { text?: unknown }).text ?? "") : note))
|
|
71
|
+
.join("\n");
|
|
72
|
+
return { ...(part as object), output: { type: "text", value: text } };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* For an API whose tool message is text only: the images go into a user
|
|
77
|
+
* message right after the results, where that API does take them.
|
|
78
|
+
*/
|
|
79
|
+
function movedOutOfToolResults(messages: readonly ModelMessage[]): ModelMessage[] {
|
|
80
|
+
return messages.flatMap((message) => {
|
|
81
|
+
if (message.role !== "tool") return [message];
|
|
82
|
+
const images = message.content.flatMap((part) => resultParts(part).filter((item) => attachmentOf(item) !== undefined));
|
|
83
|
+
if (images.length === 0) return [message];
|
|
84
|
+
const results = withoutImages(message, MOVED);
|
|
85
|
+
const carrier: ModelMessage = {
|
|
86
|
+
role: "user",
|
|
87
|
+
content: [
|
|
88
|
+
{ type: "text", text: MOVED_HEADER },
|
|
89
|
+
...images.map((item) => filePart(attachmentOf(item) as NonNullable<ReturnType<typeof attachmentOf>>)),
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
return [results, carrier];
|
|
93
|
+
});
|
|
94
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Usage } from "../events/types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* When to stop looping.
|
|
5
|
+
*
|
|
6
|
+
* Natural termination, when the model asks for no tools, is decided by the
|
|
7
|
+
* loop itself and is not expressed here. These are guards on top of it. They
|
|
8
|
+
* are ours, not the SDK's, so they can be tested without a model.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface LoopState {
|
|
12
|
+
/** Steps completed so far. */
|
|
13
|
+
step: number;
|
|
14
|
+
/** Tool names requested in the step that just finished. */
|
|
15
|
+
toolCalls: readonly string[];
|
|
16
|
+
usage: Usage;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type StopCondition = (state: LoopState) => boolean;
|
|
20
|
+
|
|
21
|
+
/** The safety net against a runaway loop. Always present. */
|
|
22
|
+
export function isStepCount(max: number): StopCondition {
|
|
23
|
+
return (state) => state.step >= max;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Stops once the model calls a tool that means "I am done". */
|
|
27
|
+
export function hasToolCall(...names: readonly string[]): StopCondition {
|
|
28
|
+
return (state) => state.toolCalls.some((name) => names.includes(name));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isTokenCount(max: number): StopCondition {
|
|
32
|
+
return (state) => (state.usage.totalTokens ?? 0) >= max;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function anyOf(...conditions: readonly StopCondition[]): StopCondition {
|
|
36
|
+
return (state) => conditions.some((condition) => condition(state));
|
|
37
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { generateText } from "ai";
|
|
2
|
+
import { normaliseUsage, type Usage } from "../events/types";
|
|
3
|
+
import { withRequestFields } from "../providers/cache";
|
|
4
|
+
import { type Model, toModel } from "../providers/model";
|
|
5
|
+
import type { AgentLanguageModel, ModelCallSettings } from "../providers/types";
|
|
6
|
+
import { type ModelPrices, priceCall } from "./cost";
|
|
7
|
+
import type { ModelMessage } from "./messages";
|
|
8
|
+
import { renderTranscript } from "./compact";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A name for a session, written by a model. It improves on the fallback, the
|
|
12
|
+
* first line of the first user turn, which the log fold always derives.
|
|
13
|
+
*
|
|
14
|
+
* It runs after a turn rather than before one and never blocks. Every failure
|
|
15
|
+
* returns `undefined`, so the session keeps the name it already had.
|
|
16
|
+
*
|
|
17
|
+
* The spend is returned to the caller, which records it through
|
|
18
|
+
* `addUsageRecord`, the single door session costs come in by.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const TITLE_TEMPLATE = `You name coding-assistant sessions so a person scanning a list can tell them apart.
|
|
22
|
+
|
|
23
|
+
Read the exchange and reply with a title for it. Rules:
|
|
24
|
+
- At most 60 characters, and no trailing period.
|
|
25
|
+
- Name the task, not the conversation: "Add a --dry-run flag to the build script", never "User asks about the build script".
|
|
26
|
+
- Use the concrete nouns from the exchange — file names, flags, commands — over general words.
|
|
27
|
+
- If the exchange is too vague to name, reply with the single word: unknown
|
|
28
|
+
- Reply with the title alone. No quotes, no preamble, no explanation.`;
|
|
29
|
+
|
|
30
|
+
/** Longer than the model is asked for, so a slightly chatty answer is trimmed rather than lost. */
|
|
31
|
+
const HARD_LIMIT = 80;
|
|
32
|
+
|
|
33
|
+
export interface TitlerOptions {
|
|
34
|
+
/** The titler's own model; it is usually a cheaper one than the run's. */
|
|
35
|
+
model: Model | AgentLanguageModel;
|
|
36
|
+
/** Its own cache key, such as `title:<sessionId>`, so it does not evict the run's prompt. */
|
|
37
|
+
cacheKey?: string;
|
|
38
|
+
/** Prices over the model's own. */
|
|
39
|
+
pricing?: ModelPrices;
|
|
40
|
+
settings?: ModelCallSettings;
|
|
41
|
+
template?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface TitleSuggestion {
|
|
45
|
+
title: string;
|
|
46
|
+
usage: Usage;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Titler {
|
|
50
|
+
suggest(
|
|
51
|
+
messages: readonly ModelMessage[],
|
|
52
|
+
options?: { signal?: AbortSignal },
|
|
53
|
+
): Promise<TitleSuggestion | undefined>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createTitler(options: TitlerOptions): Titler {
|
|
57
|
+
const template = options.template ?? TITLE_TEMPLATE;
|
|
58
|
+
const model = toModel(options.model);
|
|
59
|
+
const pricing = options.pricing ?? model.pricing;
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
async suggest(messages, callOptions = {}) {
|
|
63
|
+
if (messages.length === 0) return undefined;
|
|
64
|
+
|
|
65
|
+
// Same boundary cast as the compactor: the SDK's option types are keyed
|
|
66
|
+
// on the shape of the call, so one cast keeps the rest of the file plain.
|
|
67
|
+
const request = {
|
|
68
|
+
model: model.languageModel,
|
|
69
|
+
system: template,
|
|
70
|
+
prompt: `Here is the exchange to name:\n\n${renderTranscript(messages)}`,
|
|
71
|
+
...withRequestFields(options.settings ?? {}, model.requestFields(options.cacheKey)),
|
|
72
|
+
// Budget covers reasoning too: a model that thinks first spends the
|
|
73
|
+
// allowance, and `text` comes back blank.
|
|
74
|
+
maxOutputTokens: 200,
|
|
75
|
+
...(callOptions.signal === undefined ? {} : { abortSignal: callOptions.signal }),
|
|
76
|
+
} as Parameters<typeof generateText>[0];
|
|
77
|
+
|
|
78
|
+
let generated;
|
|
79
|
+
try {
|
|
80
|
+
generated = await generateText(request);
|
|
81
|
+
} catch {
|
|
82
|
+
// A throw here would take down the turn the titler decorates.
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const title = cleanTitle(generated.text);
|
|
87
|
+
if (title === undefined) return undefined;
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
title,
|
|
91
|
+
usage: priceCall(normaliseUsage(generated.usage), pricing, {
|
|
92
|
+
providerUsage: (generated.usage as { raw?: unknown }).raw,
|
|
93
|
+
metadata: generated.providerMetadata,
|
|
94
|
+
}),
|
|
95
|
+
};
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The first line of the model's answer, minus quotes, a label such as `Title:`
|
|
102
|
+
* and trailing periods, or `undefined`. An empty answer or `unknown` gives
|
|
103
|
+
* `undefined`: a bad title is worse than the derived one it would replace.
|
|
104
|
+
*/
|
|
105
|
+
export function cleanTitle(raw: string): string | undefined {
|
|
106
|
+
const firstLine = raw.split("\n").find((line) => line.trim() !== "");
|
|
107
|
+
if (firstLine === undefined) return undefined;
|
|
108
|
+
|
|
109
|
+
const stripped = firstLine
|
|
110
|
+
.trim()
|
|
111
|
+
.replace(/^(?:title|session|name)\s*:\s*/i, "")
|
|
112
|
+
.replace(/^["'`]+|["'`]+$/g, "")
|
|
113
|
+
.replace(/[.\s]+$/, "")
|
|
114
|
+
.trim();
|
|
115
|
+
|
|
116
|
+
if (stripped === "") return undefined;
|
|
117
|
+
// The model's own way of saying it could not tell, and a real session could
|
|
118
|
+
// never be usefully called this.
|
|
119
|
+
if (stripped.toLowerCase() === "unknown") return undefined;
|
|
120
|
+
|
|
121
|
+
return stripped.length <= HARD_LIMIT ? stripped : `${stripped.slice(0, HARD_LIMIT - 1)}…`;
|
|
122
|
+
}
|