@oyasmi/pipiclaw 0.8.7-beta.1 → 0.8.7-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.
Files changed (34) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -0
  2. package/dist/agent/channel-runner.js +18 -4
  3. package/dist/agent/prompt/builder.d.ts +11 -20
  4. package/dist/agent/prompt/builder.js +40 -87
  5. package/dist/agent/prompt/manifest.d.ts +28 -2
  6. package/dist/agent/prompt/manifest.js +50 -11
  7. package/dist/agent/prompt/resources.d.ts +11 -2
  8. package/dist/agent/prompt/resources.js +51 -12
  9. package/dist/agent/prompt/sections.d.ts +9 -10
  10. package/dist/agent/prompt/sections.js +46 -99
  11. package/dist/agent/prompt/types.d.ts +14 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/memory/bootstrap.d.ts +6 -0
  15. package/dist/memory/bootstrap.js +53 -21
  16. package/dist/memory/recall.d.ts +8 -0
  17. package/dist/memory/recall.js +19 -13
  18. package/dist/memory/task-digest.d.ts +4 -0
  19. package/dist/memory/task-digest.js +9 -3
  20. package/dist/playbooks/catalog.d.ts +7 -2
  21. package/dist/playbooks/catalog.js +10 -6
  22. package/dist/playbooks/event-scheduling.md +1 -1
  23. package/dist/playbooks/memory-and-learning.md +1 -1
  24. package/dist/playbooks/runtime-orientation.md +1 -1
  25. package/dist/playbooks/task-closeout.md +1 -1
  26. package/dist/playbooks/task-delegation.md +1 -1
  27. package/dist/playbooks/task-driving.md +1 -1
  28. package/dist/playbooks/task-planning.md +1 -1
  29. package/dist/playbooks/task-recurring.md +1 -1
  30. package/dist/playbooks/task-repair.md +1 -1
  31. package/dist/runtime/events.js +6 -1
  32. package/dist/shared/prompt-units.d.ts +46 -0
  33. package/dist/shared/prompt-units.js +153 -0
  34. package/package.json +1 -1
@@ -1,5 +1,8 @@
1
1
  import { join } from "node:path";
2
+ import { countPromptUnits } from "../shared/prompt-units.js";
2
3
  import { readActiveTasks } from "../shared/task-ledger.js";
4
+ /** Automatic-context share for the in-flight task agenda (spec 026 §5.3). */
5
+ export const TASK_AGENDA_MAX_UNITS = 600;
3
6
  function relativeWake(wakeMs, now) {
4
7
  if (wakeMs === undefined)
5
8
  return "wake —";
@@ -65,14 +68,17 @@ export async function buildTaskDigest(options) {
65
68
  if (omitted > 0)
66
69
  lines.push(`- (+${omitted} more)`);
67
70
  const footer = ["</task_agenda>"];
71
+ const maxUnits = options.maxUnits ?? Number.POSITIVE_INFINITY;
72
+ const fits = (text) => text.length <= options.maxChars && countPromptUnits(text) <= maxUnits;
68
73
  let rendered = [...header, ...lines, ...footer].join("\n");
69
- if (rendered.length <= options.maxChars)
74
+ if (fits(rendered))
70
75
  return rendered;
71
- // Over budget: drop lines from the end until it fits, keeping actionable-first order.
76
+ // Over one of the budgets: drop whole lines from the end until it fits, keeping
77
+ // actionable-first order. Chars and units are checked together (spec 026 §10.7).
72
78
  const kept = [];
73
79
  for (const line of lines) {
74
80
  const candidate = [...header, ...kept, line, `- (+${agenda.length - kept.length - 1} more)`, ...footer].join("\n");
75
- if (candidate.length > options.maxChars && kept.length > 0)
81
+ if (!fits(candidate) && kept.length > 0)
76
82
  break;
77
83
  kept.push(line);
78
84
  }
@@ -1,8 +1,8 @@
1
1
  /** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
2
2
  declare const PLAYBOOK_MODES: readonly ["normal", "task-driver", "event", "subagent", "maintenance"];
3
3
  export type PlaybookMode = (typeof PLAYBOOK_MODES)[number];
4
- /** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
5
- export declare const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
4
+ /** A catalog entry is a single trigger, not a summary; longer descriptions are clipped in the prompt (spec 026 §10.5). */
5
+ export declare const MAX_PLAYBOOK_DESCRIPTION_CHARS = 100;
6
6
  export interface RuntimePlaybookMetadata {
7
7
  name: string;
8
8
  description: string;
@@ -26,5 +26,10 @@ export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimeP
26
26
  * playbooks are pure noise for a runtime with `task_manage` switched off.
27
27
  */
28
28
  export declare function selectRuntimePlaybooks(catalog: RuntimePlaybookMetadata[], toolNames: readonly string[], mode?: PlaybookMode): RuntimePlaybookMetadata[];
29
+ /**
30
+ * The always-loaded catalog. It shows the real absolute PLAYBOOKS_DIR once at the
31
+ * top so the model can `read` a guide without guessing the install path (spec 026
32
+ * §3.3, §7.1); each entry is filename + one short trigger, never the body.
33
+ */
29
34
  export declare function renderPlaybookCatalog(playbooks: RuntimePlaybookMetadata[]): string;
30
35
  export {};
@@ -5,8 +5,8 @@ import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
5
5
  /** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
6
6
  const PLAYBOOK_MODES = ["normal", "task-driver", "event", "subagent", "maintenance"];
7
7
  const DEFAULT_PRIORITY = 100;
8
- /** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
9
- export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
8
+ /** A catalog entry is a single trigger, not a summary; longer descriptions are clipped in the prompt (spec 026 §10.5). */
9
+ export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 100;
10
10
  function parseList(value) {
11
11
  if (!value)
12
12
  return [];
@@ -85,13 +85,17 @@ export function selectRuntimePlaybooks(catalog, toolNames, mode = "normal") {
85
85
  return playbook.requiresAnyTool.some((tool) => tools.has(tool));
86
86
  });
87
87
  }
88
+ /**
89
+ * The always-loaded catalog. It shows the real absolute PLAYBOOKS_DIR once at the
90
+ * top so the model can `read` a guide without guessing the install path (spec 026
91
+ * §3.3, §7.1); each entry is filename + one short trigger, never the body.
92
+ */
88
93
  export function renderPlaybookCatalog(playbooks) {
89
- return playbooks
90
- .map((playbook) => {
94
+ const entries = playbooks.map((playbook) => {
91
95
  const description = playbook.description.length > MAX_PLAYBOOK_DESCRIPTION_CHARS
92
96
  ? `${playbook.description.slice(0, MAX_PLAYBOOK_DESCRIPTION_CHARS - 1)}…`
93
97
  : playbook.description;
94
98
  return `- ${playbook.filename} — ${description}`;
95
- })
96
- .join("\n");
99
+ });
100
+ return ["For Pipiclaw mechanisms, read the matching file with `read` under:", PLAYBOOKS_DIR, "", ...entries].join("\n");
97
101
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: event-scheduling
3
- description: Read before creating, updating, diagnosing, or retiring reminders, one-shot wakeups, periodic schedules, preAction gates, or background-job check-ins.
3
+ description: Creating, updating, or retiring reminders, schedules, preAction gates, or background-job check-ins.
4
4
  requires-tools: event_manage
5
5
  priority: 30
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: memory-and-learning
3
- description: Read when remembering or forgetting facts, choosing SESSION/MEMORY/HISTORY/ENVIRONMENT/tasks/skills, or turning repeated experience into a workspace skill.
3
+ description: Remembering or forgetting facts, choosing between memory files, or promoting experience to a skill.
4
4
  requires-tools: memory_manage, skill_manage
5
5
  priority: 20
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: runtime-orientation
3
- description: Read when locating Pipiclaw state, deciding whether knowledge belongs to runtime playbooks or workspace instructions, or interpreting channel and workspace files.
3
+ description: Locating runtime state and choosing the right knowledge layer for a question.
4
4
  priority: 10
5
5
  ---
6
6
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-closeout
3
- description: Read before candidate verification, importing a verifier verdict, requesting external approval, or completing/cancelling a task.
3
+ description: Before verification, importing a verdict, external approval, or completing/cancelling a task.
4
4
  requires-tools: task_manage
5
5
  priority: 42
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-delegation
3
- description: Read before splitting parent/child tasks, using predefined or inline subagents, creating task-owned worktrees, or delegating work you must revisit later.
3
+ description: Before splitting parent/child tasks, delegating to a sub-agent, or creating a task-owned worktree.
4
4
  requires-tools: task_manage, subagent
5
5
  priority: 45
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-driving
3
- description: Read whenever TASK_DRIVER or a task-owned event resumes work, and when checkpointing progress, waiting with wake, handling idempotent recovery, or deciding the next task action.
3
+ description: Resuming a task on a TASK_DRIVER wake or event, checkpointing, or choosing the next action.
4
4
  requires-tools: task_manage
5
5
  priority: 41
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-planning
3
- description: Read before creating or restructuring a persistent task, choosing task versus event, writing Goal/DoD/Manual/Verification, or setting control metadata and budgets.
3
+ description: Before creating or restructuring a persistent task, or choosing task versus event.
4
4
  requires-tools: task_manage
5
5
  priority: 40
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-recurring
3
- description: Read before creating, starting, rescheduling, pausing, completing a cycle of, or retiring a recurring task and its canonical schedule event.
3
+ description: Before creating, rescheduling, pausing, or retiring a recurring task and its schedule event.
4
4
  requires-tools: task_manage
5
5
  priority: 43
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-repair
3
- description: Read when a task is escalated, stalled, not waking, or has broken control metadata, stale approval/verification, terminal dependencies, or orphan events.
3
+ description: When a task is escalated, stalled, not waking, or has broken control metadata.
4
4
  requires-tools: task_manage
5
5
  priority: 44
6
6
  ---
@@ -478,7 +478,12 @@ export class EventsWatcher {
478
478
  scheduleInfo = event.schedule;
479
479
  break;
480
480
  }
481
- const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}`;
481
+ // The [SILENT] protocol only makes sense for periodic wakes, so it rides the
482
+ // periodic trigger rather than the always-on system prompt (spec 026 §7.3).
483
+ const periodicContract = event.type === "periodic"
484
+ ? " This is a periodic runtime wake. If it produces no user-visible change or result, reply with exactly [SILENT]."
485
+ : "";
486
+ const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}${periodicContract}`;
482
487
  // Create synthetic DingTalkEvent
483
488
  const syntheticEvent = {
484
489
  type: "dm",
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Prompt "units": a deterministic, tokenizer-free approximation of prompt size
3
+ * that is stable across models (spec 026 §5.1). Both the system-prompt builder and
4
+ * the per-turn memory context budget against it, so it is a real cross-domain helper
5
+ * — kept out of text-utils.ts on purpose, to avoid growing an unrelated grab bag.
6
+ *
7
+ * Counting rule:
8
+ * - each Han / Hiragana / Katakana / Hangul code point → 1 unit;
9
+ * - each run of Unicode letters/numbers (a non-CJK "word") → 1 unit;
10
+ * - punctuation and whitespace → 0.
11
+ *
12
+ * It never calls a tokenizer, the network or a model, and the same input always
13
+ * produces the same output.
14
+ */
15
+ /**
16
+ * Count prompt units in `text` in a single Unicode-aware pass.
17
+ *
18
+ * Known limitation: a single very long run of letters/numbers with no separators
19
+ * (base64, minified JS, a delimiter-free URL) counts as one unit. Such input is
20
+ * bounded by the character ceiling in `clipTextByPromptUnits` (`maxChars`), which
21
+ * is why every prompt and turn-context budget enforces both units and chars.
22
+ */
23
+ export declare function countPromptUnits(text: string): number;
24
+ export interface ClipByPromptUnitsOptions {
25
+ /** Fraction of the budget kept from the head; the rest is the tail. Default 0.6. */
26
+ headRatio?: number;
27
+ /** Separator shown where the middle was removed. Its own units/chars count against the budget. */
28
+ marker?: string;
29
+ /** Optional hard character ceiling; whichever of units/chars is hit first triggers truncation. */
30
+ maxChars?: number;
31
+ }
32
+ export interface ClipByPromptUnitsResult {
33
+ text: string;
34
+ /** Units in the original input. */
35
+ rawUnits: number;
36
+ /** Units actually kept (head + marker + tail), always ≤ maxUnits. */
37
+ injectedUnits: number;
38
+ truncated: boolean;
39
+ }
40
+ /**
41
+ * Clip `text` to at most `maxUnits` prompt units (and, when given, `maxChars`
42
+ * characters), keeping a head and a tail joined by `marker`. Cuts land only on
43
+ * code-point boundaries, so a surrogate pair is never split, and the marker is
44
+ * paid for out of the budget so the result never exceeds either limit.
45
+ */
46
+ export declare function clipTextByPromptUnits(text: string, maxUnits: number, options?: ClipByPromptUnitsOptions): ClipByPromptUnitsResult;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Prompt "units": a deterministic, tokenizer-free approximation of prompt size
3
+ * that is stable across models (spec 026 §5.1). Both the system-prompt builder and
4
+ * the per-turn memory context budget against it, so it is a real cross-domain helper
5
+ * — kept out of text-utils.ts on purpose, to avoid growing an unrelated grab bag.
6
+ *
7
+ * Counting rule:
8
+ * - each Han / Hiragana / Katakana / Hangul code point → 1 unit;
9
+ * - each run of Unicode letters/numbers (a non-CJK "word") → 1 unit;
10
+ * - punctuation and whitespace → 0.
11
+ *
12
+ * It never calls a tokenizer, the network or a model, and the same input always
13
+ * produces the same output.
14
+ */
15
+ /** A code point that is its own unit and always ends the surrounding word run. */
16
+ const CJK_REGEX = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
17
+ /** A code point that participates in a non-CJK word run. */
18
+ const WORD_REGEX = /[\p{L}\p{N}]/u;
19
+ function isCjk(codePoint) {
20
+ return CJK_REGEX.test(codePoint);
21
+ }
22
+ function isWord(codePoint) {
23
+ return WORD_REGEX.test(codePoint);
24
+ }
25
+ /**
26
+ * Count prompt units in `text` in a single Unicode-aware pass.
27
+ *
28
+ * Known limitation: a single very long run of letters/numbers with no separators
29
+ * (base64, minified JS, a delimiter-free URL) counts as one unit. Such input is
30
+ * bounded by the character ceiling in `clipTextByPromptUnits` (`maxChars`), which
31
+ * is why every prompt and turn-context budget enforces both units and chars.
32
+ */
33
+ export function countPromptUnits(text) {
34
+ let units = 0;
35
+ let inWord = false;
36
+ // `for...of` iterates code points, so surrogate pairs count as one character.
37
+ for (const char of text) {
38
+ if (isCjk(char)) {
39
+ units++;
40
+ inWord = false;
41
+ }
42
+ else if (isWord(char)) {
43
+ if (!inWord) {
44
+ units++;
45
+ inWord = true;
46
+ }
47
+ }
48
+ else {
49
+ inWord = false;
50
+ }
51
+ }
52
+ return units;
53
+ }
54
+ const DEFAULT_MARKER = "\n\n[... truncated ...]\n\n";
55
+ /**
56
+ * Clip `text` to at most `maxUnits` prompt units (and, when given, `maxChars`
57
+ * characters), keeping a head and a tail joined by `marker`. Cuts land only on
58
+ * code-point boundaries, so a surrogate pair is never split, and the marker is
59
+ * paid for out of the budget so the result never exceeds either limit.
60
+ */
61
+ export function clipTextByPromptUnits(text, maxUnits, options = {}) {
62
+ const headRatio = Math.max(0, Math.min(1, options.headRatio ?? 0.6));
63
+ const marker = options.marker ?? DEFAULT_MARKER;
64
+ const maxChars = options.maxChars;
65
+ const codePoints = Array.from(text);
66
+ const rawUnits = countPromptUnits(text);
67
+ const rawChars = text.length;
68
+ const withinUnits = rawUnits <= maxUnits;
69
+ const withinChars = maxChars === undefined || rawChars <= maxChars;
70
+ if (withinUnits && withinChars) {
71
+ return { text, rawUnits, injectedUnits: rawUnits, truncated: false };
72
+ }
73
+ // Cumulative units and characters after each code point, computed in one pass.
74
+ const cumulativeUnits = new Array(codePoints.length);
75
+ const cumulativeChars = new Array(codePoints.length);
76
+ let units = 0;
77
+ let chars = 0;
78
+ let inWord = false;
79
+ for (let index = 0; index < codePoints.length; index++) {
80
+ const char = codePoints[index];
81
+ if (isCjk(char)) {
82
+ units++;
83
+ inWord = false;
84
+ }
85
+ else if (isWord(char)) {
86
+ if (!inWord) {
87
+ units++;
88
+ inWord = true;
89
+ }
90
+ }
91
+ else {
92
+ inWord = false;
93
+ }
94
+ chars += char.length;
95
+ cumulativeUnits[index] = units;
96
+ cumulativeChars[index] = chars;
97
+ }
98
+ const markerUnits = countPromptUnits(marker);
99
+ const markerChars = marker.length;
100
+ // The marker is paid for out of the budget. If it alone would exceed either ceiling,
101
+ // keep nothing so the documented "injectedUnits ≤ maxUnits" / text ≤ maxChars contract
102
+ // still holds — the caller has sized the budget smaller than its own truncation marker.
103
+ if (markerUnits >= maxUnits || (maxChars !== undefined && markerChars >= maxChars)) {
104
+ return { text: "", rawUnits, injectedUnits: 0, truncated: true };
105
+ }
106
+ const availableUnits = Math.max(0, maxUnits - markerUnits);
107
+ const availableChars = maxChars === undefined ? Number.POSITIVE_INFINITY : Math.max(0, maxChars - markerChars);
108
+ const headUnitBudget = Math.floor(availableUnits * headRatio);
109
+ const tailUnitBudget = availableUnits - headUnitBudget;
110
+ const headCharBudget = Number.isFinite(availableChars) ? Math.floor(availableChars * headRatio) : availableChars;
111
+ const tailCharBudget = Number.isFinite(availableChars) ? availableChars - headCharBudget : availableChars;
112
+ // Largest prefix within both head budgets.
113
+ let headEnd = 0; // exclusive index into codePoints
114
+ for (let index = 0; index < codePoints.length; index++) {
115
+ const prefixUnits = cumulativeUnits[index];
116
+ const prefixChars = cumulativeChars[index];
117
+ if (prefixUnits <= headUnitBudget && prefixChars <= headCharBudget) {
118
+ headEnd = index + 1;
119
+ }
120
+ else {
121
+ break;
122
+ }
123
+ }
124
+ // Units of the suffix starting at `index`, derived from the forward cumulative
125
+ // counts. If a word run straddles the cut, both halves count it, so add one back.
126
+ const totalUnits = rawUnits;
127
+ const unitsFromIndex = (index) => {
128
+ if (index <= 0)
129
+ return totalUnits;
130
+ const prefixUnits = cumulativeUnits[index - 1];
131
+ const left = codePoints[index - 1];
132
+ const right = codePoints[index];
133
+ const split = isWord(left) && !isCjk(left) && isWord(right) && !isCjk(right);
134
+ return totalUnits - prefixUnits + (split ? 1 : 0);
135
+ };
136
+ const charsFromIndex = (index) => {
137
+ if (index <= 0)
138
+ return rawChars;
139
+ return rawChars - cumulativeChars[index - 1];
140
+ };
141
+ // Smallest start index (largest suffix) within both tail budgets and not overlapping the head.
142
+ let tailStart = codePoints.length;
143
+ for (let index = headEnd; index <= codePoints.length; index++) {
144
+ if (unitsFromIndex(index) <= tailUnitBudget && charsFromIndex(index) <= tailCharBudget) {
145
+ tailStart = index;
146
+ break;
147
+ }
148
+ }
149
+ const head = codePoints.slice(0, headEnd).join("");
150
+ const tail = codePoints.slice(tailStart).join("");
151
+ const clipped = `${head.trimEnd()}${marker}${tail.trimStart()}`;
152
+ return { text: clipped, rawUnits, injectedUnits: countPromptUnits(clipped), truncated: true };
153
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.8.7-beta.1",
3
+ "version": "0.8.7-beta.2",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {