@oyasmi/pipiclaw 0.8.9-beta.1 → 0.8.9-beta.2
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 +8 -3
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +3 -2
- package/dist/agent/effect-ledger.d.ts +11 -0
- package/dist/agent/effect-ledger.js +42 -0
- package/dist/agent/job-manager.d.ts +90 -13
- package/dist/agent/job-manager.js +235 -20
- package/dist/agent/prompt/sections.js +11 -2
- package/dist/agent/prompt/types.d.ts +7 -1
- package/dist/agent/runner-factory.d.ts +7 -0
- package/dist/agent/session-events.js +20 -1
- package/dist/index.d.ts +1 -1
- package/dist/log.d.ts +6 -0
- package/dist/log.js +12 -0
- package/dist/memory/consolidation.d.ts +5 -0
- package/dist/memory/consolidation.js +35 -147
- package/dist/memory/extraction.d.ts +45 -0
- package/dist/memory/extraction.js +227 -0
- package/dist/memory/lifecycle.js +5 -0
- package/dist/memory/maintenance-jobs.js +7 -0
- package/dist/memory/post-turn-review.d.ts +3 -1
- package/dist/memory/post-turn-review.js +20 -189
- package/dist/memory/recall.d.ts +0 -1
- package/dist/memory/recall.js +135 -77
- package/dist/memory/sidecar-worker.d.ts +7 -0
- package/dist/memory/sidecar-worker.js +23 -5
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/background-jobs.md +40 -0
- package/dist/playbooks/catalog.d.ts +1 -7
- package/dist/playbooks/catalog.js +4 -14
- package/dist/playbooks/event-scheduling.md +8 -4
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +45 -0
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-closeout.md +1 -1
- package/dist/playbooks/task-delegation.md +10 -4
- package/dist/playbooks/task-driving.md +52 -18
- package/dist/playbooks/task-planning.md +43 -18
- package/dist/runtime/bootstrap.js +24 -3
- package/dist/runtime/channel-context.d.ts +33 -0
- package/dist/runtime/dingtalk.d.ts +22 -2
- package/dist/runtime/dingtalk.js +141 -0
- package/dist/runtime/durable-dispatch.d.ts +10 -0
- package/dist/runtime/durable-dispatch.js +42 -1
- package/dist/runtime/event-validation.d.ts +48 -0
- package/dist/runtime/event-validation.js +81 -0
- package/dist/runtime/events.d.ts +17 -8
- package/dist/runtime/events.js +96 -22
- package/dist/runtime/store.d.ts +1 -1
- package/dist/runtime/task-driver.d.ts +5 -0
- package/dist/runtime/task-driver.js +38 -12
- package/dist/settings.d.ts +11 -0
- package/dist/settings.js +12 -0
- package/dist/shared/recoverable-error.d.ts +26 -0
- package/dist/shared/recoverable-error.js +29 -0
- package/dist/shared/task-ledger.d.ts +9 -7
- package/dist/shared/task-ledger.js +1 -1
- package/dist/subagents/builtin/explorer.md +16 -0
- package/dist/subagents/builtin/researcher.md +17 -0
- package/dist/subagents/builtin/verifier.md +17 -0
- package/dist/subagents/discovery.d.ts +17 -3
- package/dist/subagents/discovery.js +88 -15
- package/dist/subagents/tool.d.ts +21 -1
- package/dist/subagents/tool.js +140 -12
- package/dist/tasks/transitions.js +3 -2
- package/dist/tools/bash.d.ts +2 -0
- package/dist/tools/bash.js +18 -5
- package/dist/tools/event-manage.js +28 -77
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/job.js +2 -2
- package/dist/tools/memory-manage.js +0 -1
- package/dist/tools/registry.d.ts +29 -8
- package/dist/tools/registry.js +39 -22
- package/dist/tools/send-media.d.ts +28 -0
- package/dist/tools/send-media.js +88 -0
- package/dist/tools/task-manage/create.js +5 -4
- package/dist/tools/task-manage/lifecycle.js +12 -11
- package/dist/tools/task-manage/schema.js +2 -1
- package/dist/tools/task-manage/shared.js +13 -12
- package/dist/tools/task-manage/verification.js +14 -13
- package/dist/tools/tool-details.d.ts +44 -0
- package/dist/tools/tool-details.js +62 -0
- package/dist/tui/app.js +2 -0
- package/dist/tui/terminal-media-sender.d.ts +9 -0
- package/dist/tui/terminal-media-sender.js +15 -0
- package/package.json +2 -2
- package/dist/playbooks/task-recurring.md +0 -44
- package/dist/playbooks/task-repair.md +0 -45
package/dist/memory/recall.js
CHANGED
|
@@ -22,12 +22,23 @@ const TOKEN_PART_REGEX = /[\p{Script=Han}]+|[\p{L}\p{N}_./-]+/gu;
|
|
|
22
22
|
const ASCII_SPLIT_REGEX = /[._/-]+/g;
|
|
23
23
|
/** Automatic-context share for relevant memory recall (spec 026 §5.3). */
|
|
24
24
|
export const MEMORY_RECALL_MAX_UNITS = 1_800;
|
|
25
|
-
|
|
25
|
+
// Rerank sits on the turn's critical path and can only ever narrow the shortlist, so it
|
|
26
|
+
// gets a short leash and fails open to the local ranking.
|
|
27
|
+
const MEMORY_RECALL_RERANK_TIMEOUT_MS = 3_000;
|
|
26
28
|
const RERANK_CONTENT_CLIP = 800;
|
|
27
|
-
const HIGH_CONFIDENCE_SCORE =
|
|
28
|
-
const CLOSE_SCORE_DELTA =
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
const HIGH_CONFIDENCE_SCORE = 8;
|
|
30
|
+
const CLOSE_SCORE_DELTA = 3;
|
|
31
|
+
/**
|
|
32
|
+
* Minimum weighted evidence a candidate must show to enter the shortlist, measured in
|
|
33
|
+
* specificity mass (see `tokenSpecificity`) rather than as a fraction of the query.
|
|
34
|
+
* Normalizing by query length made recall collapse on detailed messages: a 60-token
|
|
35
|
+
* question could not clear a 25% coverage bar even when it named the exact subject of a
|
|
36
|
+
* stored entry, so the more context a user gave the less memory surfaced. Evidence is
|
|
37
|
+
* absolute instead — one rare token match counts the same however long the message is.
|
|
38
|
+
*/
|
|
39
|
+
const MIN_MATCH_EVIDENCE = 2.5;
|
|
40
|
+
/** Field the strongest match for a token was found in; a token scores once, at its best field. */
|
|
41
|
+
const FIELD_WEIGHTS = { title: 1.4, content: 1, path: 0.7 };
|
|
31
42
|
const MAX_HAN_WORD_LENGTH = Array.from(COMMON_CHINESE_WORDS).reduce((max, word) => Math.max(max, word.length), 2);
|
|
32
43
|
const LATIN_STOP_WORDS = new Set([
|
|
33
44
|
"a",
|
|
@@ -179,6 +190,14 @@ function tokenizeHanPart(part) {
|
|
|
179
190
|
tokens.push(char);
|
|
180
191
|
}
|
|
181
192
|
}
|
|
193
|
+
// Trigrams are emitted across the whole run, including positions the dictionary already
|
|
194
|
+
// covered. Greedy dictionary matching shreds compounds — "包管理器" becomes 管理 + 包 + 器,
|
|
195
|
+
// three tokens so generic they carry almost no evidence — while the trigrams 包管理/管理器
|
|
196
|
+
// survive on both the query and the memory side and match verbatim. This is what lets a
|
|
197
|
+
// domain term be recognized without shipping a domain dictionary.
|
|
198
|
+
for (let index = 0; index + 3 <= chars.length; index++) {
|
|
199
|
+
tokens.push(chars.slice(index, index + 3).join(""));
|
|
200
|
+
}
|
|
182
201
|
return Array.from(new Set(tokens));
|
|
183
202
|
}
|
|
184
203
|
function tokenizeAsciiPart(part) {
|
|
@@ -213,36 +232,93 @@ export function tokenizeRecallText(text) {
|
|
|
213
232
|
function buildTokenSet(text) {
|
|
214
233
|
return new Set(tokenize(text));
|
|
215
234
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
235
|
+
/**
|
|
236
|
+
* How much evidence a single token match is worth, from the token's own shape. Length and
|
|
237
|
+
* script are decent proxies for rarity and they cost nothing to compute: a bare "器" says
|
|
238
|
+
* almost nothing, "包管理" says a lot, and an identifier like "pnpm" says more still.
|
|
239
|
+
*/
|
|
240
|
+
function hanTokenSpecificity(token) {
|
|
241
|
+
const chars = Array.from(token);
|
|
242
|
+
const informative = chars.filter((char) => !CHINESE_STOP_CHARS.has(char)).length;
|
|
243
|
+
if (chars.length >= 3) {
|
|
244
|
+
// Function-word trigrams ("不要用") match everywhere and mean nothing.
|
|
245
|
+
return informative >= 2 ? 2.5 : 0.8;
|
|
246
|
+
}
|
|
247
|
+
if (chars.length === 2) {
|
|
248
|
+
if (informative === 0)
|
|
249
|
+
return 0.2;
|
|
250
|
+
// A bigram the dictionary does not know is more likely to be a domain term.
|
|
251
|
+
return COMMON_CHINESE_WORDS.has(token) ? 1 : 1.5;
|
|
252
|
+
}
|
|
253
|
+
return CHINESE_STOP_CHARS.has(token) ? 0.1 : 0.25;
|
|
254
|
+
}
|
|
255
|
+
function tokenSpecificity(token) {
|
|
256
|
+
if (containsHanText(token))
|
|
257
|
+
return hanTokenSpecificity(token);
|
|
258
|
+
if (/\d/.test(token))
|
|
259
|
+
return 3;
|
|
260
|
+
if (token.length >= 4)
|
|
261
|
+
return 3;
|
|
262
|
+
if (token.length === 3)
|
|
263
|
+
return 2;
|
|
264
|
+
return 0.8;
|
|
231
265
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
266
|
+
// Candidates are cached objects reused across turns by the MemoryCandidateStore, so keying
|
|
267
|
+
// off the object identity keeps tokenization off the hot path for unchanged memory files.
|
|
268
|
+
const candidateTokenCache = new WeakMap();
|
|
269
|
+
function getCandidateTokens(candidate) {
|
|
270
|
+
const cached = candidateTokenCache.get(candidate);
|
|
271
|
+
if (cached) {
|
|
272
|
+
return cached;
|
|
273
|
+
}
|
|
274
|
+
const title = buildTokenSet(candidate.title);
|
|
275
|
+
const content = buildTokenSet(candidate.searchText ?? candidate.content);
|
|
276
|
+
const path = buildTokenSet(candidate.path);
|
|
277
|
+
const index = { title, content, path, all: new Set([...title, ...content, ...path]) };
|
|
278
|
+
candidateTokenCache.set(candidate, index);
|
|
279
|
+
return index;
|
|
280
|
+
}
|
|
281
|
+
function buildDocumentFrequency(candidates) {
|
|
282
|
+
const frequencies = new Map();
|
|
283
|
+
for (const candidate of candidates) {
|
|
284
|
+
for (const token of getCandidateTokens(candidate).all) {
|
|
285
|
+
frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
|
|
237
286
|
}
|
|
238
287
|
}
|
|
239
|
-
|
|
288
|
+
return frequencies;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Damp tokens that appear in most of the corpus (section headings, house vocabulary). Kept
|
|
292
|
+
* deliberately gentle — memory corpora are tens of entries, so a token appearing in every
|
|
293
|
+
* one of them is weak evidence, not zero evidence.
|
|
294
|
+
*/
|
|
295
|
+
function documentFrequencyDamping(documentFrequency, totalCandidates) {
|
|
296
|
+
if (totalCandidates <= 1)
|
|
297
|
+
return 1;
|
|
298
|
+
return 1 / (1 + (documentFrequency - 1) / totalCandidates);
|
|
299
|
+
}
|
|
300
|
+
function computeMatchEvidence(queryTokens, candidate, documentFrequencies, totalCandidates, includePath = true) {
|
|
301
|
+
const tokens = getCandidateTokens(candidate);
|
|
302
|
+
let mass = 0;
|
|
303
|
+
let matchedCount = 0;
|
|
240
304
|
for (const token of queryTokens) {
|
|
241
|
-
|
|
242
|
-
|
|
305
|
+
const fieldWeight = tokens.title.has(token)
|
|
306
|
+
? FIELD_WEIGHTS.title
|
|
307
|
+
: tokens.content.has(token)
|
|
308
|
+
? FIELD_WEIGHTS.content
|
|
309
|
+
: includePath && tokens.path.has(token)
|
|
310
|
+
? FIELD_WEIGHTS.path
|
|
311
|
+
: 0;
|
|
312
|
+
if (fieldWeight === 0) {
|
|
313
|
+
continue;
|
|
243
314
|
}
|
|
315
|
+
matchedCount++;
|
|
316
|
+
mass +=
|
|
317
|
+
tokenSpecificity(token) *
|
|
318
|
+
fieldWeight *
|
|
319
|
+
documentFrequencyDamping(documentFrequencies.get(token) ?? 1, totalCandidates);
|
|
244
320
|
}
|
|
245
|
-
return
|
|
321
|
+
return { mass, matchedCount };
|
|
246
322
|
}
|
|
247
323
|
function computeExactMatchBoost(query, candidate) {
|
|
248
324
|
const normalizedQuery = query.trim().toLowerCase();
|
|
@@ -255,9 +331,9 @@ function computeExactMatchBoost(query, candidate) {
|
|
|
255
331
|
}
|
|
256
332
|
let boost = 0;
|
|
257
333
|
const scoringFields = [
|
|
258
|
-
[candidate.title,
|
|
259
|
-
[candidate.searchText ?? candidate.content,
|
|
260
|
-
[candidate.path,
|
|
334
|
+
[candidate.title, 4],
|
|
335
|
+
[candidate.searchText ?? candidate.content, 3],
|
|
336
|
+
[candidate.path, 1.5],
|
|
261
337
|
];
|
|
262
338
|
for (const [field, value] of scoringFields) {
|
|
263
339
|
if (field.toLowerCase().includes(normalizedQuery)) {
|
|
@@ -328,33 +404,22 @@ function compareScoredCandidates(a, b) {
|
|
|
328
404
|
b.candidate.priority - a.candidate.priority ||
|
|
329
405
|
a.candidate.title.localeCompare(b.candidate.title));
|
|
330
406
|
}
|
|
331
|
-
function scoreCandidate(query, queryTokens, intents, candidate) {
|
|
332
|
-
const
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
const pathStats = computeTokenMatchStats(queryTokens, candidate.path);
|
|
336
|
-
const matchedTokens = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText, candidate.path]);
|
|
337
|
-
const semanticFieldMatches = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText]);
|
|
338
|
-
const exactBoost = computeExactMatchBoost(query, candidate);
|
|
339
|
-
const intentBoost = computeSectionIntentBoost(intents, candidate);
|
|
340
|
-
const overallCoverage = queryTokens.length > 0 ? matchedTokens.size / queryTokens.length : 0;
|
|
341
|
-
const lexicalScore = overallCoverage * 48 +
|
|
342
|
-
titleStats.coverage * 18 +
|
|
343
|
-
contentStats.coverage * 22 +
|
|
344
|
-
pathStats.coverage * 8 +
|
|
345
|
-
exactBoost;
|
|
346
|
-
const structuralScore = candidate.priority + intentBoost + computeRecencyBoost(candidate.timestamp);
|
|
347
|
-
if (semanticFieldMatches.size === 0 || (overallCoverage < MIN_QUERY_COVERAGE && exactBoost === 0)) {
|
|
407
|
+
function scoreCandidate(query, queryTokens, intents, candidate, documentFrequencies, totalCandidates) {
|
|
408
|
+
const evidence = computeMatchEvidence(queryTokens, candidate, documentFrequencies, totalCandidates);
|
|
409
|
+
const totalEvidence = evidence.mass + computeExactMatchBoost(query, candidate);
|
|
410
|
+
if (totalEvidence < MIN_MATCH_EVIDENCE) {
|
|
348
411
|
return null;
|
|
349
412
|
}
|
|
413
|
+
const intentBoost = computeSectionIntentBoost(intents, candidate);
|
|
414
|
+
const structuralScore = candidate.priority + intentBoost + computeRecencyBoost(candidate.timestamp);
|
|
350
415
|
return {
|
|
351
416
|
candidate,
|
|
352
|
-
score:
|
|
353
|
-
lexicalMatchCount:
|
|
417
|
+
score: totalEvidence * (1 + structuralScore / 100),
|
|
418
|
+
lexicalMatchCount: evidence.matchedCount,
|
|
354
419
|
intentBoost,
|
|
355
420
|
};
|
|
356
421
|
}
|
|
357
|
-
function seedIntentCandidates(request, candidates, existing, intents, queryTokens) {
|
|
422
|
+
function seedIntentCandidates(request, candidates, existing, intents, queryTokens, documentFrequencies, totalCandidates) {
|
|
358
423
|
if (intents.size === 0) {
|
|
359
424
|
return existing;
|
|
360
425
|
}
|
|
@@ -371,18 +436,17 @@ function seedIntentCandidates(request, candidates, existing, intents, queryToken
|
|
|
371
436
|
b.candidate.priority - a.candidate.priority ||
|
|
372
437
|
a.candidate.title.localeCompare(b.candidate.title));
|
|
373
438
|
for (const { candidate, intentBoost } of intentCandidates) {
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (matchedTokens.size === 0) {
|
|
439
|
+
// Path matches are excluded here: an intent seed has to earn its place on what the
|
|
440
|
+
// entry says, not on where it is stored.
|
|
441
|
+
const evidence = computeMatchEvidence(queryTokens, candidate, documentFrequencies, totalCandidates, false);
|
|
442
|
+
if (evidence.matchedCount === 0) {
|
|
379
443
|
continue;
|
|
380
444
|
}
|
|
381
445
|
seeded.push({
|
|
382
446
|
candidate,
|
|
383
|
-
score: (intentBoost +
|
|
447
|
+
score: (intentBoost / 4 + evidence.mass) *
|
|
384
448
|
(1 + (candidate.priority + computeRecencyBoost(candidate.timestamp)) / 100),
|
|
385
|
-
lexicalMatchCount:
|
|
449
|
+
lexicalMatchCount: evidence.matchedCount,
|
|
386
450
|
intentBoost,
|
|
387
451
|
});
|
|
388
452
|
seen.add(candidate.id);
|
|
@@ -441,20 +505,15 @@ async function rerankCandidates(request, candidates) {
|
|
|
441
505
|
return candidates;
|
|
442
506
|
}
|
|
443
507
|
}
|
|
444
|
-
function hasMemorySensitiveQueryIntent(query) {
|
|
445
|
-
if (HAN_REGEX.test(query)) {
|
|
446
|
-
return /(之前|上次|记得|记住|偏好|决定|历史|纠正|不要再|以后|默认)/.test(query);
|
|
447
|
-
}
|
|
448
|
-
return /\b(previous|previously|last time|remember|preference|decision|history|correction|again|default)\b/i.test(query);
|
|
449
|
-
}
|
|
450
508
|
function shouldUseModelRerank(request, candidates) {
|
|
509
|
+
// Nothing to prune: everything on the shortlist is going to be injected anyway.
|
|
451
510
|
if (candidates.length <= request.maxInjected) {
|
|
452
511
|
return false;
|
|
453
512
|
}
|
|
454
513
|
if (request.rerankWithModel === true) {
|
|
455
514
|
return true;
|
|
456
515
|
}
|
|
457
|
-
if (request.rerankWithModel === false
|
|
516
|
+
if (request.rerankWithModel === false) {
|
|
458
517
|
return false;
|
|
459
518
|
}
|
|
460
519
|
const top = candidates[0];
|
|
@@ -462,14 +521,12 @@ function shouldUseModelRerank(request, candidates) {
|
|
|
462
521
|
if (!top || !next) {
|
|
463
522
|
return false;
|
|
464
523
|
}
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
}
|
|
472
|
-
return true;
|
|
524
|
+
// Auto mode reranks whenever the local ranking is ambiguous. It used to additionally
|
|
525
|
+
// require memory-sensitive phrasing in the query, which meant an over-full shortlist on
|
|
526
|
+
// an ordinary turn was injected unranked. Now that the lexical gate admits candidates on
|
|
527
|
+
// absolute evidence, the shortlist is wider and picking from it is exactly the job the
|
|
528
|
+
// reranker exists for — so the only reason to skip is a clear local winner.
|
|
529
|
+
return !(top.score >= HIGH_CONFIDENCE_SCORE && top.score - next.score >= CLOSE_SCORE_DELTA);
|
|
473
530
|
}
|
|
474
531
|
function renderRecallResult(items, maxChars, maxUnits) {
|
|
475
532
|
if (items.length === 0) {
|
|
@@ -536,12 +593,13 @@ export async function recallRelevantMemory(request) {
|
|
|
536
593
|
}
|
|
537
594
|
const queryTokens = tokenize(query);
|
|
538
595
|
const queryIntents = detectQueryIntents(query);
|
|
596
|
+
const documentFrequencies = buildDocumentFrequency(eligibleCandidates);
|
|
597
|
+
const totalCandidates = eligibleCandidates.length;
|
|
539
598
|
const scored = eligibleCandidates
|
|
540
|
-
.map((candidate) => scoreCandidate(query, queryTokens, queryIntents, candidate))
|
|
599
|
+
.map((candidate) => scoreCandidate(query, queryTokens, queryIntents, candidate, documentFrequencies, totalCandidates))
|
|
541
600
|
.filter((candidate) => candidate !== null)
|
|
542
|
-
.filter((candidate) => candidate.score >= MIN_LOCAL_SCORE)
|
|
543
601
|
.sort(compareScoredCandidates);
|
|
544
|
-
const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens)
|
|
602
|
+
const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens, documentFrequencies, totalCandidates)
|
|
545
603
|
.sort(compareScoredCandidates)
|
|
546
604
|
.slice(0, Math.max(request.maxCandidates, request.maxInjected));
|
|
547
605
|
if (shortlist.length === 0) {
|
|
@@ -13,6 +13,13 @@ export interface SidecarTask<T> {
|
|
|
13
13
|
channelId: string;
|
|
14
14
|
correlationId?: string;
|
|
15
15
|
};
|
|
16
|
+
/**
|
|
17
|
+
* Optional one-shot repair hint. When `parse` fails on the first attempt, the
|
|
18
|
+
* task is retried once with this text appended to the prompt, so a model that
|
|
19
|
+
* emitted malformed-but-recoverable output (e.g. a misspelled JSON key) gets a
|
|
20
|
+
* targeted correction nudge. Omit to keep parse failures fatal.
|
|
21
|
+
*/
|
|
22
|
+
repair?: (error: SidecarParseError) => string;
|
|
16
23
|
}
|
|
17
24
|
export interface SidecarResult<T> {
|
|
18
25
|
output: T;
|
|
@@ -162,22 +162,40 @@ export async function runSidecarTask(task) {
|
|
|
162
162
|
removeAbortListener();
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
|
+
/** Appends a non-empty repair hint to the original prompt, or returns it unchanged. */
|
|
166
|
+
function withRepairSuffix(prompt, suffix) {
|
|
167
|
+
const trimmed = suffix.trim();
|
|
168
|
+
return trimmed ? `${prompt}\n\n${trimmed}` : prompt;
|
|
169
|
+
}
|
|
165
170
|
export async function runRetriedSidecarTask(task) {
|
|
166
|
-
|
|
167
|
-
|
|
171
|
+
// Set when a one-shot repair hint has been applied; the next attempt runs with
|
|
172
|
+
// this prompt instead of the original.
|
|
173
|
+
let repairedPrompt;
|
|
174
|
+
let attempt = 0;
|
|
175
|
+
for (;;) {
|
|
176
|
+
attempt += 1;
|
|
168
177
|
if (isExternalAbort(task)) {
|
|
169
178
|
throw createAbortError(task.name, task.signal?.reason);
|
|
170
179
|
}
|
|
180
|
+
const current = repairedPrompt === undefined ? task : { ...task, prompt: repairedPrompt };
|
|
171
181
|
try {
|
|
172
|
-
return await runSidecarTask(
|
|
182
|
+
return await runSidecarTask(current);
|
|
173
183
|
}
|
|
174
184
|
catch (error) {
|
|
175
|
-
|
|
185
|
+
// A parse failure is recoverable exactly once when the caller supplies a
|
|
186
|
+
// repair hint: retry with the nudge appended so a malformed-but-fixable
|
|
187
|
+
// output (e.g. a misspelled JSON key) gets one targeted correction pass.
|
|
188
|
+
if (error instanceof SidecarParseError && repairedPrompt === undefined && typeof task.repair === "function") {
|
|
189
|
+
repairedPrompt = withRepairSuffix(task.prompt, task.repair(error));
|
|
190
|
+
await delay(SIDE_CAR_RETRY_DELAY_MS, task);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
// Parse failures are otherwise fatal — a blind retry would reproduce the
|
|
194
|
+
// same bad output. Transient failures get the standard retry budget.
|
|
176
195
|
if (attempt >= SIDE_CAR_MAX_ATTEMPTS || error instanceof SidecarParseError || isExternalAbort(task)) {
|
|
177
196
|
throw error;
|
|
178
197
|
}
|
|
179
198
|
await delay(SIDE_CAR_RETRY_DELAY_MS, task);
|
|
180
199
|
}
|
|
181
200
|
}
|
|
182
|
-
throw lastError instanceof Error ? lastError : new Error(`Sidecar task "${task.name}" failed`);
|
|
183
201
|
}
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const APP_NAME = "pipiclaw";
|
|
2
2
|
/** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
|
|
3
3
|
export declare const PLAYBOOKS_DIR: string;
|
|
4
|
+
export declare const BUILTIN_SUB_AGENTS_DIR: string;
|
|
4
5
|
/**
|
|
5
6
|
* Legacy default app home used before the `~/.pipiclaw` default (introduced in
|
|
6
7
|
* 0.8.x). Kept only so bootstrap can migrate an existing install to the new
|
package/dist/paths.js
CHANGED
|
@@ -12,6 +12,17 @@ const bundledPlaybooksDir = fileURLToPath(new URL("./playbooks", import.meta.url
|
|
|
12
12
|
const checkoutPlaybooksDir = fileURLToPath(new URL("../src/playbooks", import.meta.url));
|
|
13
13
|
/** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
|
|
14
14
|
export const PLAYBOOKS_DIR = existsSync(checkoutPlaybooksDir) ? checkoutPlaybooksDir : bundledPlaybooksDir;
|
|
15
|
+
/**
|
|
16
|
+
* Built-in sub-agent definitions bundled inside the installed package (spec 032 D2),
|
|
17
|
+
* same checkout/dist split as PLAYBOOKS_DIR. `discoverSubAgents` scans this directory
|
|
18
|
+
* before the workspace `sub-agents/` directory; a workspace file with the same `name`
|
|
19
|
+
* overrides the built-in one.
|
|
20
|
+
*/
|
|
21
|
+
const bundledBuiltinSubAgentsDir = fileURLToPath(new URL("./subagents/builtin", import.meta.url));
|
|
22
|
+
const checkoutBuiltinSubAgentsDir = fileURLToPath(new URL("../src/subagents/builtin", import.meta.url));
|
|
23
|
+
export const BUILTIN_SUB_AGENTS_DIR = existsSync(checkoutBuiltinSubAgentsDir)
|
|
24
|
+
? checkoutBuiltinSubAgentsDir
|
|
25
|
+
: bundledBuiltinSubAgentsDir;
|
|
15
26
|
/**
|
|
16
27
|
* Legacy default app home used before the `~/.pipiclaw` default (introduced in
|
|
17
28
|
* 0.8.x). Kept only so bootstrap can migrate an existing install to the new
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: background-jobs
|
|
3
|
+
description: 用 bash async 启动长跑命令、轮询后台作业(job),或作业跨回合仍未完成时。
|
|
4
|
+
requires-tools: job
|
|
5
|
+
priority: 35
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# 后台作业(background jobs)
|
|
9
|
+
|
|
10
|
+
`bash` 传 `async: true` 会把命令放到后台并立刻返回一个 job id;`job` 工具负责之后的查看、等待和取消。适用于构建、测试套件、大文件下载、批量处理这类**明显超过前台超时**的命令。
|
|
11
|
+
|
|
12
|
+
短命令不要 async——多一次 poll 往返比直接同步等更慢。
|
|
13
|
+
|
|
14
|
+
## 三个动作
|
|
15
|
+
|
|
16
|
+
- `job op=list`:当前作业快照,含状态与已运行时长。
|
|
17
|
+
- `job op=poll ids=[...]`:等待作业结束并取回输出;省略 `ids` 表示等所有运行中的作业。
|
|
18
|
+
- `job op=cancel ids=[...]`:按 id 终止,必须显式给 id。
|
|
19
|
+
|
|
20
|
+
`poll` **最多等约 30 秒**就返回,未完成时返回的是"仍在运行",不是失败。它适合"几乎肯定马上就好"的短等待;等不到就结束回合,作业结束时自会叫醒你。
|
|
21
|
+
|
|
22
|
+
## 作业结束会自动叫醒你
|
|
23
|
+
|
|
24
|
+
**不需要预约回访。** 作业进入终态时,runtime 会给这个 channel 发一条唤醒,带上退出码、耗时、输出尾部和完整输出的路径。所以:
|
|
25
|
+
|
|
26
|
+
- 不要为等作业而建 one-shot event;
|
|
27
|
+
- 不要为等作业去猜一个 `wake` 时间;
|
|
28
|
+
- 不要靠连续 poll 空转烧 token。
|
|
29
|
+
|
|
30
|
+
启动 async 作业后**直接结束回合**即可。醒来时你会拿到结果。
|
|
31
|
+
|
|
32
|
+
只有一种情况需要自己收尾:`notify: false`(明确不需要结果的 fire-and-forget)。那时作业结束不会叫你,得自己 `job op=list`。
|
|
33
|
+
|
|
34
|
+
如果这个作业属于某项长程任务,启动时传 `taskId`,唤醒文本会点明归属;再用 `task_manage progress` 置 `waiting` 把等待写进任务状态即可,**不必设 `wake`**。
|
|
35
|
+
|
|
36
|
+
## 硬约束
|
|
37
|
+
|
|
38
|
+
每个 channel 最多 5 个同时运行的作业。达到上限后 `bash async` 会直接被拒绝,提示你先 poll 或 cancel。终态作业会自动释放名额,不再依赖你去查。
|
|
39
|
+
|
|
40
|
+
作业记录跨重启存活:daemon 重启后仍在跑的作业会被重新认领,重启期间结束的作业会补发唤醒。即便如此,**真正重要的产物应让命令自己写进 workspace 文件**,而不是只留在作业的 stdout 里——输出保留 24 小时后会被清理。
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
/** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
|
|
2
|
-
declare const PLAYBOOK_MODES: readonly ["normal", "task-driver", "event", "subagent", "maintenance"];
|
|
3
|
-
export type PlaybookMode = (typeof PLAYBOOK_MODES)[number];
|
|
4
1
|
/** A catalog entry is a single trigger, not a summary; longer descriptions are clipped in the prompt (spec 026 §10.5). */
|
|
5
2
|
export declare const MAX_PLAYBOOK_DESCRIPTION_CHARS = 100;
|
|
6
3
|
export interface RuntimePlaybookMetadata {
|
|
@@ -14,8 +11,6 @@ export interface RuntimePlaybookMetadata {
|
|
|
14
11
|
* listed. (Prompt sections gate the other way: see `requiresAllTools` in agent/prompt/types.ts.)
|
|
15
12
|
*/
|
|
16
13
|
requiresAnyTool: string[];
|
|
17
|
-
/** Modes this playbook is offered in. Empty = all modes. */
|
|
18
|
-
modes: PlaybookMode[];
|
|
19
14
|
/** Ascending; ties break on filename. */
|
|
20
15
|
priority: number;
|
|
21
16
|
}
|
|
@@ -25,11 +20,10 @@ export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimeP
|
|
|
25
20
|
* Drop playbooks whose mechanism is unreachable with the current tool set: the task
|
|
26
21
|
* playbooks are pure noise for a runtime with `task_manage` switched off.
|
|
27
22
|
*/
|
|
28
|
-
export declare function selectRuntimePlaybooks(catalog: RuntimePlaybookMetadata[], toolNames: readonly string[]
|
|
23
|
+
export declare function selectRuntimePlaybooks(catalog: RuntimePlaybookMetadata[], toolNames: readonly string[]): RuntimePlaybookMetadata[];
|
|
29
24
|
/**
|
|
30
25
|
* The always-loaded catalog. It shows the real absolute PLAYBOOKS_DIR once at the
|
|
31
26
|
* top so the model can `read` a guide without guessing the install path (spec 026
|
|
32
27
|
* §3.3, §7.1); each entry is filename + one short trigger, never the body.
|
|
33
28
|
*/
|
|
34
29
|
export declare function renderPlaybookCatalog(playbooks: RuntimePlaybookMetadata[]): string;
|
|
35
|
-
export {};
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
import { basename, join } from "node:path";
|
|
3
3
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
4
|
-
import {
|
|
5
|
-
/** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
|
|
6
|
-
const PLAYBOOK_MODES = ["normal", "task-driver", "event", "subagent", "maintenance"];
|
|
4
|
+
import { TOOL_NAMES } from "../tools/registry.js";
|
|
7
5
|
const DEFAULT_PRIORITY = 100;
|
|
8
6
|
/** A catalog entry is a single trigger, not a summary; longer descriptions are clipped in the prompt (spec 026 §10.5). */
|
|
9
7
|
export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 100;
|
|
@@ -43,22 +41,16 @@ function parseFrontmatter(content, filename) {
|
|
|
43
41
|
// otherwise drop the playbook from the catalog with no signal anywhere.
|
|
44
42
|
const requiresAnyTool = parseList(fields.get("requires-tools"));
|
|
45
43
|
for (const tool of requiresAnyTool) {
|
|
46
|
-
if (!(tool
|
|
44
|
+
if (!TOOL_NAMES.has(tool)) {
|
|
47
45
|
throw new Error(`Runtime playbook ${filename} requires unknown tool "${tool}".`);
|
|
48
46
|
}
|
|
49
47
|
}
|
|
50
|
-
const modes = parseList(fields.get("modes"));
|
|
51
|
-
for (const mode of modes) {
|
|
52
|
-
if (!PLAYBOOK_MODES.includes(mode)) {
|
|
53
|
-
throw new Error(`Runtime playbook ${filename} declares unknown mode "${mode}".`);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
48
|
const priorityField = fields.get("priority");
|
|
57
49
|
const priority = priorityField ? Number(priorityField) : DEFAULT_PRIORITY;
|
|
58
50
|
if (!Number.isFinite(priority)) {
|
|
59
51
|
throw new Error(`Runtime playbook ${filename} has a non-numeric priority "${priorityField}".`);
|
|
60
52
|
}
|
|
61
|
-
return { name, description, requiresAnyTool,
|
|
53
|
+
return { name, description, requiresAnyTool, priority };
|
|
62
54
|
}
|
|
63
55
|
/** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
|
|
64
56
|
export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
|
|
@@ -75,11 +67,9 @@ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
|
|
|
75
67
|
* Drop playbooks whose mechanism is unreachable with the current tool set: the task
|
|
76
68
|
* playbooks are pure noise for a runtime with `task_manage` switched off.
|
|
77
69
|
*/
|
|
78
|
-
export function selectRuntimePlaybooks(catalog, toolNames
|
|
70
|
+
export function selectRuntimePlaybooks(catalog, toolNames) {
|
|
79
71
|
const tools = new Set(toolNames);
|
|
80
72
|
return catalog.filter((playbook) => {
|
|
81
|
-
if (playbook.modes.length > 0 && !playbook.modes.includes(mode))
|
|
82
|
-
return false;
|
|
83
73
|
if (playbook.requiresAnyTool.length === 0)
|
|
84
74
|
return true;
|
|
85
75
|
return playbook.requiresAnyTool.some((tool) => tools.has(tool));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: event-scheduling
|
|
3
|
-
description:
|
|
3
|
+
description: 创建、调整或退役提醒、定时调度(cron)、preAction 传感器门控,或跨回合的回访事件(event)。
|
|
4
4
|
requires-tools: event_manage
|
|
5
5
|
priority: 30
|
|
6
6
|
---
|
|
@@ -14,7 +14,7 @@ priority: 30
|
|
|
14
14
|
- 当前回合立即能做:直接做,不建 immediate。`event_manage` 会拒绝 immediate,防止自触发循环。
|
|
15
15
|
- 将来某时只提醒一次:one-shot,至少提前 2 分钟。
|
|
16
16
|
- 固定节奏重复提醒/检查:periodic,五段 cron(按主机时区解释,无 timezone 字段)。
|
|
17
|
-
- 周期性产出任务:单个 task 文件,节奏写在 frontmatter 的 `schedule`,见 `task-
|
|
17
|
+
- 周期性产出任务:单个 task 文件,节奏写在 frontmatter 的 `schedule`,见 `task-planning.md`。
|
|
18
18
|
|
|
19
19
|
优先使用 `event_manage`,它会验证 JSON、channel、时间间隔、preAction command guard 和总量。工具不可用时才直接维护 `events/*.json`;无效文件可能被 scheduler 忽略。
|
|
20
20
|
|
|
@@ -38,8 +38,12 @@ preAction 的 bash 命令退出 0 才唤醒 agent,非 0 静默跳过。它适
|
|
|
38
38
|
|
|
39
39
|
传感器应使用 periodic:one-shot 即使 gate 未通过也会被消费。任何传感器都要有退出条件和合理频率;task-owned 传感器还要保留任务 `wake` 兜底,避免永久静默或空转。
|
|
40
40
|
|
|
41
|
-
##
|
|
41
|
+
## 回访事件
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
当前回合等不到结果、又没有对应 task 可以承载等待时,按预计完成时间建一条 one-shot 回访;只有需要按外部条件触发时才用 periodic + preAction。回访完成后删除临时事件。
|
|
44
|
+
|
|
45
|
+
**等后台作业(`bash async`)不属于这一类**:作业结束时 runtime 会自动唤醒你,不要为它建任何事件,见 `background-jobs.md`。
|
|
46
|
+
|
|
47
|
+
## 维护纪律
|
|
44
48
|
|
|
45
49
|
周期事件无新结果时只回复 `[SILENT]`,避免发送空状态卡。更新事件时整体替换 definition;不再需要时及时删除,并用 `/events history` 排查触发与 gate 结果。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: memory-and-learning
|
|
3
|
-
description:
|
|
3
|
+
description: 记住或忘记事实(memory)、在记忆文件之间取舍,或把经验沉淀成技能(skill)。
|
|
4
4
|
requires-tools: memory_manage, skill_manage
|
|
5
5
|
priority: 20
|
|
6
6
|
---
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: outbound-media
|
|
3
|
+
description: 把生成的文件、图片、报表或导出物作为附件(attachment / media)交付给用户时。
|
|
4
|
+
requires-tools: send_media
|
|
5
|
+
priority: 25
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# 附件交付(outbound media)
|
|
9
|
+
|
|
10
|
+
产物只有真正到了用户手里才算交付。`send_media` 把本地文件作为**原生附件**发进当前 channel:图片内联展示,其余作为可下载文件。
|
|
11
|
+
|
|
12
|
+
## 什么时候用
|
|
13
|
+
|
|
14
|
+
用 `send_media`:生成的报表、截图、图表、导出文件、日志片段打包——**用户需要拿到文件本身**。
|
|
15
|
+
|
|
16
|
+
不要用:
|
|
17
|
+
|
|
18
|
+
- 给自己看文件内容用 `read`,不要先发给用户再阅读。
|
|
19
|
+
- 几行文本、一小段代码、一个结论:直接写在回复里,附件反而更难读。
|
|
20
|
+
- 只把路径贴给用户(如 `/home/.../report.pdf`)。用户在钉钉里打不开主机路径;这正是本工具存在的原因。
|
|
21
|
+
|
|
22
|
+
## 调用约定
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
send_media label="本周巡检报告" path="reports/2026-W29.pdf" fileName="巡检报告-2026-W29.pdf"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- `label`:说明你在发什么、为什么发,会展示给用户。
|
|
29
|
+
- `path`:workspace 相对路径或绝对路径,经与 `read` 相同的 path guard。
|
|
30
|
+
- `fileName`:可选的收件显示名,默认取文件本身的名字。想让用户看到有意义的名字就显式传。
|
|
31
|
+
|
|
32
|
+
`.jpg .jpeg .png .gif .webp .bmp` 按图片内联,其余一律按文件下载。**目标 channel 由运行时绑定**,不是参数——你无法也不需要指定发给谁,当前对话就是目的地。
|
|
33
|
+
|
|
34
|
+
## 失败与下一步
|
|
35
|
+
|
|
36
|
+
| 报错 | 含义 | 下一步 |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| `Path blocked [...]` | 路径被 path guard 拒绝 | 把产物写到 workspace 内再发,不要绕守卫 |
|
|
39
|
+
| `not a regular file (does it exist?)` | 路径不存在或是目录 | 先确认产物真的生成了;目录先打包成单个文件 |
|
|
40
|
+
| `the file is empty` | 生成步骤静默失败了 | 回去查生成命令的退出码和输出,别重发空文件 |
|
|
41
|
+
| 发送失败(transport 报错) | 渠道侧拒绝或超限 | 文件过大时改发摘要 + 关键片段,或拆分后重试 |
|
|
42
|
+
|
|
43
|
+
## 与任务台账的关系
|
|
44
|
+
|
|
45
|
+
任务(task)的产物交付属于**结果**,不是日志:发送成功后,把"已作为附件发给用户"写进该轮的 progress note 或 done evidence,让后续唤醒不会重复投递同一份产物。若发送是任务的外部副作用(`sideEffects: external`)的一部分,遵守 `task-closeout.md` 的审批(approval)门禁,不要先发后批。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-delegation
|
|
3
|
-
description:
|
|
3
|
+
description: 拆分父子任务(task)、委派子代理(subagent),或创建任务隔离的 worktree 前。
|
|
4
4
|
requires-tools: task_manage, subagent
|
|
5
5
|
priority: 45
|
|
6
6
|
---
|
|
@@ -19,11 +19,17 @@ priority: 45
|
|
|
19
19
|
|
|
20
20
|
## 内建 subagent
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
不需要预先配置:不传 `agent` 时给 `systemPrompt` 即可发起委派,`workspaceDir/sub-agents/` 为空不影响这条路径。随包自带三个默认 agent(`explorer` 只读定位/摘要、`verifier` 独立验收、`researcher` 外部信息收集),同名 workspace 文件覆盖内置版本。选择明确适合的预定义 agent;没有时才用聚焦的 inline `systemPrompt`。task 描述必须包含目标、范围、相关路径、约束、验收方法和返回格式,因为子代理看不到主对话。
|
|
23
23
|
|
|
24
|
-
用 `maxTurns`、`maxToolCalls`、`maxWallTimeSec` 限幅。进程内 subagent
|
|
24
|
+
用 `maxTurns`、`maxToolCalls`、`maxWallTimeSec` 限幅。进程内 subagent 同回合同步返回,不需要回访事件;主 agent 负责验收结果和更新台账,子代理不驱动 task/event 台账。触顶时子代理会收敛输出已完成的结论而不是整段丢弃,但预算仍然是真实上限,不要依赖它兜底过大的任务。
|
|
25
25
|
|
|
26
|
-
独立验收必须 `purpose: verify` + `taskId
|
|
26
|
+
独立验收必须 `purpose: verify` + `taskId`,见 `task-closeout.md`。
|
|
27
|
+
|
|
28
|
+
## 产物契约与回传预算
|
|
29
|
+
|
|
30
|
+
每次委派都会在 `channelDir/subagent-artifacts/<runId>/` 下建产物目录,子代理的完整输出总会落盘到该目录的 `output.md`,与 `returns` 无关。回传给父代理的文本超过大小预算时会被截断,附上 `output.md` 的绝对路径——父代理判断值得保留的内容,按需 `read` 全文,再决定是否经 `memory_manage` 提炼为记忆。产物目录不自动清理,和 worktree 一样由父代理负责闭环:任务收尾时决定保留还是删除。
|
|
31
|
+
|
|
32
|
+
需要子代理把主产出写成文件而不是回传整段文本时传 `returns: "artifact"`,子代理需以 `ARTIFACT: <filename>` 结尾;忘记该标记时会自动降级为纯文本模式。
|
|
27
33
|
|
|
28
34
|
## worktree 隔离
|
|
29
35
|
|