@kadaliao/dsh-bots 0.10.2 → 0.11.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 +99 -43
- package/README.zh-CN.md +70 -29
- package/client.js +568 -148
- package/index.js +394 -72
- package/lib/needs.mjs +400 -0
- package/lib/prompt.mjs +46 -10
- package/lib/settings.mjs +15 -5
- package/lib/team-migration.mjs +79 -0
- package/lib/teams-0.11.mjs +299 -0
- package/lib/teams.mjs +92 -92
- package/lib/watchdog.mjs +13 -0
- package/package.json +1 -1
package/lib/needs.mjs
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Needs (Bots 0.11): what the person asked for, one level above the tasks
|
|
3
|
+
* (tickets) that do the work. A need is one request in the person's own terms
|
|
4
|
+
* ("A comparison of Q3 competitor pricing"); the dispatcher names it when it
|
|
5
|
+
* hands out the work, in the person's language, and every task it opens for that
|
|
6
|
+
* request counts toward it. One need may take several tasks (research split
|
|
7
|
+
* between teammates, then a write-up), and several messages (the request, a
|
|
8
|
+
* change to it, "how is it going?"); a message may also hold two needs.
|
|
9
|
+
*
|
|
10
|
+
* A need stores only what a task does not know: its title, who asked where
|
|
11
|
+
* (`origin`), the person's words (`asks`), its tasks (top-level ones: a
|
|
12
|
+
* sub-task counts through the task that opened it) and whether the person
|
|
13
|
+
* dropped it (`closed`). Its status comes from its tasks' stages
|
|
14
|
+
* ({@link needStatus}); `snapshot` keeps the last one, for when the tasks are
|
|
15
|
+
* pruned.
|
|
16
|
+
*
|
|
17
|
+
* `needs.json` under the bots cache holds `{version: 1, needs}`. It is read on
|
|
18
|
+
* first use and written whole through a temp file and a rename; a missing file
|
|
19
|
+
* starts empty, one that is not JSON in the expected shape is set aside as
|
|
20
|
+
* `needs.json.corrupt-<time>` before the first write replaces it.
|
|
21
|
+
*
|
|
22
|
+
* @module @kadaliao/dsh-bots/lib/needs
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { randomInt } from 'node:crypto';
|
|
26
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
|
|
29
|
+
export const NEED_ID_RE = /^n[a-z0-9]{8}$/;
|
|
30
|
+
/** What a person sees a need as, most pressing first. */
|
|
31
|
+
export const NEED_STATUSES = ['waiting', 'working', 'failed', 'done', 'stopped'];
|
|
32
|
+
/** Longest title, in characters. */
|
|
33
|
+
export const MAX_NEED_TITLE = 80;
|
|
34
|
+
/** Longest piece of the person's words one need keeps. */
|
|
35
|
+
export const MAX_ASK = 2000;
|
|
36
|
+
/** The person's messages one need keeps; past this the oldest go (the first, the request itself, stays). */
|
|
37
|
+
export const KEEP_ASKS = 20;
|
|
38
|
+
/** Settled needs `prune` keeps by default. */
|
|
39
|
+
export const KEEP_SETTLED = 500;
|
|
40
|
+
|
|
41
|
+
const ALNUM = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
|
42
|
+
|
|
43
|
+
/** `n` and 8 random lowercase letters and digits. */
|
|
44
|
+
export function newNeedId() {
|
|
45
|
+
let id = 'n';
|
|
46
|
+
for (let i = 0; i < 8; i += 1) id += ALNUM[randomInt(ALNUM.length)];
|
|
47
|
+
return id;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One line of at most `max` characters (code points); a cut one ends with `…`. */
|
|
51
|
+
export function clampNeedTitle(text, max = MAX_NEED_TITLE) {
|
|
52
|
+
const s = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
53
|
+
const chars = [...s];
|
|
54
|
+
return chars.length <= max ? s : `${chars.slice(0, Math.max(0, max - 1)).join('').trimEnd()}…`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
58
|
+
const time = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : 0);
|
|
59
|
+
|
|
60
|
+
function normalizeAsk(raw) {
|
|
61
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
62
|
+
const text = str(raw.text, MAX_ASK).trim();
|
|
63
|
+
if (!text) return null;
|
|
64
|
+
return {
|
|
65
|
+
...(typeof raw.id === 'string' && raw.id ? { id: raw.id.slice(0, 200) } : {}),
|
|
66
|
+
at: time(raw.at),
|
|
67
|
+
text,
|
|
68
|
+
...(typeof raw.via === 'string' && raw.via ? { via: raw.via.slice(0, 40) } : {}),
|
|
69
|
+
...(typeof raw.who === 'string' && raw.who ? { who: raw.who.slice(0, 120) } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizeOrigin(raw) {
|
|
74
|
+
const o = raw && typeof raw === 'object' ? raw : {};
|
|
75
|
+
return {
|
|
76
|
+
...(typeof o.threadKey === 'string' && o.threadKey ? { threadKey: o.threadKey.slice(0, 500) } : {}),
|
|
77
|
+
...(typeof o.via === 'string' && o.via ? { via: o.via.slice(0, 40) } : {}),
|
|
78
|
+
...(typeof o.who === 'string' && o.who ? { who: o.who.slice(0, 120) } : {}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const SNAPSHOT_KEYS = ['status', 'done', 'total', 'failed', 'stalled'];
|
|
83
|
+
|
|
84
|
+
/** A stored need in its known shape, unknown fields kept; null when it is not one. */
|
|
85
|
+
export function normalizeNeed(raw) {
|
|
86
|
+
if (!raw || typeof raw !== 'object' || !NEED_ID_RE.test(String(raw.id ?? ''))) return null;
|
|
87
|
+
const title = clampNeedTitle(raw.title);
|
|
88
|
+
if (!title) return null;
|
|
89
|
+
const asks = (Array.isArray(raw.asks) ? raw.asks : []).map(normalizeAsk).filter(Boolean);
|
|
90
|
+
const tickets = [...new Set((Array.isArray(raw.tickets) ? raw.tickets : []).filter((t) => typeof t === 'string' && t))];
|
|
91
|
+
const createdAt = time(raw.createdAt) || Date.now();
|
|
92
|
+
const snap = raw.snapshot && typeof raw.snapshot === 'object' && NEED_STATUSES.includes(raw.snapshot.status) ? raw.snapshot : null;
|
|
93
|
+
return {
|
|
94
|
+
...raw,
|
|
95
|
+
id: raw.id,
|
|
96
|
+
title,
|
|
97
|
+
...(raw.auto === true ? { auto: true } : { auto: undefined }),
|
|
98
|
+
botId: typeof raw.botId === 'string' ? raw.botId : '',
|
|
99
|
+
origin: normalizeOrigin(raw.origin),
|
|
100
|
+
asks,
|
|
101
|
+
tickets,
|
|
102
|
+
createdAt,
|
|
103
|
+
updatedAt: time(raw.updatedAt) || createdAt,
|
|
104
|
+
...(raw.closed && typeof raw.closed === 'object' ? { closed: { at: time(raw.closed.at) || createdAt, by: raw.closed.by === 'user' ? 'user' : 'dispatcher' } } : { closed: undefined }),
|
|
105
|
+
...(NEED_ID_RE.test(String(raw.mergedInto ?? '')) ? { mergedInto: raw.mergedInto } : { mergedInto: undefined }),
|
|
106
|
+
...(snap ? { snapshot: Object.fromEntries([...SNAPSHOT_KEYS.map((k) => [k, k === 'status' ? snap.status : Math.max(0, Math.round(Number(snap[k]) || 0))]), ['at', time(snap.at)]]) } : { snapshot: undefined }),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* How far a need got, from its tasks (the top-level ones it lists, as stored; missing ones are left
|
|
112
|
+
* out). `stageOf` is lib/tickets.mjs's. The first row that matches wins:
|
|
113
|
+
*
|
|
114
|
+
* | status | when |
|
|
115
|
+
* | --------- | --------------------------------------------------------------------- |
|
|
116
|
+
* | `stopped` | the person (or the dispatcher, for them) dropped it |
|
|
117
|
+
* | `waiting` | a task asks a question, or is blocked, and nobody answered yet |
|
|
118
|
+
* | `working` | a task is open (queued, working, stalled) |
|
|
119
|
+
* | `done` | every task ended, and at least one is done |
|
|
120
|
+
* | `failed` | every task ended, none done, one failed |
|
|
121
|
+
* | `stopped` | every task ended stopped |
|
|
122
|
+
*
|
|
123
|
+
* With no task found (all pruned), the stored `snapshot` stands, else it is `working`.
|
|
124
|
+
* `failed` and `stalled` count tasks in those stages, so an open need can say "one failed".
|
|
125
|
+
* @param {object} need
|
|
126
|
+
* @param {object[]} tasks - its tickets, as found
|
|
127
|
+
* @param {(t: object) => string} stageOf
|
|
128
|
+
*/
|
|
129
|
+
export function needStatus(need, tasks, stageOf) {
|
|
130
|
+
const list = (Array.isArray(tasks) ? tasks : []).filter(Boolean);
|
|
131
|
+
const stages = list.map((t) => ({ t, stage: stageOf(t) }));
|
|
132
|
+
const count = (s) => stages.filter((x) => x.stage === s).length;
|
|
133
|
+
const done = count('done');
|
|
134
|
+
const failed = stages.filter((x) => x.stage === 'failed' && x.t.ended).length;
|
|
135
|
+
const stalled = count('stalled');
|
|
136
|
+
const waiting = stages.filter((x) => x.stage === 'question' || (x.stage === 'failed' && !x.t.ended));
|
|
137
|
+
const open = stages.filter((x) => !x.t.ended);
|
|
138
|
+
let status;
|
|
139
|
+
if (need?.closed) status = 'stopped';
|
|
140
|
+
else if (list.length === 0) status = need?.snapshot?.status ?? 'working';
|
|
141
|
+
else if (waiting.length) status = 'waiting';
|
|
142
|
+
else if (open.length) status = 'working';
|
|
143
|
+
else if (done) status = 'done';
|
|
144
|
+
else if (failed) status = 'failed';
|
|
145
|
+
else status = 'stopped';
|
|
146
|
+
const total = list.length || need?.snapshot?.total || 0;
|
|
147
|
+
const endedAt = list.length && open.length === 0 ? Math.max(...list.map((t) => time(t.ended?.at))) : 0;
|
|
148
|
+
return {
|
|
149
|
+
status,
|
|
150
|
+
done: list.length ? done : (need?.snapshot?.done ?? 0),
|
|
151
|
+
total,
|
|
152
|
+
failed,
|
|
153
|
+
stalled,
|
|
154
|
+
...(endedAt ? { endedAt } : {}),
|
|
155
|
+
// The tasks waiting for the person, so the board can say what they are asked.
|
|
156
|
+
waiting: waiting.map((x) => x.t.id),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The needs file under `dir`. Writes go through at once; `onChange(fn)` hears each one.
|
|
162
|
+
* @param {string} dir
|
|
163
|
+
* @param {{now?: () => number}} [opts]
|
|
164
|
+
*/
|
|
165
|
+
export function createNeeds(dir, { now = Date.now } = {}) {
|
|
166
|
+
const file = join(dir, 'needs.json');
|
|
167
|
+
/** @type {{version: 1, needs: object[]}|null} */
|
|
168
|
+
let data = null;
|
|
169
|
+
const byId = new Map();
|
|
170
|
+
const byTicket = new Map();
|
|
171
|
+
const listeners = new Set();
|
|
172
|
+
|
|
173
|
+
const setAside = () => {
|
|
174
|
+
try {
|
|
175
|
+
let to = `${file}.corrupt-${now()}`;
|
|
176
|
+
for (let n = 1; existsSync(to); n += 1) to = `${file}.corrupt-${now()}-${n}`;
|
|
177
|
+
renameSync(file, to);
|
|
178
|
+
} catch {
|
|
179
|
+
// It goes when the next write replaces it.
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const index = (n) => {
|
|
184
|
+
byId.set(n.id, n);
|
|
185
|
+
if (!n.mergedInto) for (const t of n.tickets) byTicket.set(t, n.id);
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const load = () => {
|
|
189
|
+
if (data) return data;
|
|
190
|
+
let parsed = null;
|
|
191
|
+
let text = null;
|
|
192
|
+
try {
|
|
193
|
+
text = readFileSync(file, 'utf8');
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error?.code !== 'ENOENT') throw new Error(`cannot read ${file} (${error?.code ?? error?.message ?? error}); fix or move it, needs are not loaded until then`, { cause: error });
|
|
196
|
+
}
|
|
197
|
+
if (text !== null) {
|
|
198
|
+
try {
|
|
199
|
+
parsed = JSON.parse(text);
|
|
200
|
+
} catch {
|
|
201
|
+
parsed = null;
|
|
202
|
+
}
|
|
203
|
+
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.needs)) {
|
|
204
|
+
parsed = null;
|
|
205
|
+
setAside();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
data = { version: 1, needs: [] };
|
|
209
|
+
for (const raw of parsed?.needs ?? []) {
|
|
210
|
+
const n = normalizeNeed(raw);
|
|
211
|
+
if (!n || byId.has(n.id)) continue;
|
|
212
|
+
data.needs.push(n);
|
|
213
|
+
index(n);
|
|
214
|
+
}
|
|
215
|
+
return data;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const save = () => {
|
|
219
|
+
try {
|
|
220
|
+
mkdirSync(dir, { recursive: true });
|
|
221
|
+
// A need quotes what the person said: readable by this user only.
|
|
222
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(data, (k, v) => (v === undefined ? undefined : v)), { encoding: 'utf8', mode: 0o600 });
|
|
223
|
+
renameSync(`${file}.tmp`, file);
|
|
224
|
+
} catch {
|
|
225
|
+
// Kept in memory; the next write tries again.
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const changed = (need) => {
|
|
230
|
+
save();
|
|
231
|
+
for (const fn of listeners) {
|
|
232
|
+
try {
|
|
233
|
+
fn(need);
|
|
234
|
+
} catch {
|
|
235
|
+
// A listener must not break a write.
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/** The need, following merges to the one that took it. */
|
|
241
|
+
const find = (id) => {
|
|
242
|
+
load();
|
|
243
|
+
let n = byId.get(String(id ?? '').trim().replace(/^need\//, ''));
|
|
244
|
+
for (let hops = 0; n?.mergedInto && hops < 8; hops += 1) n = byId.get(n.mergedInto) ?? n;
|
|
245
|
+
return n?.mergedInto ? undefined : n;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const addAsksTo = (n, asks) => {
|
|
249
|
+
let added = false;
|
|
250
|
+
for (const raw of asks ?? []) {
|
|
251
|
+
const a = normalizeAsk(raw);
|
|
252
|
+
if (!a) continue;
|
|
253
|
+
if (a.id ? n.asks.some((x) => x.id === a.id) : n.asks.some((x) => x.text === a.text && x.at === a.at)) continue;
|
|
254
|
+
n.asks.push(a);
|
|
255
|
+
added = true;
|
|
256
|
+
}
|
|
257
|
+
if (n.asks.length > KEEP_ASKS) n.asks = [n.asks[0], ...n.asks.slice(-(KEEP_ASKS - 1))];
|
|
258
|
+
return added;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
/** Every need not merged away, newest first. */
|
|
263
|
+
list() {
|
|
264
|
+
load();
|
|
265
|
+
return data.needs.filter((n) => !n.mergedInto).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
get: (id) => find(id),
|
|
269
|
+
|
|
270
|
+
/** The need a top-level ticket counts toward, if any. */
|
|
271
|
+
byTicket(ticketId) {
|
|
272
|
+
load();
|
|
273
|
+
const id = byTicket.get(String(ticketId ?? ''));
|
|
274
|
+
return id ? find(id) : undefined;
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* A new need. `title` is the request restated for the person; `auto` marks one the dispatcher did
|
|
279
|
+
* not name (its title is the person's own words, clipped).
|
|
280
|
+
* @param {{title: string, botId?: string, origin?: object, asks?: object[], tickets?: string[], auto?: boolean}} p
|
|
281
|
+
*/
|
|
282
|
+
create({ title, botId = '', origin = {}, asks = [], tickets = [], auto = false }) {
|
|
283
|
+
load();
|
|
284
|
+
const at = now();
|
|
285
|
+
let id = newNeedId();
|
|
286
|
+
while (byId.has(id)) id = newNeedId();
|
|
287
|
+
const n = normalizeNeed({ id, title, botId, origin, asks, tickets, createdAt: at, updatedAt: at, ...(auto ? { auto: true } : {}) });
|
|
288
|
+
if (!n) throw new Error('a need needs a title');
|
|
289
|
+
data.needs.push(n);
|
|
290
|
+
index(n);
|
|
291
|
+
changed(n);
|
|
292
|
+
return n;
|
|
293
|
+
},
|
|
294
|
+
|
|
295
|
+
/** Count a (top-level) ticket toward a need, with the person's words that came with it. */
|
|
296
|
+
addTicket(id, ticketId, asks = []) {
|
|
297
|
+
const n = find(id);
|
|
298
|
+
if (!n) return undefined;
|
|
299
|
+
const prev = byTicket.get(ticketId);
|
|
300
|
+
if (prev && prev !== n.id) {
|
|
301
|
+
const other = byId.get(prev);
|
|
302
|
+
if (other) other.tickets = other.tickets.filter((t) => t !== ticketId);
|
|
303
|
+
}
|
|
304
|
+
if (!n.tickets.includes(ticketId)) n.tickets.push(ticketId);
|
|
305
|
+
byTicket.set(ticketId, n.id);
|
|
306
|
+
addAsksTo(n, asks);
|
|
307
|
+
// Work handed out again makes a dropped need live again.
|
|
308
|
+
n.closed = undefined;
|
|
309
|
+
n.updatedAt = now();
|
|
310
|
+
changed(n);
|
|
311
|
+
return n;
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
/** The person said more about a need (a change, a follow-up): their words join it. */
|
|
315
|
+
addAsks(id, asks) {
|
|
316
|
+
const n = find(id);
|
|
317
|
+
if (!n || !addAsksTo(n, asks)) return n;
|
|
318
|
+
n.updatedAt = now();
|
|
319
|
+
changed(n);
|
|
320
|
+
return n;
|
|
321
|
+
},
|
|
322
|
+
|
|
323
|
+
rename(id, title) {
|
|
324
|
+
const n = find(id);
|
|
325
|
+
const next = clampNeedTitle(title);
|
|
326
|
+
if (!n || !next) return undefined;
|
|
327
|
+
n.title = next;
|
|
328
|
+
n.auto = undefined;
|
|
329
|
+
n.updatedAt = now();
|
|
330
|
+
changed(n);
|
|
331
|
+
return n;
|
|
332
|
+
},
|
|
333
|
+
|
|
334
|
+
/** `id`'s tasks and words go to `into`; `id` is then only a pointer to it. */
|
|
335
|
+
merge(id, into) {
|
|
336
|
+
const from = find(id);
|
|
337
|
+
const to = find(into);
|
|
338
|
+
if (!from || !to || from.id === to.id) return undefined;
|
|
339
|
+
for (const t of from.tickets) {
|
|
340
|
+
if (!to.tickets.includes(t)) to.tickets.push(t);
|
|
341
|
+
byTicket.set(t, to.id);
|
|
342
|
+
}
|
|
343
|
+
addAsksTo(to, from.asks);
|
|
344
|
+
to.asks.sort((a, b) => a.at - b.at);
|
|
345
|
+
to.createdAt = Math.min(to.createdAt, from.createdAt);
|
|
346
|
+
to.updatedAt = now();
|
|
347
|
+
from.mergedInto = to.id;
|
|
348
|
+
from.tickets = [];
|
|
349
|
+
from.updatedAt = now();
|
|
350
|
+
changed(to);
|
|
351
|
+
return to;
|
|
352
|
+
},
|
|
353
|
+
|
|
354
|
+
/** The person dropped it (their tasks are stopped by the caller). */
|
|
355
|
+
close(id, { by = 'dispatcher' } = {}) {
|
|
356
|
+
const n = find(id);
|
|
357
|
+
if (!n) return undefined;
|
|
358
|
+
n.closed = { at: now(), by: by === 'user' ? 'user' : 'dispatcher' };
|
|
359
|
+
n.updatedAt = now();
|
|
360
|
+
changed(n);
|
|
361
|
+
return n;
|
|
362
|
+
},
|
|
363
|
+
|
|
364
|
+
/** Keep the latest status (a write only when it changed). */
|
|
365
|
+
snapshot(id, s) {
|
|
366
|
+
const n = find(id);
|
|
367
|
+
if (!n || !s || !NEED_STATUSES.includes(s.status)) return n;
|
|
368
|
+
const prev = n.snapshot ?? {};
|
|
369
|
+
if (SNAPSHOT_KEYS.every((k) => prev[k] === s[k])) return n;
|
|
370
|
+
n.snapshot = { ...Object.fromEntries(SNAPSHOT_KEYS.map((k) => [k, s[k]])), at: now() };
|
|
371
|
+
n.updatedAt = now();
|
|
372
|
+
changed(n);
|
|
373
|
+
return n;
|
|
374
|
+
},
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Retention: keep the newest `keepSettled` needs that are done, failed or stopped (by their last
|
|
378
|
+
* change), drop older ones and merged pointers whose target went. Open needs are never dropped.
|
|
379
|
+
*/
|
|
380
|
+
prune({ keepSettled = KEEP_SETTLED } = {}) {
|
|
381
|
+
load();
|
|
382
|
+
const settled = data.needs.filter((n) => !n.mergedInto && ['done', 'failed', 'stopped'].includes(n.snapshot?.status ?? (n.closed ? 'stopped' : ''))).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
383
|
+
const drop = new Set(settled.slice(keepSettled).map((n) => n.id));
|
|
384
|
+
for (const n of data.needs) if (n.mergedInto && (drop.has(n.mergedInto) || !byId.has(n.mergedInto))) drop.add(n.id);
|
|
385
|
+
if (drop.size === 0) return 0;
|
|
386
|
+
data.needs = data.needs.filter((n) => !drop.has(n.id));
|
|
387
|
+
byId.clear();
|
|
388
|
+
byTicket.clear();
|
|
389
|
+
for (const n of data.needs) index(n);
|
|
390
|
+
changed(null);
|
|
391
|
+
return drop.size;
|
|
392
|
+
},
|
|
393
|
+
|
|
394
|
+
/** `fn(need)` after each write (`null` for a prune). Returns an unsubscribe. */
|
|
395
|
+
onChange(fn) {
|
|
396
|
+
listeners.add(fn);
|
|
397
|
+
return () => listeners.delete(fn);
|
|
398
|
+
},
|
|
399
|
+
};
|
|
400
|
+
}
|
package/lib/prompt.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What a bot's model reads: its persona section (
|
|
3
|
-
* dispatcher, or worker in a ticket session), the DM framing, the timing
|
|
2
|
+
* What a bot's model reads: its persona section (router dispatcher, a
|
|
3
|
+
* dispatcher working alone, or worker in a ticket session), the DM framing, the timing
|
|
4
4
|
* builder its schedule tool uses, and the router's tool limits. Pure
|
|
5
5
|
* functions, no Harness.
|
|
6
6
|
*
|
|
@@ -15,22 +15,52 @@ export function rosterLine(bot, selfId) {
|
|
|
15
15
|
return `- @${bot.handle} — ${bot.name}${tags.length ? ` (${tags.join(', ')})` : ''}${bot.bio ? `: ${bot.bio}` : ''}`;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* The roster as a bot reads it. Bots hired as a team (`teamNames`: team id → name) are listed under
|
|
20
|
+
* their team, so that with several teams hired the dispatcher still sees who belongs together; the
|
|
21
|
+
* dispatcher and bots of no team come first. Without teams it is one line per bot.
|
|
22
|
+
*/
|
|
23
|
+
export function rosterLines(roster, selfId, teamNames = {}) {
|
|
24
|
+
const named = (b) => b.role !== 'primary' && Boolean(teamNames[b.team]);
|
|
25
|
+
const lines = roster.filter((b) => !named(b)).map((b) => rosterLine(b, selfId));
|
|
26
|
+
for (const id of [...new Set(roster.filter(named).map((b) => b.team))]) {
|
|
27
|
+
lines.push(`- ${teamNames[id]}:`);
|
|
28
|
+
for (const b of roster.filter((x) => named(x) && x.team === id)) lines.push(` ${rosterLine(b, selfId)}`);
|
|
29
|
+
}
|
|
30
|
+
return lines;
|
|
31
|
+
}
|
|
32
|
+
|
|
18
33
|
const LANGUAGE_LINE = '- Write to the user in the language they use (Chinese or English). Between bots, use the language of the task you were given.';
|
|
19
34
|
const MANAGE_LINE = '- `bot_list` shows the team with each bot\'s skills and apps; `bot_create`, `bot_update` and `bot_delete` manage bots when the user asks for it or a new specialist is clearly needed.';
|
|
20
35
|
const SCHEDULE_NOTICE_LINE = '- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.';
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What a bot writes when a turn needs no words. Harness counts an answer with no content as a
|
|
39
|
+
* failed model call (`EMPTY_RESPONSE`, retried, then the turn fails), so "end your turn without a
|
|
40
|
+
* summary" must still leave text: this marker, which the plugin never shows or sends.
|
|
41
|
+
*/
|
|
42
|
+
export const NO_REPLY = 'NO_REPLY';
|
|
43
|
+
|
|
44
|
+
/** Whether a turn's text is the no-reply marker alone (any case, in backticks or with a full stop). */
|
|
45
|
+
export function isNoReply(text) {
|
|
46
|
+
return /^[\s`*_"']*no[_ ]reply[\s`*_"'.!]*$/i.test(String(text ?? ''));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const NO_REPLY_LINE = `- Never end a turn with an empty answer. When nothing needs saying (a notice, an acknowledgement, or after a tool already said it all), write only ${NO_REPLY}: it is never shown or sent.`;
|
|
21
50
|
const SCHEDULE_LINE = 'Use `bot_schedule` to give any bot (yourself included) recurring or timed tasks: the instruction is delivered to that bot\'s conversation at each occurrence.';
|
|
22
51
|
|
|
23
52
|
/** A team's dispatcher has no Harness sub-agents (Bots 0.10): parallel help is a teammate's task, which the person can follow. The other bots keep theirs. */
|
|
24
53
|
const teamHelpersLine = (router) =>
|
|
25
54
|
`- Your helpers are your teammates: as the dispatcher you have no Harness sub-agents (\`subagent\`, \`wait_agent\`, workflows). When a skill says to start sub-agents or parallel researchers, hand those parts to teammates with \`bot_send_message\` instead${router ? '' : ', or do them yourself one after another'}.`;
|
|
26
55
|
|
|
27
|
-
/** "Working with other bots" as a
|
|
56
|
+
/** "Working with other bots" as a dispatcher working alone reads it (the 0.7 text, from before tasks). */
|
|
28
57
|
const HANDS_ON_TEAM = [
|
|
29
58
|
'- Message another bot with `bot_send_message` (to: its @handle). It receives your text in its own conversation and works on it there; its answer comes back to you as a "Bot message from @…" message.',
|
|
30
59
|
'- A message that starts with "Bot message from @…" was sent by that bot, not by the user. Answer it with `bot_send_message` when it asks for something; do not answer pure acknowledgements or thanks, so conversations end.',
|
|
31
60
|
'- Keep messages self-contained: the other bot cannot see your conversation.',
|
|
32
|
-
'- When you are working on a bot message, your answer goes back through `bot_send_message`; after sending it, end your turn
|
|
61
|
+
'- When you are working on a bot message, your answer goes back through `bot_send_message`; after sending it, end your turn with only ' + NO_REPLY + ' — nobody reads a summary.',
|
|
33
62
|
SCHEDULE_NOTICE_LINE,
|
|
63
|
+
NO_REPLY_LINE,
|
|
34
64
|
LANGUAGE_LINE,
|
|
35
65
|
MANAGE_LINE,
|
|
36
66
|
];
|
|
@@ -41,6 +71,7 @@ const routerTeam = (self) => [
|
|
|
41
71
|
'- Keep messages self-contained: the bot cannot see this conversation.',
|
|
42
72
|
'- A message that starts with "Bot message from @…" was sent by that teammate, not by the person: teammates open no tasks for you, their messages come here. Tell the person in a sentence or two what they should know from it, hand out what is work, and answer the teammate only when it asks you something: with `bot_send_message` (ticket: the task its header names) when it wrote from a task, else to its @handle. Never answer acknowledgements or thanks.',
|
|
43
73
|
SCHEDULE_NOTICE_LINE,
|
|
74
|
+
NO_REPLY_LINE,
|
|
44
75
|
LANGUAGE_LINE,
|
|
45
76
|
MANAGE_LINE,
|
|
46
77
|
];
|
|
@@ -52,6 +83,7 @@ const HOME_TICKETS_TEAM = [
|
|
|
52
83
|
'- A message that starts with "Report from @…" or "Bot message from @…" was sent by that bot, not by the user. Pass a report\'s result on to whoever asked; a `question` or `blocked` report needs an answer with `bot_send_message` (ticket: its id).',
|
|
53
84
|
'- Keep messages self-contained: the other bot cannot see your conversation.',
|
|
54
85
|
SCHEDULE_NOTICE_LINE,
|
|
86
|
+
NO_REPLY_LINE,
|
|
55
87
|
LANGUAGE_LINE,
|
|
56
88
|
MANAGE_LINE,
|
|
57
89
|
];
|
|
@@ -62,6 +94,7 @@ const TICKET_TEAM = [
|
|
|
62
94
|
'- Keep messages self-contained: the other bot cannot see your conversation.',
|
|
63
95
|
'- A message that starts with "Bot message from @…" or "Report from @…" was sent by that bot, not by the user.',
|
|
64
96
|
SCHEDULE_NOTICE_LINE,
|
|
97
|
+
NO_REPLY_LINE,
|
|
65
98
|
LANGUAGE_LINE,
|
|
66
99
|
MANAGE_LINE,
|
|
67
100
|
];
|
|
@@ -102,9 +135,10 @@ function originPhrase(ticket) {
|
|
|
102
135
|
* bot's conversation only.
|
|
103
136
|
* @param {object} bot
|
|
104
137
|
* @param {object[]} roster - every bot, the bot itself included.
|
|
105
|
-
* @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[], dispatcher?: 'router'|'hands-on', tickets?: boolean, ticket?: object}} [extra]
|
|
138
|
+
* @param {{skillsInline?: boolean, apps?: string[], skillNames?: object, channels?: string[], dispatcher?: 'router'|'hands-on', tickets?: boolean, ticket?: object, teamNames?: object}} [extra]
|
|
106
139
|
* `channels`: chat apps the team is reachable from ('Telegram').
|
|
107
|
-
* `
|
|
140
|
+
* `teamNames`: team id → name, to list hired teams' bots under their team.
|
|
141
|
+
* `dispatcher`: how the dispatcher (role 'primary') works in its home conversation: 'router' (it has teammates) only understands, hands out and reports; 'hands-on' (default: it works alone) is the 0.7 text. Ignored for other bots.
|
|
108
142
|
* `tickets`: delegating from a home opens a task whose answer arrives as a report (router mode); a non-dispatcher bot's home then says so. Without it (hands-on) the 0.7 text stands.
|
|
109
143
|
* `ticket`: the ticket (see PLAN-0.8 §10) when this conversation is that ticket's session; the text then frames the conversation as one task, whatever the bot's role.
|
|
110
144
|
*/
|
|
@@ -118,7 +152,7 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
118
152
|
const others = roster.filter((b) => b.id !== bot.id);
|
|
119
153
|
lines.push('', '## The bot team');
|
|
120
154
|
lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
|
|
121
|
-
if (roster.length > 1)
|
|
155
|
+
if (roster.length > 1) lines.push(...rosterLines(roster, bot.id, extra.teamNames));
|
|
122
156
|
lines.push('', '## Working with other bots', ...(ticket ? TICKET_TEAM : router ? routerTeam(bot.handle) : homeTickets ? HOME_TICKETS_TEAM : HANDS_ON_TEAM));
|
|
123
157
|
if (others.length && bot.role === 'primary') lines.push(teamHelpersLine(router));
|
|
124
158
|
if (ticket) {
|
|
@@ -132,9 +166,9 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
132
166
|
? [
|
|
133
167
|
`- Your \`done\`, \`question\` and \`blocked\` reports are shown to the person as they are, ${shownWhere(ticket)}, and whoever asked is told. Write them for the person: the whole answer, in their language, nothing addressed to a bot. Their replies come back here.`,
|
|
134
168
|
'- To the person a report reads as you talking to them in the chat, so write it the way you would answer there: start with the answer itself, not with its status ("done", "finished", "here is the report"), and leave out task ids and how the work was handed around.',
|
|
135
|
-
'- Your plain text reaches no one: only reports do. Put everything the person needs in the report (nobody sees this conversation); after a `done` report, end your turn
|
|
169
|
+
'- Your plain text reaches no one: only reports do. Put everything the person needs in the report (nobody sees this conversation); after a `done` report, end your turn with only ' + NO_REPLY + '.',
|
|
136
170
|
]
|
|
137
|
-
: ['- Your plain text reaches no one: only reports do. Put everything the requester needs in the report (it cannot see this conversation); after a `done` report, end your turn
|
|
171
|
+
: ['- Your plain text reaches no one: only reports do. Put everything the requester needs in the report (it cannot see this conversation); after a `done` report, end your turn with only ' + NO_REPLY + '.']),
|
|
138
172
|
'- Asking another bot opens a sub-task; its report comes back here by itself.',
|
|
139
173
|
'- Messages from the person about this task may arrive here directly. Take them into account and answer them in a report.',
|
|
140
174
|
`- \`bot_recall\` reads this task (\`ticket/${ticket.id}\`), its parent and sub-tasks, and the threads it belongs to.`,
|
|
@@ -147,6 +181,8 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
147
181
|
'- Every message is its own request, unless it clearly continues one of the open tasks listed with it ("[Panel]" messages list them). When several messages arrive together, handle every one of them: never drop a request because another came after it.',
|
|
148
182
|
'- You put no question cards to the person: a card would hold every message after it until it is answered. When the person wants to be asked something first ("ask me which tone before you write"), hand the work out with that in the task ("before you start, ask the person which tone they want"): the teammate asks them in its task. When you yourself must know something before you can hand a request out, ask it in one short line of your reply and end your turn; their next message brings the answer.',
|
|
149
183
|
'- For each request do one of these, then end your turn: answer it yourself only from what you already know (a greeting, what the person means, the team, its tasks and what they already reported); hand it out with `bot_send_message` and tell the person in a sentence what happens next, as a colleague would in a chat ("@ledger is looking into it, back in a few minutes"); or, when it continues an open task, add it to that task with `bot_send_message` (ticket: its id).',
|
|
184
|
+
'- Each request of the person is a need: the panel shows them their needs and how far the work on each got. When you hand out work for a new request, pass `need` with it: the request restated for the person in one short line, in their language, saying what they get, not who does it or how ("A comparison of Q3 competitor pricing", not "@scout researches pricing"). Tasks for the same request share its need: pass the same line, or the need id the first call returned. For more work on a need listed under "Open needs", pass its id. Leave `need` out for work the person did not ask for.',
|
|
185
|
+
'- When the person drops a request ("forget the logo"), drop its need with `bot_need`: its open tasks stop. When two needs turn out to be one request, merge them; when the person changes what they want, rename it.',
|
|
150
186
|
'- Talk to the person like a person in a chat, in their language. Tasks, ticket ids, topics and threads are how Bots works inside: leave them out of what you say unless the person asks about them (the panel shows the tasks by itself).',
|
|
151
187
|
'- A conversation that starts with "[Thread]" is a thread: the person replies to one earlier message, and you see the conversation up to it, not what came after. Stay on that message; tasks you open there answer in the thread.',
|
|
152
188
|
'- Every delegation with `bot_send_message` opens a task (ticket) for that bot and returns at once. Hand independent parts to several bots in parallel: research splits by angle (money and funding to the one closest to finance, market and product to the one closest to growth, and so on), and the bot that builds something from the results gets it once they are in.',
|
|
@@ -163,7 +199,7 @@ export function personaText(bot, roster, extra = {}) {
|
|
|
163
199
|
'',
|
|
164
200
|
'## You are the dispatcher',
|
|
165
201
|
'The user treats you as the main bot. For a task that fits another bot\'s role, delegate it with `bot_send_message`, possibly to several bots in parallel, then combine their answers for the user. Do small or general tasks yourself. When no bot fits a recurring kind of work, propose creating one.',
|
|
166
|
-
'While teammates are still answering, stay quiet: when a reply arrives and others are still outstanding,
|
|
202
|
+
'While teammates are still answering, stay quiet: when a reply arrives and others are still outstanding, write only ' + NO_REPLY + ' instead of writing to the user. Report once, when everything you asked for is in (or when something is blocked).',
|
|
167
203
|
SCHEDULE_LINE,
|
|
168
204
|
);
|
|
169
205
|
}
|
package/lib/settings.mjs
CHANGED
|
@@ -13,8 +13,9 @@ import { join } from 'node:path';
|
|
|
13
13
|
|
|
14
14
|
export const DEFAULTS = Object.freeze({
|
|
15
15
|
/**
|
|
16
|
-
* How the dispatcher works in its home conversation:
|
|
17
|
-
*
|
|
16
|
+
* How the dispatcher works in its home conversation: it only understands, hands out (each
|
|
17
|
+
* delegation is a ticket with its own conversation) and reports. Always 'router' since 0.11: the
|
|
18
|
+
* 0.7 'hands-on' mode is gone, and a stored one reads as 'router' (with the one-time notice).
|
|
18
19
|
*/
|
|
19
20
|
dispatcher: 'router',
|
|
20
21
|
tickets: Object.freeze({
|
|
@@ -27,9 +28,16 @@ export const DEFAULTS = Object.freeze({
|
|
|
27
28
|
}),
|
|
28
29
|
/**
|
|
29
30
|
* The one-time panel notice that an upgraded team now runs in router mode: 'pending' until the
|
|
30
|
-
* user dismisses it
|
|
31
|
+
* user dismisses it, 'dismissed' after; null before the first run of 0.8 decided. A team still set
|
|
32
|
+
* to the old hands-on mode gets it (again) when it is moved to router mode (0.11).
|
|
31
33
|
*/
|
|
32
34
|
routerNotice: null,
|
|
35
|
+
/**
|
|
36
|
+
* The one-time panel notice that team templates lost their leads (0.11.1), shown while a team
|
|
37
|
+
* hired before still has a lead that is not the dispatcher: null until the user answers it,
|
|
38
|
+
* 'dismissed' after (whether the leads were removed or kept).
|
|
39
|
+
*/
|
|
40
|
+
leadNotice: null,
|
|
33
41
|
topics: Object.freeze({
|
|
34
42
|
/** A conversation quiet for this many hours starts a new topic before its next task; 0 = never. */
|
|
35
43
|
idleHours: 6,
|
|
@@ -108,13 +116,15 @@ export function normalizeSettings(input) {
|
|
|
108
116
|
}
|
|
109
117
|
const model = m.model && typeof m.model === 'object' && typeof m.model.provider === 'string' && m.model.provider && typeof m.model.model === 'string' && m.model.model ? { provider: m.model.provider.slice(0, 200), model: m.model.model.slice(0, 200) } : null;
|
|
110
118
|
return {
|
|
111
|
-
dispatcher:
|
|
119
|
+
dispatcher: 'router',
|
|
112
120
|
tickets: {
|
|
113
121
|
maxWorking: Math.round(num(tk.maxWorking, DEFAULTS.tickets.maxWorking, 1, 32)),
|
|
114
122
|
stallMinutes: Math.round(num(tk.stallMinutes, DEFAULTS.tickets.stallMinutes, 1, 24 * 60)),
|
|
115
123
|
archiveHours: num(tk.archiveHours, DEFAULTS.tickets.archiveHours, 0, 24 * 30),
|
|
116
124
|
},
|
|
117
|
-
|
|
125
|
+
// A team that had picked hands-on is told once that its dispatcher now only hands out the work.
|
|
126
|
+
routerNotice: s.dispatcher === 'hands-on' ? 'pending' : s.routerNotice === 'pending' || s.routerNotice === 'dismissed' ? s.routerNotice : null,
|
|
127
|
+
leadNotice: s.leadNotice === 'dismissed' ? 'dismissed' : null,
|
|
118
128
|
topics: {
|
|
119
129
|
idleHours: num(t.idleHours, DEFAULTS.topics.idleHours, 0, 24 * 30),
|
|
120
130
|
maxContextK: Math.round(num(t.maxContextK, DEFAULTS.topics.maxContextK, 0, 4096)),
|