@oyasmi/pipiclaw 0.7.5 → 0.7.7

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 (54) hide show
  1. package/README.md +11 -1
  2. package/dist/agent/channel-runner.js +7 -3
  3. package/dist/agent/commands.js +2 -1
  4. package/dist/agent/job-manager.d.ts +79 -0
  5. package/dist/agent/job-manager.js +241 -0
  6. package/dist/agent/prompt-builder.js +13 -4
  7. package/dist/agent/session-events.js +5 -0
  8. package/dist/memory/recall.js +6 -0
  9. package/dist/memory/review-log.d.ts +1 -1
  10. package/dist/models/api-keys.d.ts +5 -1
  11. package/dist/models/api-keys.js +10 -4
  12. package/dist/runtime/bootstrap.js +2 -0
  13. package/dist/runtime/dingtalk.js +13 -1
  14. package/dist/runtime/task-commands.d.ts +3 -0
  15. package/dist/runtime/task-commands.js +148 -2
  16. package/dist/shared/atomic-file.js +23 -3
  17. package/dist/shared/task-events.d.ts +32 -0
  18. package/dist/shared/task-events.js +29 -0
  19. package/dist/shared/task-ledger.d.ts +26 -0
  20. package/dist/shared/task-ledger.js +38 -0
  21. package/dist/subagents/tool.js +26 -4
  22. package/dist/tools/bash.d.ts +12 -0
  23. package/dist/tools/bash.js +67 -1
  24. package/dist/tools/config.d.ts +9 -0
  25. package/dist/tools/config.js +23 -0
  26. package/dist/tools/edit.js +0 -0
  27. package/dist/tools/grep.d.ts +19 -0
  28. package/dist/tools/grep.js +262 -0
  29. package/dist/tools/index.js +5 -0
  30. package/dist/tools/job.d.ts +13 -0
  31. package/dist/tools/job.js +92 -0
  32. package/dist/tools/memory-manage.d.ts +24 -0
  33. package/dist/tools/memory-manage.js +150 -0
  34. package/dist/tools/read.js +103 -16
  35. package/dist/tools/registry.d.ts +7 -1
  36. package/dist/tools/registry.js +31 -23
  37. package/dist/tools/session-search.js +4 -1
  38. package/dist/tools/skill-manage.d.ts +12 -5
  39. package/dist/tools/skill-manage.js +113 -15
  40. package/dist/tools/task-manage.d.ts +16 -2
  41. package/dist/tools/task-manage.js +119 -22
  42. package/dist/tools/web-cache.d.ts +11 -0
  43. package/dist/tools/web-cache.js +62 -0
  44. package/dist/tools/web-fetch.d.ts +3 -0
  45. package/dist/tools/web-fetch.js +73 -5
  46. package/dist/tui/app.js +1 -1
  47. package/dist/tui/commands.js +1 -1
  48. package/package.json +1 -1
  49. package/dist/tools/memory-save.d.ts +0 -16
  50. package/dist/tools/memory-save.js +0 -42
  51. package/dist/tools/skill-list.d.ts +0 -18
  52. package/dist/tools/skill-list.js +0 -86
  53. package/dist/tools/skill-view.d.ts +0 -13
  54. package/dist/tools/skill-view.js +0 -44
@@ -4,25 +4,35 @@ import { join } from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import { parseScheduledEventContent } from "../runtime/events.js";
6
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
7
- import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, taskBody } from "../shared/task-ledger.js";
7
+ import { isTaskScheduleEvent, taskEventPrefix, taskScheduleEventFilename } from "../shared/task-events.js";
8
+ import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, taskBody, } from "../shared/task-ledger.js";
8
9
  const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked"];
9
10
  const taskManageSchema = Type.Object({
10
11
  label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
11
- action: Type.Union([Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
12
- description: '"set" updates a task\'s status/wake/recurrence; "done" closes it out (archive one-shot tasks, clean up residual events); "list" returns active tasks.',
12
+ action: Type.Union([Type.Literal("create"), Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
13
+ description: '"create" writes a standard task skeleton; "set" updates status/wake/recurrence; "done" closes it out and requires summary/evidence; "list" returns active tasks.',
13
14
  }),
14
- id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for set/done." })),
15
- status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for set. To close a task use action done, not status." })),
15
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/set/done." })),
16
+ title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
17
+ goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
18
+ dod: Type.Optional(Type.String({ description: "Required for create: acceptance criteria / definition of done." })),
19
+ manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
20
+ status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/set. To close a task use action done, not status." })),
16
21
  wake: Type.Optional(Type.String({
17
22
  description: "ISO8601 earliest-recheck time for set; empty string clears it. Keep in sync with any .checkin event.",
18
23
  })),
19
24
  recurrence: Type.Optional(Type.String({ description: "Annotation only (e.g. 每周一); empty string clears it." })),
25
+ summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
26
+ evidence: Type.Optional(Type.String({
27
+ description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
28
+ })),
29
+ residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
20
30
  });
21
31
  function parseAction(action) {
22
- if (action === "set" || action === "done" || action === "list") {
32
+ if (action === "create" || action === "set" || action === "done" || action === "list") {
23
33
  return action;
24
34
  }
25
- throw new Error('Unsupported task action. Use "set", "done", or "list".');
35
+ throw new Error('Unsupported task action. Use "create", "set", "done", or "list".');
26
36
  }
27
37
  function toWorkspacePath(options, hostPath) {
28
38
  if (hostPath.startsWith(options.workspaceDir)) {
@@ -45,6 +55,54 @@ function renderTaskFile(fields, body) {
45
55
  lines.push("---");
46
56
  return `${lines.join("\n")}\n${body}`;
47
57
  }
58
+ function requiredField(value, field, action) {
59
+ const trimmed = value?.trim();
60
+ if (!trimmed) {
61
+ throw new Error(`action "${action}" requires ${field}.`);
62
+ }
63
+ return trimmed;
64
+ }
65
+ function requireNonEmpty(value, field) {
66
+ return requiredField(value, field, "done");
67
+ }
68
+ function markdownValue(value) {
69
+ const lines = value.trim().split(/\r?\n/);
70
+ if (lines.length === 1)
71
+ return lines[0];
72
+ return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
73
+ }
74
+ function appendCompletionEvidence(body, request) {
75
+ const summary = requireNonEmpty(request.summary, "summary");
76
+ const evidence = requireNonEmpty(request.evidence, "evidence");
77
+ const lines = [
78
+ "## Completion Evidence",
79
+ "",
80
+ `- Summary: ${markdownValue(summary)}`,
81
+ `- Evidence: ${markdownValue(evidence)}`,
82
+ ];
83
+ const residualRisk = request.residualRisk?.trim();
84
+ if (residualRisk) {
85
+ lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
86
+ }
87
+ const normalizedBody = body.endsWith("\n") ? body.replace(/\n+$/, "\n") : `${body}\n`;
88
+ return `${normalizedBody}\n${lines.join("\n")}\n`;
89
+ }
90
+ function normalizeCreateStatus(status) {
91
+ if (status === undefined)
92
+ return "open";
93
+ if (SETTABLE_STATUSES.includes(status)) {
94
+ return status;
95
+ }
96
+ throw new Error(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
97
+ }
98
+ function renderTaskSkeleton(request) {
99
+ const title = requiredField(request.title, "title", "create");
100
+ const goal = requiredField(request.goal, "goal", "create");
101
+ const dod = requiredField(request.dod, "dod", "create");
102
+ const fields = applySet({ status: normalizeCreateStatus(request.status) }, request);
103
+ const body = renderStandardTaskBody({ title, goal, dod, manual: request.manual });
104
+ return { fields, body };
105
+ }
48
106
  /**
49
107
  * Read a task file and split it into its three-field frontmatter and verbatim body.
50
108
  * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
@@ -95,19 +153,47 @@ function applySet(fields, request) {
95
153
  }
96
154
  return next;
97
155
  }
156
+ async function createTask(options, request) {
157
+ if (!request.id)
158
+ throw new Error('action "create" requires an id.');
159
+ const id = normalizeTaskId(request.id);
160
+ const dir = tasksDir(options);
161
+ const taskPath = join(dir, `${id}.md`);
162
+ const archivePath = join(dir, "archive", `${id}.md`);
163
+ if (existsSync(taskPath)) {
164
+ throw new Error(`Task "${id}" already exists; use action "set" or edit the body instead.`);
165
+ }
166
+ if (existsSync(archivePath)) {
167
+ throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
168
+ }
169
+ const { fields, body } = renderTaskSkeleton(request);
170
+ await mkdir(dir, { recursive: true });
171
+ await writeFileAtomically(taskPath, renderTaskFile(fields, body));
172
+ return {
173
+ action: "create",
174
+ id,
175
+ path: toWorkspacePath(options, taskPath),
176
+ status: fields.status,
177
+ notice: `已创建任务 \`${id}\`(status: ${fields.status})。`,
178
+ };
179
+ }
98
180
  /**
99
- * On close-out, delete residual one-shot/immediate events named `task.<channelId>.<id>.*`
100
- * and report whether a periodic (schedule) event survives. Unparseable events with the
101
- * prefix are left untouched (fail-safe: don't blind-delete something we can't classify).
181
+ * On close-out, keep only the task's recurring cadence event
182
+ * (`task.<channelId>.<id>.schedule`) and delete every other task-owned event.
183
+ *
184
+ * A task may also own temporary periodic events (for example an agentmux idle sensor).
185
+ * Those are lifecycle check-ins, not proof that the task itself is recurring, so they
186
+ * must not prevent a one-shot task from being archived.
102
187
  */
103
188
  async function cleanupTaskEvents(options, id) {
104
189
  const dir = eventsDir(options);
105
190
  if (!existsSync(dir))
106
- return { deleted: [], hasPeriodic: false };
107
- const prefix = `task.${options.channelId}.${id}.`;
191
+ return { deleted: [], hasSchedule: false };
192
+ const prefix = taskEventPrefix(options.channelId, id);
193
+ const scheduleFilename = taskScheduleEventFilename(options.channelId, id);
108
194
  const deleted = [];
109
- let hasPeriodic = false;
110
- for (const filename of await readdir(dir)) {
195
+ let hasSchedule = false;
196
+ for (const filename of (await readdir(dir)).sort()) {
111
197
  if (!filename.endsWith(".json") || !filename.startsWith(prefix))
112
198
  continue;
113
199
  const eventPath = join(dir, filename);
@@ -118,14 +204,14 @@ async function cleanupTaskEvents(options, id) {
118
204
  catch {
119
205
  continue; // can't classify → leave it for /events to handle
120
206
  }
121
- if (type === "periodic") {
122
- hasPeriodic = true; // the cadence lives on for the next cycle
207
+ if (filename === scheduleFilename && isTaskScheduleEvent({ use: "schedule", event: { type } })) {
208
+ hasSchedule = true; // the cadence lives on for the next cycle
123
209
  continue;
124
210
  }
125
211
  await unlink(eventPath);
126
212
  deleted.push(filename.slice(0, -".json".length));
127
213
  }
128
- return { deleted, hasPeriodic };
214
+ return { deleted, hasSchedule };
129
215
  }
130
216
  async function setTask(options, request) {
131
217
  if (!request.id)
@@ -150,12 +236,13 @@ async function doneTask(options, request) {
150
236
  const dir = tasksDir(options);
151
237
  const taskPath = join(dir, `${id}.md`);
152
238
  const { fields, body } = await readTaskDocument(taskPath, id);
153
- await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, body));
154
- const { deleted, hasPeriodic } = await cleanupTaskEvents(options, id);
239
+ const bodyWithEvidence = appendCompletionEvidence(body, request);
240
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, bodyWithEvidence));
241
+ const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
155
242
  // Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
156
243
  let archived = false;
157
244
  let finalPath = taskPath;
158
- if (!hasPeriodic) {
245
+ if (!hasSchedule) {
159
246
  const archiveDir = join(dir, "archive");
160
247
  await mkdir(archiveDir, { recursive: true });
161
248
  finalPath = join(archiveDir, `${id}.md`);
@@ -190,6 +277,8 @@ async function listTasks(options) {
190
277
  }
191
278
  export async function manageTask(options, request) {
192
279
  switch (request.action) {
280
+ case "create":
281
+ return createTask(options, request);
193
282
  case "set":
194
283
  return setTask(options, request);
195
284
  case "done":
@@ -203,16 +292,24 @@ export function createTaskManageTool(options) {
203
292
  name: "task_manage",
204
293
  label: "task_manage",
205
294
  description: "Manage this channel's task ledger frontmatter and lifecycle: set status/wake/recurrence, close a task out " +
206
- "(archiving one-shot tasks and cleaning up its residual events), or list active tasks. Write the task body " +
207
- "(goal, DoD, manual, cycle log) with write/edit; this tool owns only the frontmatter and close-out.",
295
+ "(requiring summary/evidence, archiving one-shot tasks, and cleaning up residual events), or list active " +
296
+ "tasks. Write the task body (goal, DoD, manual, cycle log) with write/edit; this tool owns only the " +
297
+ "frontmatter and close-out evidence.",
208
298
  parameters: taskManageSchema,
209
299
  execute: async (_toolCallId, args) => {
210
300
  const result = await manageTask(options, {
211
301
  action: parseAction(args.action),
212
302
  id: args.id,
303
+ title: args.title,
304
+ goal: args.goal,
305
+ dod: args.dod,
306
+ manual: args.manual,
213
307
  status: args.status,
214
308
  wake: args.wake,
215
309
  recurrence: args.recurrence,
310
+ summary: args.summary,
311
+ evidence: args.evidence,
312
+ residualRisk: args.residualRisk,
216
313
  });
217
314
  return {
218
315
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
@@ -0,0 +1,11 @@
1
+ export declare const WEB_CACHE_TTL_MS: number;
2
+ export interface WebCacheEntry {
3
+ body: string;
4
+ fetchedAt: number;
5
+ }
6
+ /** Cache key from the requested URL plus extract mode (markdown vs text render differently). */
7
+ export declare function webCacheKey(url: string, extractMode: string): string;
8
+ /** Return the cached body if present and within the TTL, else null. */
9
+ export declare function readWebCache(channelDir: string, key: string, ttlMs?: number): Promise<WebCacheEntry | null>;
10
+ /** Persist a body and evict the oldest entries beyond the cap. Best-effort; never throws. */
11
+ export declare function writeWebCache(channelDir: string, key: string, body: string): Promise<void>;
@@ -0,0 +1,62 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { writeFileAtomically } from "../shared/atomic-file.js";
6
+ /**
7
+ * Small per-channel cache of fetched web page bodies so a long page can be paged over with `offset`
8
+ * without re-issuing the (slow, non-deterministic) HTTP request. Bodies are the clean extracted text
9
+ * — the banner and windowing are re-applied by the tool on each read.
10
+ */
11
+ const WEB_CACHE_DIR = "web-cache";
12
+ export const WEB_CACHE_TTL_MS = 15 * 60 * 1000;
13
+ const WEB_CACHE_MAX_FILES = 20;
14
+ function cacheDir(channelDir) {
15
+ return join(channelDir, WEB_CACHE_DIR);
16
+ }
17
+ /** Cache key from the requested URL plus extract mode (markdown vs text render differently). */
18
+ export function webCacheKey(url, extractMode) {
19
+ return createHash("sha256").update(`${extractMode}\n${url}`).digest("hex").slice(0, 24);
20
+ }
21
+ function bodyPath(channelDir, key) {
22
+ return join(cacheDir(channelDir), `${key}.txt`);
23
+ }
24
+ /** Return the cached body if present and within the TTL, else null. */
25
+ export async function readWebCache(channelDir, key, ttlMs = WEB_CACHE_TTL_MS) {
26
+ const path = bodyPath(channelDir, key);
27
+ try {
28
+ const stats = await stat(path);
29
+ // `>=` so a TTL of 0 means "always refetch" rather than depending on sub-ms timing.
30
+ if (Date.now() - stats.mtimeMs >= ttlMs) {
31
+ return null;
32
+ }
33
+ return { body: await readFile(path, "utf-8"), fetchedAt: stats.mtimeMs };
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /** Persist a body and evict the oldest entries beyond the cap. Best-effort; never throws. */
40
+ export async function writeWebCache(channelDir, key, body) {
41
+ try {
42
+ const dir = cacheDir(channelDir);
43
+ if (!existsSync(dir)) {
44
+ await mkdir(dir, { recursive: true });
45
+ }
46
+ await writeFileAtomically(bodyPath(channelDir, key), body);
47
+ await pruneWebCache(dir);
48
+ }
49
+ catch {
50
+ // Caching is an optimization; a failure just means the next read refetches.
51
+ }
52
+ }
53
+ async function pruneWebCache(dir) {
54
+ const files = (await readdir(dir)).filter((name) => name.endsWith(".txt"));
55
+ if (files.length <= WEB_CACHE_MAX_FILES) {
56
+ return;
57
+ }
58
+ const withTimes = await Promise.all(files.map(async (name) => ({ name, mtimeMs: (await stat(join(dir, name)).catch(() => null))?.mtimeMs ?? 0 })));
59
+ withTimes.sort((a, b) => a.mtimeMs - b.mtimeMs);
60
+ const excess = withTimes.slice(0, withTimes.length - WEB_CACHE_MAX_FILES);
61
+ await Promise.all(excess.map((entry) => rm(join(dir, entry.name), { force: true })));
62
+ }
@@ -7,12 +7,15 @@ declare const webFetchSchema: Type.TObject<{
7
7
  url: Type.TString;
8
8
  extractMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"markdown">, Type.TLiteral<"text">]>>;
9
9
  maxChars: Type.TOptional<Type.TNumber>;
10
+ offset: Type.TOptional<Type.TInteger>;
10
11
  }>;
11
12
  export interface WebFetchToolOptions {
12
13
  webConfig: PipiclawWebToolsConfig;
13
14
  securityConfig: SecurityConfig;
14
15
  workspaceDir: string;
15
16
  channelId?: string;
17
+ /** Present on the main path; enables per-channel body caching + offset pagination. */
18
+ channelDir?: string;
16
19
  }
17
20
  export declare function createWebFetchTool(options: WebFetchToolOptions): AgentTool<typeof webFetchSchema>;
18
21
  export {};
@@ -1,29 +1,97 @@
1
1
  import { Type } from "typebox";
2
2
  import { resolveWebFetchRequest } from "../web/config.js";
3
3
  import { runWebFetch } from "../web/fetch.js";
4
+ import { formatFetchedText, UNTRUSTED_WEB_CONTENT_BANNER } from "../web/format.js";
5
+ import { readWebCache, webCacheKey, writeWebCache } from "./web-cache.js";
6
+ // Large cap used to fetch the full readable body for caching; the displayed window is bounded by the
7
+ // configured/requested maxChars. Still smaller than maxResponseBytes so a hostile page can't OOM us.
8
+ const FULL_FETCH_MAX_CHARS = 2_000_000;
4
9
  const webFetchSchema = Type.Object({
5
10
  label: Type.String({ description: "Brief description of what you're fetching and why (shown to user)" }),
6
11
  url: Type.String({ description: "HTTP or HTTPS URL to fetch" }),
7
12
  extractMode: Type.Optional(Type.Union([Type.Literal("markdown"), Type.Literal("text")], {
8
13
  description: "Preferred text extraction format for HTML pages",
9
14
  })),
10
- maxChars: Type.Optional(Type.Number({ description: "Maximum extracted text characters to return" })),
15
+ maxChars: Type.Optional(Type.Number({ description: "Maximum extracted text characters to return per call" })),
16
+ offset: Type.Optional(Type.Integer({
17
+ minimum: 0,
18
+ description: "Character offset into the page body to start from. Use the offset the previous call reported to page through a long page — it is served from cache with no refetch.",
19
+ })),
11
20
  });
21
+ /** Strip the untrusted-content banner that runWebFetch prepends, so the cached body is clean. */
22
+ function stripBanner(text) {
23
+ if (text.startsWith(UNTRUSTED_WEB_CONTENT_BANNER)) {
24
+ return text.slice(UNTRUSTED_WEB_CONTENT_BANNER.length).replace(/^\n+/, "");
25
+ }
26
+ return text;
27
+ }
28
+ function windowResult(body, offset, maxChars, url, fromCache) {
29
+ const start = Math.min(offset, body.length);
30
+ const end = Math.min(start + maxChars, body.length);
31
+ const slice = body.slice(start, end);
32
+ let text = formatFetchedText(slice);
33
+ if (end < body.length) {
34
+ const cacheNote = fromCache ? " (served from cache, no refetch)" : "";
35
+ text += `\n\n[Showing chars ${start}-${end} of ${body.length}. Re-call web_fetch with the same url and offset=${end} to continue${cacheNote}.]`;
36
+ }
37
+ else if (offset >= body.length && body.length > 0) {
38
+ text += `\n\n[Reached end of page (${body.length} chars). No more content.]`;
39
+ }
40
+ return {
41
+ content: [{ type: "text", text }],
42
+ details: {
43
+ kind: "web_fetch",
44
+ url,
45
+ offset: start,
46
+ shownChars: slice.length,
47
+ totalChars: body.length,
48
+ fromCache,
49
+ untrusted: true,
50
+ },
51
+ };
52
+ }
12
53
  export function createWebFetchTool(options) {
13
54
  return {
14
55
  name: "web_fetch",
15
56
  label: "web_fetch",
16
- description: "Fetch a public URL and extract readable content. Returns text for HTML/JSON/text pages and image content blocks for images.",
57
+ description: "Fetch a public URL and extract readable content. Returns text for HTML/JSON/text pages and image content " +
58
+ "blocks for images. Long pages are cached per channel; page through them with offset (no refetch).",
17
59
  parameters: webFetchSchema,
18
- execute: async (_toolCallId, { url, extractMode, maxChars, }, signal) => {
60
+ execute: async (_toolCallId, { url, extractMode, maxChars, offset, }, signal) => {
19
61
  const request = resolveWebFetchRequest(options.webConfig.fetch, url, extractMode, maxChars);
62
+ const displayMaxChars = request.maxChars;
63
+ const startOffset = offset && offset > 0 ? offset : 0;
64
+ // Cache is per-channel; when no channelDir is available (e.g. sub-agent path) fall back to a
65
+ // plain single-shot fetch with the requested maxChars.
66
+ if (!options.channelDir) {
67
+ return runWebFetch({
68
+ webConfig: options.webConfig,
69
+ securityConfig: options.securityConfig,
70
+ workspaceDir: options.workspaceDir,
71
+ channelId: options.channelId,
72
+ }, request, signal);
73
+ }
74
+ const key = webCacheKey(url, request.extractMode);
75
+ const cached = await readWebCache(options.channelDir, key);
76
+ if (cached) {
77
+ return windowResult(cached.body, startOffset, displayMaxChars, url, true);
78
+ }
79
+ // Cache miss: fetch the full readable body once, cache it, then serve the window.
20
80
  const result = await runWebFetch({
21
81
  webConfig: options.webConfig,
22
82
  securityConfig: options.securityConfig,
23
83
  workspaceDir: options.workspaceDir,
24
84
  channelId: options.channelId,
25
- }, request, signal);
26
- return result;
85
+ }, { ...request, maxChars: FULL_FETCH_MAX_CHARS }, signal);
86
+ // Images (and any non-text result) are passed through unchanged — nothing to page or cache.
87
+ const hasImage = result.content.some((part) => part.type === "image");
88
+ const textPart = result.content.find((part) => part.type === "text");
89
+ if (hasImage || !textPart || textPart.type !== "text") {
90
+ return result;
91
+ }
92
+ const body = stripBanner(textPart.text);
93
+ await writeWebCache(options.channelDir, key, body);
94
+ return windowResult(body, startOffset, displayMaxChars, url, false);
27
95
  },
28
96
  };
29
97
  }
package/dist/tui/app.js CHANGED
@@ -89,7 +89,7 @@ export async function runTuiApp(options) {
89
89
  renderHelp: () => renderBuiltInHelp(),
90
90
  renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
91
91
  runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
92
- runTasks: (args) => handleTasksCommand({ args, channelDir }),
92
+ runTasks: (args) => handleTasksCommand({ args, channelDir, workspaceDir: paths.workspaceDir, channelId }),
93
93
  statusInfo: { version: readCliVersion(), sandbox, startedAt: Date.now() },
94
94
  });
95
95
  try {
@@ -58,7 +58,7 @@ export const TUI_SLASH_COMMANDS = [
58
58
  { name: "status", description: "Show model, context and run state" },
59
59
  { name: "usage", description: "Show LLM cost for this channel", argumentHint: "[7d|month]" },
60
60
  { name: "events", description: "Manage scheduled events", argumentHint: "<list|show|delete|history>" },
61
- { name: "tasks", description: "View the task ledger (read-only)", argumentHint: "[show <id>|archive]" },
61
+ { name: "tasks", description: "View the task ledger (read-only)", argumentHint: "[show <id>|archive|doctor]" },
62
62
  { name: "model", description: "Show or switch the model", argumentHint: "[provider/model]" },
63
63
  { name: "new", description: "Start a new session" },
64
64
  { name: "compact", description: "Compact the session context", argumentHint: "[instructions]" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
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": {
@@ -1,16 +0,0 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { Type } from "typebox";
3
- import type { MemoryCandidateStore } from "../memory/candidates.js";
4
- import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
5
- declare const memorySaveSchema: Type.TObject<{
6
- content: Type.TString;
7
- kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">]>>;
8
- }>;
9
- export interface MemorySaveToolOptions {
10
- channelId: string;
11
- channelDir: string;
12
- memoryCandidateStore: MemoryCandidateStore;
13
- channelMemoryQueue?: ChannelMemoryQueue;
14
- }
15
- export declare function createMemorySaveTool(options: MemorySaveToolOptions): AgentTool<typeof memorySaveSchema>;
16
- export {};
@@ -1,42 +0,0 @@
1
- import { Type } from "typebox";
2
- import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
3
- import { applyChannelMemoryOps, getChannelMemoryPath } from "../memory/files.js";
4
- const memorySaveSchema = Type.Object({
5
- content: Type.String({
6
- description: "The durable fact to remember, as a single self-contained, keyword-rich sentence. Write it so future keyword search can find it.",
7
- }),
8
- kind: Type.Optional(Type.Union([
9
- Type.Literal("preference"),
10
- Type.Literal("fact"),
11
- Type.Literal("decision"),
12
- Type.Literal("constraint"),
13
- Type.Literal("open-loop"),
14
- ], { description: "What kind of durable memory this is." })),
15
- });
16
- export function createMemorySaveTool(options) {
17
- const queue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
18
- return {
19
- name: "memory_save",
20
- label: "memory_save",
21
- description: "Save a durable fact to this channel's long-term MEMORY.md immediately. Use when the user explicitly asks you to remember something (a preference, decision, constraint, or long-running commitment), so it survives restarts and future sessions. Do not use for transient task state — that is captured automatically.",
22
- parameters: memorySaveSchema,
23
- execute: async (_toolCallId, { content, kind }) => {
24
- const trimmed = content.trim();
25
- if (!trimmed) {
26
- return {
27
- content: [{ type: "text", text: "No content provided; nothing was saved." }],
28
- details: { kind: "memory_save", saved: false },
29
- };
30
- }
31
- // Serialize through the shared channel memory queue so this never races with
32
- // background consolidation/maintenance on the same channel's files.
33
- const result = await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "add", content: trimmed }]));
34
- // Make the new memory recallable within this same turn.
35
- options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
36
- return {
37
- content: [{ type: "text", text: `Saved to channel memory${kind ? ` (${kind})` : ""}.` }],
38
- details: { kind: "memory_save", saved: result.added > 0 },
39
- };
40
- },
41
- };
42
- }
@@ -1,18 +0,0 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { Type } from "typebox";
3
- declare const skillListSchema: Type.TObject<{
4
- label: Type.TString;
5
- }>;
6
- export interface WorkspaceSkillSummary {
7
- name: string;
8
- description: string;
9
- path: string;
10
- warning?: string;
11
- }
12
- export interface SkillListToolOptions {
13
- workspaceDir: string;
14
- workspacePath: string;
15
- }
16
- export declare function listWorkspaceSkills(options: SkillListToolOptions): Promise<WorkspaceSkillSummary[]>;
17
- export declare function createSkillListTool(options: SkillListToolOptions): AgentTool<typeof skillListSchema>;
18
- export {};
@@ -1,86 +0,0 @@
1
- import { readdir, readFile, stat } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { Type } from "typebox";
4
- import { validateSkillFrontmatter, validateSkillName } from "./skill-security.js";
5
- const skillListSchema = Type.Object({
6
- label: Type.String({ description: "Brief description of why you're listing workspace skills (shown to user)" }),
7
- });
8
- function extractDescription(content) {
9
- const match = content.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
10
- if (!match) {
11
- return "";
12
- }
13
- for (const line of (match[1] ?? "").split("\n")) {
14
- const fieldMatch = line.match(/^description:\s*(.*)$/);
15
- if (fieldMatch) {
16
- return fieldMatch[1].replace(/^["']|["']$/g, "").trim();
17
- }
18
- }
19
- return "";
20
- }
21
- function isNodeError(error) {
22
- return error instanceof Error && "code" in error;
23
- }
24
- export async function listWorkspaceSkills(options) {
25
- const skillsDir = join(options.workspaceDir, "skills");
26
- let names;
27
- try {
28
- names = await readdir(skillsDir);
29
- }
30
- catch (error) {
31
- if (isNodeError(error) && error.code === "ENOENT") {
32
- return [];
33
- }
34
- throw error;
35
- }
36
- const summaries = [];
37
- for (const name of names.sort()) {
38
- const nameValidation = validateSkillName(name);
39
- if (!nameValidation.ok) {
40
- continue;
41
- }
42
- const skillDir = join(skillsDir, name);
43
- const skillStats = await stat(skillDir).catch(() => null);
44
- if (!skillStats?.isDirectory()) {
45
- continue;
46
- }
47
- const skillPath = join(skillDir, "SKILL.md");
48
- let content;
49
- try {
50
- const skillFileStats = await stat(skillPath);
51
- if (!skillFileStats.isFile()) {
52
- continue;
53
- }
54
- content = await readFile(skillPath, "utf-8");
55
- }
56
- catch (error) {
57
- if (isNodeError(error) && error.code === "ENOENT") {
58
- continue;
59
- }
60
- throw error;
61
- }
62
- const validation = validateSkillFrontmatter(content, name);
63
- summaries.push({
64
- name,
65
- description: extractDescription(content),
66
- path: `${options.workspacePath}/skills/${name}/SKILL.md`,
67
- warning: validation.ok ? undefined : validation.error,
68
- });
69
- }
70
- return summaries;
71
- }
72
- export function createSkillListTool(options) {
73
- return {
74
- name: "skill_list",
75
- label: "skill_list",
76
- description: "List workspace-level Pipiclaw skills that can be viewed or managed.",
77
- parameters: skillListSchema,
78
- execute: async () => {
79
- const skills = await listWorkspaceSkills(options);
80
- return {
81
- content: [{ type: "text", text: JSON.stringify({ skills }) }],
82
- details: { kind: "skill_list", count: skills.length },
83
- };
84
- },
85
- };
86
- }
@@ -1,13 +0,0 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { Type } from "typebox";
3
- declare const skillViewSchema: Type.TObject<{
4
- label: Type.TString;
5
- name: Type.TString;
6
- filePath: Type.TOptional<Type.TString>;
7
- }>;
8
- export interface SkillViewToolOptions {
9
- workspaceDir: string;
10
- workspacePath: string;
11
- }
12
- export declare function createSkillViewTool(options: SkillViewToolOptions): AgentTool<typeof skillViewSchema>;
13
- export {};