@celljs/ta-recall 0.0.0-stage → 4.11.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.en.md +19 -0
- package/README.md +18 -2
- package/extension/index.mjs +614 -0
- package/host/index.mjs +820 -0
- package/package.json +53 -4
- package/web/index.js +1038 -0
package/README.en.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Cell - Ta Recall
|
|
2
|
+
|
|
3
|
+
A pi package that comes with Ta (on by default; Settings → Extensions of the web client turns it off): Recall. What was done stays: ask how it was done, keep what you ask for again as a skill, and get a brief each day.
|
|
4
|
+
|
|
5
|
+
- **Ask the past**: Ta has a tool `search_conversations({ query, days?, here? })` that searches what you and Ta said in the conversations of every directory (not the output of tools). Asked "how did we fix the relay last week", it searches first, then answers with links to the conversations, which open them. The search of Quick open gets a section Ask Ta: "Ask Ta: <what you typed>" asks in a new conversation, under it the conversations with every word.
|
|
6
|
+
- **Keep as a skill**: when you ask for something you asked for in another conversation, Ta does it, then drafts a skill with `propose_skill`, which shows as a card: its name, what it is for, its steps to unfold, Save as a skill or No thanks. Saved, it goes to `~/.ta/agent/skills/<name>/SKILL.md`, which new conversations use, or `/skill:<name>`; after No thanks the like is not offered again. + of the message box → Keep as a skill has Ta draft one of the conversation. A model without Ta's tools (another coding agent) drafts it in a `ta-skill` block, to the same effect.
|
|
7
|
+
- **Daily brief**: each day at its time (09:00 by default), when something happened since the last one, Ta writes in the conversation Daily brief what got done, what waits for you and what is next, each line linking its conversation. When the computer was off, one comes once the Ta service starts, one a day at most; the first comes at the next time after the package is installed.
|
|
8
|
+
|
|
9
|
+
Settings → Recall: the daily brief, its time, one written now, and the offers to keep a skill.
|
|
10
|
+
|
|
11
|
+
Sessions a package opened for a role of its own (an agent of a channel, a run of a schedule) are offered no skill.
|
|
12
|
+
|
|
13
|
+
## Data and calls
|
|
14
|
+
|
|
15
|
+
Data of the package (`@celljs/ta-recall`): `suggest`, `brief` (`{ enabled, time }`), `briefFile`, `briefLast`, `decided` (what was decided of each card), `declined` (the requests not wanted as skills).
|
|
16
|
+
|
|
17
|
+
Methods of its host (`pi.host`), which a web extension calls with `callPackageHost('@celljs/ta-recall', …)`: `search(query)`, `similar(text, piSessionId?)`, `saveSkill(key, draft)`, `declineSkill(key, ask?)`, `briefNow()`.
|
|
18
|
+
|
|
19
|
+
Design record: `docs/design/ta-recall.md`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Cell - Ta Recall
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 扩展 关闭):回顾。把做过的事留下来:问以前怎么做的、把常交代的事存成技能、每天一份简报。
|
|
4
|
+
|
|
5
|
+
- **问过去**:Ta 有一个工具 `search_conversations({ query, days?, here? })`,在所有目录的对话里搜你和 Ta 说过的话(不含工具输出),你问"上周 relay 那个 bug 怎么修的"时它先搜,再回答并链出对话;点链接打开那个对话。快捷打开的搜索里多一个"问 Ta"分区:"问 Ta:<你输入的>"新开一个对话去问,下面是包含所有关键词的对话。
|
|
6
|
+
- **存成技能**:你在另一个对话里交代过的事又交代一次时,Ta 做完后会用 `propose_skill` 起草一份技能,对话里出现一张卡片:名字、说明、可展开的步骤,"保存为技能"或"不用"。保存后写到 `~/.ta/agent/skills/<名字>/SKILL.md`,新对话自动用上,也可以 `/skill:<名字>`;"不用"之后类似的事不再问。输入框 + → 存成技能 让 Ta 把当前对话的做法起草成技能。没有 Ta 工具的模型(外部 Agent)用 `ta-skill` 代码块起草,效果一样。
|
|
7
|
+
- **每日简报**:每天到了设定时间(默认 09:00),如果上次以来有新动静,Ta 在"每日简报"对话里写:做完了什么、等你定什么、下一步,每条链到对话。电脑没开就在 Ta 服务启动后补一份,一天最多一份;第一次装上从下一个简报时间开始。
|
|
8
|
+
|
|
9
|
+
设置 → 回顾:每日简报开关、简报时间、现在写一份、建议存成技能开关。
|
|
10
|
+
|
|
11
|
+
由别的包打开、承担固定角色的会话(频道里的智能体、定时任务的运行)不建议存技能。
|
|
12
|
+
|
|
13
|
+
## 数据与调用
|
|
14
|
+
|
|
15
|
+
包数据(`@celljs/ta-recall`):`suggest`(是否建议存技能)、`brief`(`{ enabled, time }`)、`briefFile`(简报对话的会话文件)、`briefLast`(上次简报的时间)、`decided`(各卡片的保存或拒绝)、`declined`(拒绝过的请求)。
|
|
16
|
+
|
|
17
|
+
包宿主(`pi.host`)的方法,Web 扩展经 `callPackageHost('@celljs/ta-recall', …)` 调用:`search(query)`、`similar(text, piSessionId?)`、`saveSkill(key, draft)`、`declineSkill(key, ask?)`、`briefNow()`。
|
|
18
|
+
|
|
19
|
+
设计记录:`docs/design/ta-recall.md`。
|
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
// web-src/extension.ts
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
|
|
4
|
+
// ../ta-protocol/esm/common/ta-extension-host.js
|
|
5
|
+
var TA_HOST_EVENT = "ta:host";
|
|
6
|
+
var TaHostUtil;
|
|
7
|
+
(function(TaHostUtil2) {
|
|
8
|
+
TaHostUtil2.WAIT_MS = 1000;
|
|
9
|
+
function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
|
|
10
|
+
return new Promise((resolve) => {
|
|
11
|
+
const timer = setTimeout(() => resolve(undefined), waitMs);
|
|
12
|
+
const request = {
|
|
13
|
+
name,
|
|
14
|
+
resolve: (answer) => {
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
resolve(answer);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
events.emit(TA_HOST_EVENT, request);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
TaHostUtil2.reach = reach;
|
|
23
|
+
})(TaHostUtil || (TaHostUtil = {}));
|
|
24
|
+
|
|
25
|
+
// web-src/conversation-index.ts
|
|
26
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
|
|
29
|
+
// web-src/conversation-util.ts
|
|
30
|
+
var CONTEXT = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
|
|
31
|
+
var SKILL = /^<skill name="([^"]+)"[^>]*>[\s\S]*?<\/skill>\s*/;
|
|
32
|
+
var IMAGE_NOTE = /^\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]$|^\[Image converted from [^\]]+ to [^\]]+\.\]$/gm;
|
|
33
|
+
var TITLE_CHARS = 80;
|
|
34
|
+
var ConversationUtil;
|
|
35
|
+
((ConversationUtil) => {
|
|
36
|
+
function parse(file, content, agentDir) {
|
|
37
|
+
let header;
|
|
38
|
+
let name;
|
|
39
|
+
let group;
|
|
40
|
+
let updatedAt = 0;
|
|
41
|
+
const said = [];
|
|
42
|
+
for (const line of content.split(`
|
|
43
|
+
`)) {
|
|
44
|
+
if (!line || !header && !line.includes('"session"') || line.includes('"role":"toolResult"') || !(line.includes('"message"') || line.includes('"session') || line.includes('"custom"'))) {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
let entry;
|
|
48
|
+
try {
|
|
49
|
+
entry = JSON.parse(line);
|
|
50
|
+
} catch {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const at = Date.parse(entry.timestamp ?? "") || 0;
|
|
54
|
+
if (entry.type === "session") {
|
|
55
|
+
header = entry;
|
|
56
|
+
} else if (entry.type === "session_info" && typeof entry.name === "string") {
|
|
57
|
+
name = entry.name.trim() || undefined;
|
|
58
|
+
} else if (entry.type === "custom" && entry.customType === "ta-group" && typeof entry.data?.group === "string") {
|
|
59
|
+
group = entry.data.group;
|
|
60
|
+
} else if (entry.type === "message") {
|
|
61
|
+
const role = entry.message?.role;
|
|
62
|
+
if (role !== "user" && role !== "assistant") {
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const raw = textOf(entry.message?.content);
|
|
66
|
+
const text = role === "user" ? userText(raw) : raw;
|
|
67
|
+
updatedAt = Math.max(updatedAt, at);
|
|
68
|
+
if (text) {
|
|
69
|
+
said.push(role === "user" && CONTEXT.test(raw) ? { role, text, at, framed: true } : { role, text, at });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (!header) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const createdAt = Date.parse(header.timestamp ?? "") || 0;
|
|
77
|
+
const first = said.find((item) => item.role === "user")?.text.split(`
|
|
78
|
+
`)[0].trim();
|
|
79
|
+
return {
|
|
80
|
+
file,
|
|
81
|
+
cwd: cwdOf(header.cwd ?? "", agentDir),
|
|
82
|
+
title: (name ?? first ?? "").slice(0, TITLE_CHARS),
|
|
83
|
+
createdAt,
|
|
84
|
+
updatedAt: Math.max(updatedAt, createdAt),
|
|
85
|
+
...group ? { group } : {},
|
|
86
|
+
said
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
ConversationUtil.parse = parse;
|
|
90
|
+
function textOf(content) {
|
|
91
|
+
if (typeof content === "string") {
|
|
92
|
+
return content.trim();
|
|
93
|
+
}
|
|
94
|
+
if (!Array.isArray(content)) {
|
|
95
|
+
return "";
|
|
96
|
+
}
|
|
97
|
+
return content.flatMap((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
|
|
98
|
+
`).trim();
|
|
99
|
+
}
|
|
100
|
+
ConversationUtil.textOf = textOf;
|
|
101
|
+
function userText(content) {
|
|
102
|
+
const text = textOf(content).replace(CONTEXT, "").replace(IMAGE_NOTE, "");
|
|
103
|
+
const skill = SKILL.exec(text);
|
|
104
|
+
return (skill ? `/skill:${skill[1]} ${text.slice(skill[0].length)}` : text).trim();
|
|
105
|
+
}
|
|
106
|
+
ConversationUtil.userText = userText;
|
|
107
|
+
function cwdOf(cwd, agentDir) {
|
|
108
|
+
const mirror = `${agentDir.replace(/\/+$/, "")}/remote/ssh/`;
|
|
109
|
+
return cwd.startsWith(mirror) ? `ssh://${cwd.slice(mirror.length)}` : cwd;
|
|
110
|
+
}
|
|
111
|
+
ConversationUtil.cwdOf = cwdOf;
|
|
112
|
+
})(ConversationUtil ||= {});
|
|
113
|
+
|
|
114
|
+
// web-src/conversation-index.ts
|
|
115
|
+
class ConversationIndex {
|
|
116
|
+
agentDir;
|
|
117
|
+
kept = new Map;
|
|
118
|
+
reading;
|
|
119
|
+
constructor(agentDir) {
|
|
120
|
+
this.agentDir = agentDir;
|
|
121
|
+
}
|
|
122
|
+
get sessionsDir() {
|
|
123
|
+
return join(this.agentDir, "sessions");
|
|
124
|
+
}
|
|
125
|
+
all() {
|
|
126
|
+
this.reading ??= this.read().finally(() => {
|
|
127
|
+
this.reading = undefined;
|
|
128
|
+
});
|
|
129
|
+
return this.reading;
|
|
130
|
+
}
|
|
131
|
+
async read() {
|
|
132
|
+
const files = await this.files();
|
|
133
|
+
const seen = new Set;
|
|
134
|
+
const conversations = [];
|
|
135
|
+
await Promise.all(files.map(async (file) => {
|
|
136
|
+
seen.add(file);
|
|
137
|
+
const info = await stat(file).catch(() => {
|
|
138
|
+
return;
|
|
139
|
+
});
|
|
140
|
+
if (!info) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
let kept = this.kept.get(file);
|
|
144
|
+
if (!kept || kept.mtimeMs !== info.mtimeMs || kept.size !== info.size) {
|
|
145
|
+
const content = await readFile(file, "utf8").catch(() => {
|
|
146
|
+
return;
|
|
147
|
+
});
|
|
148
|
+
kept = {
|
|
149
|
+
mtimeMs: info.mtimeMs,
|
|
150
|
+
size: info.size,
|
|
151
|
+
conversation: content === undefined ? undefined : ConversationUtil.parse(file, content, this.agentDir)
|
|
152
|
+
};
|
|
153
|
+
this.kept.set(file, kept);
|
|
154
|
+
}
|
|
155
|
+
if (kept.conversation) {
|
|
156
|
+
conversations.push(kept.conversation);
|
|
157
|
+
}
|
|
158
|
+
}));
|
|
159
|
+
for (const file of this.kept.keys()) {
|
|
160
|
+
if (!seen.has(file)) {
|
|
161
|
+
this.kept.delete(file);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return conversations.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
165
|
+
}
|
|
166
|
+
async files() {
|
|
167
|
+
const root = this.sessionsDir;
|
|
168
|
+
const dirs = await readdir(root, { withFileTypes: true }).catch(() => []);
|
|
169
|
+
const lists = await Promise.all(dirs.filter((entry) => entry.isDirectory()).map(async (entry) => {
|
|
170
|
+
const names = await readdir(join(root, entry.name)).catch(() => []);
|
|
171
|
+
return names.filter((name) => name.endsWith(".jsonl")).map((name) => join(root, entry.name, name));
|
|
172
|
+
}));
|
|
173
|
+
return lists.flat();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// web-src/recall-protocol.ts
|
|
178
|
+
var NAME = "@celljs/ta-recall";
|
|
179
|
+
var TOOL_NAME = "search_conversations";
|
|
180
|
+
var PROPOSE_TOOL = "propose_skill";
|
|
181
|
+
var SKILL_TYPE = "ta-recall-skill";
|
|
182
|
+
var SKILL_BLOCK = "ta-skill";
|
|
183
|
+
var Keys;
|
|
184
|
+
((Keys) => {
|
|
185
|
+
Keys.SUGGEST = "suggest";
|
|
186
|
+
Keys.BRIEF = "brief";
|
|
187
|
+
Keys.BRIEF_FILE = "briefFile";
|
|
188
|
+
Keys.BRIEF_LAST = "briefLast";
|
|
189
|
+
Keys.ASKED = "asked";
|
|
190
|
+
Keys.BRIEF_SUMMARY = "briefSummary";
|
|
191
|
+
Keys.BRIEF_SEEN = "briefSeen";
|
|
192
|
+
Keys.BRIEF_PINNED = "briefPinned";
|
|
193
|
+
Keys.BRIEF_HANDLED = "briefHandled";
|
|
194
|
+
Keys.DECIDED = "decided";
|
|
195
|
+
Keys.DECLINED = "declined";
|
|
196
|
+
})(Keys ||= {});
|
|
197
|
+
var Limits;
|
|
198
|
+
((Limits) => {
|
|
199
|
+
Limits.SEARCH_DAYS = 30;
|
|
200
|
+
Limits.SEARCH_HITS = 8;
|
|
201
|
+
Limits.SNIPPETS = 3;
|
|
202
|
+
Limits.SNIPPET_CHARS = 240;
|
|
203
|
+
Limits.SIMILAR_DAYS = 60;
|
|
204
|
+
Limits.SIMILAR_MIN_CHARS = 16;
|
|
205
|
+
Limits.SIMILAR_SCORE = 0.5;
|
|
206
|
+
Limits.DECLINED_KEPT = 100;
|
|
207
|
+
Limits.ASKED_KEPT = 200;
|
|
208
|
+
Limits.BRIEF_CONVERSATIONS = 30;
|
|
209
|
+
Limits.BRIEF_ITEMS = 5;
|
|
210
|
+
Limits.ASKED_ARCHIVE_DAYS = 7;
|
|
211
|
+
})(Limits ||= {});
|
|
212
|
+
|
|
213
|
+
// web-src/search-util.ts
|
|
214
|
+
var DAY_MS = 24 * 60 * 60000;
|
|
215
|
+
var PAIRS_CHARS = 1000;
|
|
216
|
+
var SearchUtil;
|
|
217
|
+
((SearchUtil) => {
|
|
218
|
+
function terms(query) {
|
|
219
|
+
return [
|
|
220
|
+
...new Set(query.toLowerCase().split(/[\s,,、|]+/).filter((term) => term.length > 0))
|
|
221
|
+
].slice(0, 12);
|
|
222
|
+
}
|
|
223
|
+
SearchUtil.terms = terms;
|
|
224
|
+
function search(conversations, query, now = Date.now()) {
|
|
225
|
+
const words = terms(query.query);
|
|
226
|
+
if (words.length === 0) {
|
|
227
|
+
return [];
|
|
228
|
+
}
|
|
229
|
+
const since = now - (query.days ?? Limits.SEARCH_DAYS) * DAY_MS;
|
|
230
|
+
const hits = [];
|
|
231
|
+
for (const conversation of conversations) {
|
|
232
|
+
if (conversation.updatedAt < since || conversation.file === query.exclude || query.cwd && conversation.cwd !== query.cwd) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const found = new Set;
|
|
236
|
+
const places = [];
|
|
237
|
+
const title = conversation.title.toLowerCase();
|
|
238
|
+
for (const word of words) {
|
|
239
|
+
if (title.includes(word)) {
|
|
240
|
+
found.add(word);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
for (const said of conversation.said) {
|
|
244
|
+
const text = said.text.toLowerCase();
|
|
245
|
+
const has = words.filter((word) => text.includes(word));
|
|
246
|
+
if (has.length === 0 || query.all && has.length < words.length) {
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
for (const word of has) {
|
|
250
|
+
found.add(word);
|
|
251
|
+
}
|
|
252
|
+
places.push({ said, word: has[0] });
|
|
253
|
+
}
|
|
254
|
+
if (places.length === 0 && !(query.all ? words.every((word) => found.has(word)) : found.size > 0)) {
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
hits.push({
|
|
258
|
+
file: conversation.file,
|
|
259
|
+
cwd: conversation.cwd,
|
|
260
|
+
title: conversation.title,
|
|
261
|
+
updatedAt: conversation.updatedAt,
|
|
262
|
+
matched: found.size,
|
|
263
|
+
places: places.length,
|
|
264
|
+
snippets: places.slice(-Limits.SNIPPETS).map((place) => ({ role: place.said.role, at: place.said.at, text: snippet(place.said.text, place.word) }))
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return hits.sort((a, b) => b.matched - a.matched || Math.min(b.places, 5) - Math.min(a.places, 5) || b.updatedAt - a.updatedAt).slice(0, query.limit ?? Limits.SEARCH_HITS).map(({ places: _, ...hit }) => hit);
|
|
268
|
+
}
|
|
269
|
+
SearchUtil.search = search;
|
|
270
|
+
function snippet(text, word, chars = Limits.SNIPPET_CHARS) {
|
|
271
|
+
const line = text.replace(/\s+/g, " ").trim();
|
|
272
|
+
if (line.length <= chars) {
|
|
273
|
+
return line;
|
|
274
|
+
}
|
|
275
|
+
const at = Math.max(0, line.toLowerCase().indexOf(word));
|
|
276
|
+
const start = Math.max(0, Math.min(at - Math.floor(chars / 3), line.length - chars));
|
|
277
|
+
return `${start > 0 ? "…" : ""}${line.slice(start, start + chars).trim()}${start + chars < line.length ? "…" : ""}`;
|
|
278
|
+
}
|
|
279
|
+
SearchUtil.snippet = snippet;
|
|
280
|
+
})(SearchUtil ||= {});
|
|
281
|
+
var SimilarUtil;
|
|
282
|
+
((SimilarUtil) => {
|
|
283
|
+
function pairs(text) {
|
|
284
|
+
const flat = text.slice(0, PAIRS_CHARS).toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
|
|
285
|
+
const counts = new Map;
|
|
286
|
+
for (let index = 0;index < flat.length - 1; index++) {
|
|
287
|
+
const pair = flat.slice(index, index + 2);
|
|
288
|
+
counts.set(pair, (counts.get(pair) ?? 0) + 1);
|
|
289
|
+
}
|
|
290
|
+
return counts;
|
|
291
|
+
}
|
|
292
|
+
SimilarUtil.pairs = pairs;
|
|
293
|
+
function dice(a, b) {
|
|
294
|
+
let size = 0;
|
|
295
|
+
let shared = 0;
|
|
296
|
+
for (const count of a.values()) {
|
|
297
|
+
size += count;
|
|
298
|
+
}
|
|
299
|
+
for (const [pair, count] of b) {
|
|
300
|
+
size += count;
|
|
301
|
+
shared += Math.min(count, a.get(pair) ?? 0);
|
|
302
|
+
}
|
|
303
|
+
return size === 0 ? 0 : 2 * shared / size;
|
|
304
|
+
}
|
|
305
|
+
SimilarUtil.dice = dice;
|
|
306
|
+
function comparable(text) {
|
|
307
|
+
const trimmed = text.trim();
|
|
308
|
+
return trimmed.length >= Limits.SIMILAR_MIN_CHARS && !trimmed.startsWith("/");
|
|
309
|
+
}
|
|
310
|
+
SimilarUtil.comparable = comparable;
|
|
311
|
+
function find(text, conversations, options = {}) {
|
|
312
|
+
if (!comparable(text)) {
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
const mine = pairs(text);
|
|
316
|
+
if ((options.declined ?? []).some((declined) => dice(mine, pairs(declined)) >= Limits.SIMILAR_SCORE)) {
|
|
317
|
+
return [];
|
|
318
|
+
}
|
|
319
|
+
const since = (options.now ?? Date.now()) - Limits.SIMILAR_DAYS * DAY_MS;
|
|
320
|
+
const exclude = new Set(options.exclude ?? []);
|
|
321
|
+
const found = [];
|
|
322
|
+
for (const conversation of conversations) {
|
|
323
|
+
if (conversation.group || exclude.has(conversation.file) || conversation.updatedAt < since) {
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
let best;
|
|
327
|
+
for (const said of conversation.said) {
|
|
328
|
+
if (said.role !== "user" || said.framed || said.at < since || !comparable(said.text)) {
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
const score = dice(mine, pairs(said.text));
|
|
332
|
+
if (score >= Limits.SIMILAR_SCORE && (!best || score > best.score)) {
|
|
333
|
+
best = { file: conversation.file, title: conversation.title, text: said.text, at: said.at, score };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (best) {
|
|
337
|
+
found.push(best);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return found.sort((a, b) => b.score - a.score).slice(0, 3).map(({ score: _, ...ask }) => ask);
|
|
341
|
+
}
|
|
342
|
+
SimilarUtil.find = find;
|
|
343
|
+
})(SimilarUtil ||= {});
|
|
344
|
+
|
|
345
|
+
// web-src/skill-util.ts
|
|
346
|
+
var FENCE = "```";
|
|
347
|
+
var NAME_CHARS = 64;
|
|
348
|
+
var DESCRIPTION_CHARS = 1024;
|
|
349
|
+
var SkillUtil;
|
|
350
|
+
((SkillUtil) => {
|
|
351
|
+
function find(text) {
|
|
352
|
+
const lines = text.split(/\r?\n/);
|
|
353
|
+
let found;
|
|
354
|
+
for (let index = 0;index < lines.length; index++) {
|
|
355
|
+
const open = /^\s*(`{3,})\s*([\w-]+)\s*$/.exec(lines[index]);
|
|
356
|
+
if (open?.[2] !== SKILL_BLOCK) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const close = new RegExp(`^\\s*${open[1]}\`*\\s*$`);
|
|
360
|
+
const end = lines.findIndex((line, at) => at > index && close.test(line));
|
|
361
|
+
found = lines.slice(index + 1, end < 0 ? lines.length : end);
|
|
362
|
+
index = end < 0 ? lines.length : end;
|
|
363
|
+
}
|
|
364
|
+
return found && parse(found);
|
|
365
|
+
}
|
|
366
|
+
SkillUtil.find = find;
|
|
367
|
+
function parse(lines) {
|
|
368
|
+
const rule = lines.findIndex((line) => line.trim() === "---");
|
|
369
|
+
const head = rule < 0 ? [] : lines.slice(0, rule);
|
|
370
|
+
const body = lines.slice(rule + 1).join(`
|
|
371
|
+
`).trim();
|
|
372
|
+
if (!body) {
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const field = (key) => head.map((line) => new RegExp(`^\\s*${key}\\s*:\\s*(.*)$`, "i").exec(line)?.[1].trim().replace(/^["'](.*)["']$/, "$1")).find((value) => value !== undefined);
|
|
376
|
+
const description = (field("description") ?? "").replace(/\s+/g, " ").slice(0, DESCRIPTION_CHARS);
|
|
377
|
+
return { name: name(field("name") ?? "") || name(description) || "skill", description, body };
|
|
378
|
+
}
|
|
379
|
+
function name(text) {
|
|
380
|
+
return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, NAME_CHARS).replace(/-+$/, "");
|
|
381
|
+
}
|
|
382
|
+
SkillUtil.name = name;
|
|
383
|
+
function check(draft) {
|
|
384
|
+
const body = typeof draft?.body === "string" ? draft.body.trim() : "";
|
|
385
|
+
if (!body) {
|
|
386
|
+
throw new Error("A skill needs a body.");
|
|
387
|
+
}
|
|
388
|
+
const description = (typeof draft.description === "string" ? draft.description : "").replace(/\s+/g, " ").trim().slice(0, DESCRIPTION_CHARS);
|
|
389
|
+
return { name: name(typeof draft.name === "string" ? draft.name : "") || "skill", description: description || body.split(`
|
|
390
|
+
`)[0].slice(0, 200), body };
|
|
391
|
+
}
|
|
392
|
+
SkillUtil.check = check;
|
|
393
|
+
function markdown(draft) {
|
|
394
|
+
return `---
|
|
395
|
+
name: ${draft.name}
|
|
396
|
+
description: ${JSON.stringify(draft.description)}
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
${draft.body.trim()}
|
|
400
|
+
`;
|
|
401
|
+
}
|
|
402
|
+
SkillUtil.markdown = markdown;
|
|
403
|
+
function blockHelp() {
|
|
404
|
+
return [
|
|
405
|
+
`${FENCE}${SKILL_BLOCK}`,
|
|
406
|
+
"name: <lowercase-words-with-dashes>",
|
|
407
|
+
"description: <one line: what it does and when to use it>",
|
|
408
|
+
"---",
|
|
409
|
+
"<the body: the goal, then the steps, commands, files and checks that worked, in general terms, without what held only this once>",
|
|
410
|
+
FENCE,
|
|
411
|
+
"Use a longer fence when the body has fences of its own. Write it in the language of the user."
|
|
412
|
+
].join(`
|
|
413
|
+
`);
|
|
414
|
+
}
|
|
415
|
+
SkillUtil.blockHelp = blockHelp;
|
|
416
|
+
function hint(asks) {
|
|
417
|
+
const lines = asks.map((ask2) => `- "${ask2.title}" (${new Date(ask2.at).toISOString().slice(0, 10)}): ${JSON.stringify(ask2.text.replace(/\s+/g, " ").slice(0, 200))}`);
|
|
418
|
+
return [
|
|
419
|
+
"The user asked for much the same in other conversations before:",
|
|
420
|
+
...lines,
|
|
421
|
+
`Do what is asked first. Then, if it is a way of working worth doing the same way again (steps, commands, checks; not a one-off answer), offer to keep it as a skill in one short sentence and draft it with ${PROPOSE_TOOL}, which Ta shows as a card the user saves with a tap. Without that tool, end your answer with the draft in a fenced block of the language ${SKILL_BLOCK} instead:`,
|
|
422
|
+
blockHelp(),
|
|
423
|
+
"Offer nothing when it is not worth keeping."
|
|
424
|
+
].join(`
|
|
425
|
+
`);
|
|
426
|
+
}
|
|
427
|
+
SkillUtil.hint = hint;
|
|
428
|
+
function ask(language) {
|
|
429
|
+
const context = [
|
|
430
|
+
"[ta-recall:skill]",
|
|
431
|
+
"The user wants the way of working of this conversation kept as a skill of Ta, which Ta loads in every new conversation: written so that one who never saw this conversation does it the same way.",
|
|
432
|
+
"- Keep what worked: the goal, the steps, the commands, files, checks and pitfalls; leave out what was only tried and dropped and what holds only this once.",
|
|
433
|
+
`- Draft it with ${PROPOSE_TOOL}, which Ta shows as a card the user saves, and say in a line what it does; do not write the skill file yourself. Without that tool, end your answer with the draft in a fenced block of the language ${SKILL_BLOCK}:`,
|
|
434
|
+
blockHelp(),
|
|
435
|
+
"- When the conversation holds no way of working worth keeping, say so and draft nothing."
|
|
436
|
+
].join(`
|
|
437
|
+
`);
|
|
438
|
+
return `<context>
|
|
439
|
+
${context}
|
|
440
|
+
</context>
|
|
441
|
+
${/^zh/i.test(language) ? "把这个对话里的做法存成技能" : "Keep how this was done as a skill"}`;
|
|
442
|
+
}
|
|
443
|
+
SkillUtil.ask = ask;
|
|
444
|
+
})(SkillUtil ||= {});
|
|
445
|
+
|
|
446
|
+
// web-src/tool.ts
|
|
447
|
+
var RecallTool;
|
|
448
|
+
((RecallTool) => {
|
|
449
|
+
RecallTool.NAME = TOOL_NAME;
|
|
450
|
+
RecallTool.DEFINITION = {
|
|
451
|
+
name: RecallTool.NAME,
|
|
452
|
+
label: "Search conversations",
|
|
453
|
+
description: "Searches the user's earlier conversations with Ta, in every directory: what they asked, what was answered, done and decided. Returns the conversations with the most of the words, newest first among equals, each with its title, directory, date, session file and a few places. A session file is JSON lines that read can open for more.",
|
|
454
|
+
promptSnippet: "Search the user's earlier conversations with Ta (what was asked, done and decided)",
|
|
455
|
+
promptGuidelines: [
|
|
456
|
+
"When the user asks about earlier work (how something was fixed, what was decided, where it was left), search the conversations with search_conversations, and git history when it is code, before answering; link the conversations you use as [title](session file)."
|
|
457
|
+
],
|
|
458
|
+
parameters: {
|
|
459
|
+
type: "object",
|
|
460
|
+
properties: {
|
|
461
|
+
query: {
|
|
462
|
+
type: "string",
|
|
463
|
+
description: "Words separated by spaces, a conversation having more of them first: names, errors, files, and the same thing in the other language the user may have used (relay 重连 reconnect)."
|
|
464
|
+
},
|
|
465
|
+
days: { type: "number", description: `How many days back; default ${Limits.SEARCH_DAYS}.` },
|
|
466
|
+
here: { type: "boolean", description: "Only the conversations of this directory." }
|
|
467
|
+
},
|
|
468
|
+
required: ["query"]
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
function result(hits, days) {
|
|
472
|
+
if (hits.length === 0) {
|
|
473
|
+
return `No conversation of the last ${days} days has these words. Try other words, the other language, more days, or git log -S.`;
|
|
474
|
+
}
|
|
475
|
+
const lines = hits.map((hit, index) => {
|
|
476
|
+
const places = hit.snippets.map((place) => ` - ${place.role === "user" ? "user" : "Ta"}, ${date(place.at)}: ${place.text}`);
|
|
477
|
+
return [`${index + 1}. [${hit.title || "Untitled"}](${hit.file}) · ${hit.cwd} · ${date(hit.updatedAt)}`, ...places].join(`
|
|
478
|
+
`);
|
|
479
|
+
});
|
|
480
|
+
return [...lines, "", "Read a session file for more. Link the conversations you use as [title](session file)."].join(`
|
|
481
|
+
`);
|
|
482
|
+
}
|
|
483
|
+
RecallTool.result = result;
|
|
484
|
+
function date(at) {
|
|
485
|
+
return at ? new Date(at).toISOString().slice(0, 16).replace("T", " ") : "";
|
|
486
|
+
}
|
|
487
|
+
})(RecallTool ||= {});
|
|
488
|
+
var ProposeTool;
|
|
489
|
+
((ProposeTool) => {
|
|
490
|
+
ProposeTool.NAME = PROPOSE_TOOL;
|
|
491
|
+
ProposeTool.DEFINITION = {
|
|
492
|
+
name: ProposeTool.NAME,
|
|
493
|
+
label: "Propose skill",
|
|
494
|
+
description: "Offers the user to keep a way of working as a skill of Ta, which Ta loads in every new conversation. The draft shows in this conversation as a card once your turn ends, with Save and No thanks; nothing is written until the user saves it. Write it so that one who never saw this conversation does it the same way.",
|
|
495
|
+
promptSnippet: "Offer to keep a way of working as a skill the user saves from a card",
|
|
496
|
+
promptGuidelines: ["When the user asks to keep how something is done as a skill, draft it with propose_skill rather than writing a SKILL.md yourself."],
|
|
497
|
+
parameters: {
|
|
498
|
+
type: "object",
|
|
499
|
+
properties: {
|
|
500
|
+
name: { type: "string", description: "Lowercase words with dashes, as weekly-deps-upgrade." },
|
|
501
|
+
description: { type: "string", description: "One line in the language of the user: what it does and when to use it." },
|
|
502
|
+
body: {
|
|
503
|
+
type: "string",
|
|
504
|
+
description: "Markdown in the language of the user: the goal, then the steps, commands, files, checks and pitfalls that worked, in general terms, without what held only this once."
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
required: ["name", "description", "body"]
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
ProposeTool.RESULT = "The draft shows as a card when your turn ends; the user saves it or not. Say in one short sentence what the skill does, and end your turn.";
|
|
511
|
+
})(ProposeTool ||= {});
|
|
512
|
+
|
|
513
|
+
// web-src/extension.ts
|
|
514
|
+
var BRIEF_MARK = "[ta-recall:brief]";
|
|
515
|
+
var REPEAT_SECTION = "ta-recall-repeat";
|
|
516
|
+
function activate(pi) {
|
|
517
|
+
let reached;
|
|
518
|
+
const reach = () => reached ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer && { service: answer.service, agentDir: answer.host.agentDir });
|
|
519
|
+
let local;
|
|
520
|
+
let asked;
|
|
521
|
+
let draft;
|
|
522
|
+
let briefing = false;
|
|
523
|
+
pi.on("session_start", () => {
|
|
524
|
+
reach();
|
|
525
|
+
});
|
|
526
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
527
|
+
asked = undefined;
|
|
528
|
+
draft = undefined;
|
|
529
|
+
briefing = false;
|
|
530
|
+
if (event.messageType === "custom" || typeof event.prompt !== "string") {
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (event.prompt.includes(BRIEF_MARK)) {
|
|
534
|
+
briefing = true;
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
const text = ConversationUtil.userText(event.prompt);
|
|
538
|
+
asked = text;
|
|
539
|
+
try {
|
|
540
|
+
const similar = await (await reach())?.service?.similar(text, ctx.sessionManager.getSessionId()) ?? [];
|
|
541
|
+
if (similar.length) {
|
|
542
|
+
event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, [REPEAT_SECTION]: SkillUtil.hint(similar) };
|
|
543
|
+
}
|
|
544
|
+
return;
|
|
545
|
+
} catch (error) {
|
|
546
|
+
console.error("ta-recall could not compare the request:", error);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
});
|
|
550
|
+
pi.on("context", (event) => {
|
|
551
|
+
const messages = event.messages.filter((message) => !(message.role === "custom" && message.customType === SKILL_TYPE));
|
|
552
|
+
return messages.length === event.messages.length ? undefined : { messages };
|
|
553
|
+
});
|
|
554
|
+
pi.on("agent_end", (event, ctx) => {
|
|
555
|
+
const answer = [...event.messages ?? []].reverse().find((message) => message.role === "assistant");
|
|
556
|
+
const found = answer && answer.stopReason !== "aborted" ? SkillUtil.find(ConversationUtil.textOf(answer.content)) : undefined;
|
|
557
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
558
|
+
if (briefing && answer && answer.stopReason !== "aborted" && file) {
|
|
559
|
+
const text = ConversationUtil.textOf(answer.content);
|
|
560
|
+
reach().then((reached2) => reached2?.service?.keepBrief(file, text)).catch((error) => console.error("ta-recall could not keep the brief:", error));
|
|
561
|
+
}
|
|
562
|
+
if (found && !draft) {
|
|
563
|
+
draft = { key: `${ctx.sessionManager.getSessionId()}:${Date.now()}`, draft: found, ...asked ? { ask: asked } : {} };
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
pi.on("agent_settled", (event) => {
|
|
567
|
+
const card = draft;
|
|
568
|
+
draft = undefined;
|
|
569
|
+
if (card && !event.aborted) {
|
|
570
|
+
pi.sendMessage({ customType: SKILL_TYPE, content: card.draft.name, display: true, details: card }, { triggerTurn: false });
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
const search = async (query, ctx) => {
|
|
574
|
+
const answer = await reach();
|
|
575
|
+
if (answer?.service) {
|
|
576
|
+
return answer.service.search(query);
|
|
577
|
+
}
|
|
578
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
579
|
+
if (!file) {
|
|
580
|
+
throw new Error("This session keeps no file, so the conversations of before are not known here.");
|
|
581
|
+
}
|
|
582
|
+
local ??= new ConversationIndex(dirname(dirname(dirname(file))));
|
|
583
|
+
return SearchUtil.search(await local.all(), query);
|
|
584
|
+
};
|
|
585
|
+
pi.registerTool({
|
|
586
|
+
...ProposeTool.DEFINITION,
|
|
587
|
+
execute: async (_id, params, _signal, _update, ctx) => {
|
|
588
|
+
const checked = SkillUtil.check({
|
|
589
|
+
name: String(params?.name ?? ""),
|
|
590
|
+
description: String(params?.description ?? ""),
|
|
591
|
+
body: typeof params?.body === "string" ? params.body : ""
|
|
592
|
+
});
|
|
593
|
+
draft = { key: `${ctx.sessionManager.getSessionId()}:${Date.now()}`, draft: checked, ...asked ? { ask: asked } : {} };
|
|
594
|
+
return { content: [{ type: "text", text: ProposeTool.RESULT }], details: { name: checked.name } };
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
pi.registerTool({
|
|
598
|
+
...RecallTool.DEFINITION,
|
|
599
|
+
execute: async (_id, params, _signal, _update, ctx) => {
|
|
600
|
+
const query = typeof params?.query === "string" ? params.query.trim() : "";
|
|
601
|
+
if (!query) {
|
|
602
|
+
throw new Error("Say what to search for in query: words separated by spaces.");
|
|
603
|
+
}
|
|
604
|
+
const days = typeof params.days === "number" && params.days > 0 ? Math.min(Math.round(params.days), 3650) : Limits.SEARCH_DAYS;
|
|
605
|
+
const agentDir = (await reach())?.agentDir;
|
|
606
|
+
const cwd = params.here === true ? agentDir ? ConversationUtil.cwdOf(ctx.cwd, agentDir) : ctx.cwd : undefined;
|
|
607
|
+
const hits = await search({ query, days, cwd, exclude: ctx.sessionManager.getSessionFile() }, ctx);
|
|
608
|
+
return { content: [{ type: "text", text: RecallTool.result(hits, days) }], details: { count: hits.length } };
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
export {
|
|
613
|
+
activate as default
|
|
614
|
+
};
|