@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.3

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 (79) hide show
  1. package/dist/agent/job-manager.d.ts +9 -0
  2. package/dist/agent/job-manager.js +20 -6
  3. package/dist/agent/prompt/builder.d.ts +1 -1
  4. package/dist/agent/prompt/builder.js +1 -1
  5. package/dist/agent/prompt/sections.js +3 -3
  6. package/dist/executor.d.ts +5 -1
  7. package/dist/executor.js +35 -5
  8. package/dist/file-store.d.ts +4 -1
  9. package/dist/file-store.js +5 -0
  10. package/dist/memory/journal.d.ts +13 -0
  11. package/dist/memory/journal.js +47 -4
  12. package/dist/memory/search.js +13 -6
  13. package/dist/memory/session-corpus.d.ts +11 -0
  14. package/dist/memory/session-corpus.js +15 -4
  15. package/dist/memory/session-search.d.ts +3 -0
  16. package/dist/memory/session-search.js +45 -8
  17. package/dist/memory/store.d.ts +9 -0
  18. package/dist/memory/store.js +25 -2
  19. package/dist/playbooks/agent-delegation.md +35 -76
  20. package/dist/playbooks/background-jobs.md +14 -16
  21. package/dist/playbooks/event-scheduling.md +20 -25
  22. package/dist/playbooks/memory-and-learning.md +28 -61
  23. package/dist/playbooks/outbound-media.md +10 -12
  24. package/dist/playbooks/runtime-orientation.md +34 -53
  25. package/dist/playbooks/task-loop.md +49 -69
  26. package/dist/runtime/bootstrap.js +25 -11
  27. package/dist/security/path-guard-filter.d.ts +22 -0
  28. package/dist/security/path-guard-filter.js +35 -0
  29. package/dist/subagents/discovery.d.ts +2 -3
  30. package/dist/subagents/discovery.js +3 -1
  31. package/dist/subagents/tool.d.ts +6 -0
  32. package/dist/subagents/tool.js +10 -2
  33. package/dist/tasks/brief.d.ts +1 -1
  34. package/dist/tasks/brief.js +11 -2
  35. package/dist/tasks/log.d.ts +4 -0
  36. package/dist/tasks/log.js +13 -1
  37. package/dist/tools/bash.d.ts +13 -0
  38. package/dist/tools/bash.js +123 -20
  39. package/dist/tools/edit.js +36 -5
  40. package/dist/tools/event-manage.d.ts +25 -4
  41. package/dist/tools/event-manage.js +81 -33
  42. package/dist/tools/glob.js +57 -4
  43. package/dist/tools/grep.d.ts +2 -0
  44. package/dist/tools/grep.js +187 -14
  45. package/dist/tools/job.js +16 -4
  46. package/dist/tools/memory-manage.js +80 -41
  47. package/dist/tools/read.js +42 -5
  48. package/dist/tools/registry.d.ts +6 -0
  49. package/dist/tools/registry.js +4 -1
  50. package/dist/tools/send-media.js +6 -4
  51. package/dist/tools/session-search.js +4 -1
  52. package/dist/tools/skill.d.ts +2 -0
  53. package/dist/tools/skill.js +12 -0
  54. package/dist/tools/subagent-manage.js +1 -1
  55. package/dist/tools/subagent-tool-names.d.ts +11 -0
  56. package/dist/tools/subagent-tool-names.js +19 -0
  57. package/dist/tools/task-manage/log-view.js +6 -3
  58. package/dist/tools/task-manage/schema.d.ts +6 -6
  59. package/dist/tools/task-manage/schema.js +5 -12
  60. package/dist/tools/task-manage/shared.js +16 -2
  61. package/dist/tools/task-manage/step-end.js +22 -5
  62. package/dist/tools/task-manage.js +9 -1
  63. package/dist/tools/web-cache.d.ts +11 -3
  64. package/dist/tools/web-cache.js +26 -8
  65. package/dist/tools/web-fetch.d.ts +1 -0
  66. package/dist/tools/web-fetch.js +68 -15
  67. package/dist/tools/write.js +3 -0
  68. package/dist/web/fetch.d.ts +5 -0
  69. package/dist/web/fetch.js +36 -1
  70. package/examples/sub-agents/README.md +14 -4
  71. package/examples/sub-agents/builder-hard.md +12 -34
  72. package/examples/sub-agents/builder.md +11 -31
  73. package/examples/sub-agents/explorer.md +10 -16
  74. package/examples/sub-agents/git-committer.md +15 -20
  75. package/examples/sub-agents/planner.md +11 -21
  76. package/examples/sub-agents/reviewer.md +10 -31
  77. package/examples/sub-agents/verifier.md +12 -27
  78. package/examples/sub-agents/worker.md +11 -35
  79. package/package.json +7 -3
@@ -26,6 +26,8 @@ function isImageFile(filePath) {
26
26
  /** Directory tree caps, mirroring oh-my-pi's read: shallow and per-directory bounded. */
27
27
  const DIR_MAX_DEPTH = 2;
28
28
  const DIR_PER_DIR_LIMIT = 12;
29
+ /** Source cap on entries `listDirectory` collects before we ever start rendering (fix plan §2.4). */
30
+ const DIR_MAX_ENTRIES = 4_000;
29
31
  /**
30
32
  * Render a depth-2 directory tree from `FileStore.listDirectory` entries. Kept deliberately
31
33
  * portable — no sizes or mtimes, since formats differ across platforms; the structure is the value.
@@ -39,23 +41,41 @@ function renderDirectoryTree(entries) {
39
41
  const perParentCount = new Map();
40
42
  const lines = [];
41
43
  const elided = new Map();
44
+ // Parents whose own line was omitted (over the per-dir cap). Their descendants must be skipped
45
+ // too — otherwise the tree shows children of a directory it never listed.
46
+ const elidedParents = new Set();
42
47
  for (const entry of sorted) {
43
48
  const segments = entry.relativePath.split("/");
44
49
  const depth = segments.length - 1;
45
50
  const parent = depth === 0 ? "" : segments.slice(0, -1).join("/");
51
+ if (isUnderElidedParent(parent, elidedParents)) {
52
+ continue;
53
+ }
46
54
  const count = (perParentCount.get(parent) ?? 0) + 1;
47
55
  perParentCount.set(parent, count);
48
56
  if (count > DIR_PER_DIR_LIMIT) {
49
57
  elided.set(parent, (elided.get(parent) ?? 0) + 1);
58
+ if (entry.isDirectory) {
59
+ elidedParents.add(entry.relativePath);
60
+ }
50
61
  continue;
51
62
  }
52
63
  lines.push(`${" ".repeat(depth)}${entry.name}${entry.isDirectory ? "/" : ""}`);
53
64
  }
54
- for (const [, count] of elided) {
55
- lines.push(` [+${count} more]`);
65
+ for (const [parent, count] of elided) {
66
+ const indent = parent === "" ? "" : " ".repeat(parent.split("/").length);
67
+ lines.push(`${indent} [+${count} more]`);
56
68
  }
57
69
  return lines.join("\n");
58
70
  }
71
+ function isUnderElidedParent(parent, elidedParents) {
72
+ for (const elided of elidedParents) {
73
+ if (parent === elided || parent.startsWith(`${elided}/`)) {
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ }
59
79
  const readSchema = Type.Object({
60
80
  path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
61
81
  offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
@@ -77,7 +97,7 @@ export function createReadTool(executor, fileStore, options = {}) {
77
97
  return {
78
98
  name: "read",
79
99
  label: "read",
80
- description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files.`,
100
+ description: `Read a file, a PDF (converted to text), or a directory (rendered as a shallow tree). Also reads images (jpg, png, gif, webp), returned as attachments. Text/PDF output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); use offset/limit to page a large file. A directory tree is depth-2, capped per directory, and points you to subdirectories for the rest.`,
81
101
  parameters: readSchema,
82
102
  execute: async (_toolCallId, { path, offset, limit }, signal) => {
83
103
  const target = await checkPathGuard(path, "read", securityConfig, securityContext, {
@@ -121,15 +141,32 @@ export function createReadTool(executor, fileStore, options = {}) {
121
141
  `The file may be scanned/image-based — ask the user for a text version or a screenshot.`);
122
142
  }
123
143
  pdfText = converted.stdout;
144
+ if (converted.stdoutTruncated) {
145
+ // The 10MB capture cap hit mid-conversion — the rest of the PDF's text is gone.
146
+ // Say so rather than presenting a partial extraction as the whole document.
147
+ pdfText += `\n\n[pdftotext output exceeded the command capture limit and was cut off here; this is not the complete document. Ask the user for a text version to read the rest.]`;
148
+ }
124
149
  }
125
150
  const stat = isPdf ? undefined : await fileStore.stat(target);
126
151
  if (!isPdf && !stat) {
127
152
  throw new RecoverableToolError(`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
128
153
  }
129
154
  if (stat?.isDirectory) {
130
- const entries = await fileStore.listDirectory(target, { maxDepth: DIR_MAX_DEPTH });
155
+ const entries = await fileStore.listDirectory(target, {
156
+ maxDepth: DIR_MAX_DEPTH,
157
+ maxEntries: DIR_MAX_ENTRIES,
158
+ });
159
+ const tree = renderDirectoryTree(entries);
160
+ const clamped = truncateHead(tree);
161
+ let text = `Directory: ${path}\n\n${clamped.content}`;
162
+ if (entries.length >= DIR_MAX_ENTRIES) {
163
+ text += `\n\n[Listing stopped at ${DIR_MAX_ENTRIES} entries; this directory is large. read a specific subdirectory to see the rest.]`;
164
+ }
165
+ else if (clamped.truncated) {
166
+ text += `\n\n[Tree truncated at ${DEFAULT_MAX_BYTES / 1024}KB; read a specific subdirectory to see the rest.]`;
167
+ }
131
168
  return {
132
- content: [{ type: "text", text: `Directory: ${path}\n\n${renderDirectoryTree(entries)}` }],
169
+ content: [{ type: "text", text }],
133
170
  details: undefined,
134
171
  };
135
172
  }
@@ -34,6 +34,12 @@ export interface ToolBuildContext {
34
34
  bashDefaultTimeoutSeconds?: number;
35
35
  /** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
36
36
  rtkEnabled?: boolean;
37
+ /**
38
+ * Set by `buildToolSet` from `BuildToolSetOptions.forSubagent`. A sub-agent's `securityContext`
39
+ * has no `channelDir` and may be project-bounded, so tools that would otherwise write into the
40
+ * channel directory (bash/job output spill) must fall back to a neutral location for it.
41
+ */
42
+ forSubagent?: boolean;
37
43
  /**
38
44
  * Present only on the main path. Enables bash `async` and the `job` tool.
39
45
  * The sub-agent set never supplies it, so sub-agents get neither.
@@ -56,6 +56,9 @@ export const TOOL_REGISTRY = [
56
56
  ...fileToolOptions(ctx),
57
57
  rtkEnabled: ctx.rtkEnabled === true,
58
58
  interceptorEnabled: ctx.toolsConfig?.tools.bashInterceptor.enabled === true,
59
+ // Sub-agents get no channel dir (their guard context has none); their spill stays in tmpdir.
60
+ ...(ctx.forSubagent ? {} : { channelDir: ctx.channelDir }),
61
+ ...(ctx.taskLoop ? { boundTaskId: ctx.taskLoop.taskId } : {}),
59
62
  ...(ctx.jobManager ? { jobManager: ctx.jobManager } : {}),
60
63
  ...(ctx.bashDefaultTimeoutSeconds !== undefined
61
64
  ? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
@@ -275,7 +278,7 @@ export function buildToolSet(ctx, options = {}) {
275
278
  if (registration.enabledBy && !registration.enabledBy(ctx)) {
276
279
  continue;
277
280
  }
278
- result.push(withToolDetails(registration.create(ctx), registration.name));
281
+ result.push(withToolDetails(registration.create({ ...ctx, forSubagent: options.forSubagent }), registration.name));
279
282
  }
280
283
  return result;
281
284
  }
@@ -7,7 +7,7 @@ import { formatSize, MAX_INLINE_BINARY_BYTES } from "./truncate.js";
7
7
  /** Extensions delivered as inline images; everything else goes as a file attachment. */
8
8
  const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
9
9
  const sendMediaSchema = Type.Object({
10
- path: Type.String({ description: "Path to the local file to send (relative to the workspace, or absolute)" }),
10
+ path: Type.String({ description: "Local file path (relative to the current project root, or absolute)" }),
11
11
  fileName: Type.Optional(Type.String({ description: "Display name for the recipient; defaults to the file's own name" })),
12
12
  });
13
13
  /**
@@ -36,18 +36,20 @@ export function createSendMediaTool(fileStore, options) {
36
36
  });
37
37
  const stat = await fileStore.stat(target);
38
38
  if (!stat || !stat.isFile) {
39
- throw new RecoverableToolError(`Cannot send ${path}: not a regular file (does it exist?).`);
39
+ throw new RecoverableToolError(`Cannot send ${path}: not a regular file. Locate the generated file and retry with its path.`);
40
40
  }
41
41
  if (stat.size > MAX_INLINE_BINARY_BYTES) {
42
42
  throw new RecoverableToolError(`Cannot send ${path}: it is ${formatSize(stat.size)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} send limit. ` +
43
43
  "Compress it first, or provide the path so the user can be told where to find it.");
44
44
  }
45
45
  if (stat.size === 0) {
46
- throw new RecoverableToolError(`Cannot send ${path}: the file is empty.`);
46
+ throw new RecoverableToolError(`Cannot send ${path}: the file is empty. Generate the content before sending it.`);
47
47
  }
48
48
  const { data } = await fileStore.readBytes(target, { signal });
49
49
  const name = fileName?.trim() || basename(path);
50
- const kind = IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) ? "image" : "file";
50
+ // Route by the *real file's* extension, not the display name: `fileName` is only a label,
51
+ // so a PNG sent with fileName "报告" must still be delivered as an image (fix plan §4).
52
+ const kind = IMAGE_EXTENSIONS.has(extname(path).toLowerCase()) ? "image" : "file";
51
53
  const result = await options.mediaSender.sendMedia(options.channelId, { data, fileName: name, kind });
52
54
  if (!result.ok) {
53
55
  throw new Error(result.error ?? "Failed to send the file to the channel.");
@@ -42,8 +42,11 @@ export function createSessionSearchTool(options) {
42
42
  model,
43
43
  resolveApiKey: options.resolveApiKey,
44
44
  });
45
+ const partialNote = response.partialDocuments > 0
46
+ ? ` ${response.partialDocuments} scanned message(s) were themselves clipped at the scan cap, so a keyword past that point would not be found — this is not proof it was never said.`
47
+ : "";
45
48
  const text = response.results.length === 0
46
- ? `${JSON.stringify(response)}\n\nNo matches in cold transcript storage. Try a broader query, drop roleFilter, or read the distilled memory directly (MEMORY.md / HISTORY.md in this channel).`
49
+ ? `${JSON.stringify(response)}\n\nNo matches in cold transcript storage. Try a broader query, drop roleFilter, or read the distilled memory directly (MEMORY.md / HISTORY.md in this channel).${partialNote}`
47
50
  : JSON.stringify(response);
48
51
  return {
49
52
  content: [
@@ -26,6 +26,8 @@ export interface SkillToolOptions {
26
26
  }
27
27
  export declare function listWorkspaceSkills(options: {
28
28
  workspaceDir: string;
29
+ securityConfig?: SecurityConfig;
30
+ securityContext?: SecurityRuntimeContext;
29
31
  }): Promise<WorkspaceSkillSummary[]>;
30
32
  export interface WorkspaceSkillFile {
31
33
  name: string;
@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
6
6
  import { checkPathGuard } from "../security/path-guard-check.js";
7
+ import { readGuardAllows } from "../security/path-guard-filter.js";
7
8
  import { isNodeError } from "../shared/fs-utils.js";
8
9
  import { RecoverableToolError } from "../shared/recoverable-error.js";
9
10
  import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./skill-security.js";
@@ -36,6 +37,14 @@ function extractDescription(content) {
36
37
  }
37
38
  export async function listWorkspaceSkills(options) {
38
39
  const skillsDir = join(options.workspaceDir, "skills");
40
+ // `skill read` runs each SKILL.md through the path guard (`loadWorkspaceSkillFile`); `list`
41
+ // must apply the same guard so a skill whose SKILL.md is a symlink out of `workspace/skills/`
42
+ // is silently omitted here too, rather than being advertised and then refused on read.
43
+ const guardConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
44
+ const guardContext = options.securityContext ?? {
45
+ agentWorkspaceDir: options.workspaceDir,
46
+ projectRoot: options.workspaceDir,
47
+ };
39
48
  let names;
40
49
  try {
41
50
  names = await readdir(skillsDir);
@@ -58,6 +67,9 @@ export async function listWorkspaceSkills(options) {
58
67
  continue;
59
68
  }
60
69
  const skillPath = join(skillDir, "SKILL.md");
70
+ if (!readGuardAllows(skillPath, guardConfig, guardContext)) {
71
+ continue;
72
+ }
61
73
  let content;
62
74
  try {
63
75
  const skillFileStats = await stat(skillPath);
@@ -95,7 +95,7 @@ export function createSubAgentListTool(options) {
95
95
  return {
96
96
  name: "subagent_list",
97
97
  label: "subagent_list",
98
- description: "Snapshot of this channel's delegation runs. A finished run wakes this channel itself — never poll here, end the turn.",
98
+ description: "Snapshot of this channel's delegation runs. Completion wakes this channel; inspect when a decision needs current status, not in a polling loop.",
99
99
  parameters: subagentListSchema,
100
100
  execute: async () => {
101
101
  // Spec 042 D9: this used to return every run on the channel, unbounded, in both the
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The single source of truth for which tools a sub-agent role may request.
3
+ *
4
+ * This is a leaf module with no imports so both ends can read it without pulling in a cycle:
5
+ * `registry.ts` stamps `availableToSubagents` from it when building the sub-agent tool set, and
6
+ * `subagents/discovery.ts` validates a role file's `tools:` list against it. They used to be two
7
+ * hand-maintained lists and had already drifted (`glob` was build-available but validation-rejected).
8
+ * A test asserts the two ends still agree.
9
+ */
10
+ export declare const SUBAGENT_TOOL_NAMES: readonly ["read", "grep", "glob", "bash", "edit", "write", "web_search", "web_fetch"];
11
+ export type SubAgentToolName = (typeof SUBAGENT_TOOL_NAMES)[number];
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The single source of truth for which tools a sub-agent role may request.
3
+ *
4
+ * This is a leaf module with no imports so both ends can read it without pulling in a cycle:
5
+ * `registry.ts` stamps `availableToSubagents` from it when building the sub-agent tool set, and
6
+ * `subagents/discovery.ts` validates a role file's `tools:` list against it. They used to be two
7
+ * hand-maintained lists and had already drifted (`glob` was build-available but validation-rejected).
8
+ * A test asserts the two ends still agree.
9
+ */
10
+ export const SUBAGENT_TOOL_NAMES = [
11
+ "read",
12
+ "grep",
13
+ "glob",
14
+ "bash",
15
+ "edit",
16
+ "write",
17
+ "web_search",
18
+ "web_fetch",
19
+ ];
@@ -1,5 +1,5 @@
1
1
  import { normalizeTaskId } from "../../tasks/ledger.js";
2
- import { readTaskLog, renderTaskLogLine } from "../../tasks/log.js";
2
+ import { readTaskLog, renderTaskLogLine, taskLogIsArchived } from "../../tasks/log.js";
3
3
  const DEFAULT_LIMIT = 20;
4
4
  const MAX_LIMIT = 100;
5
5
  /**
@@ -11,14 +11,17 @@ const MAX_LIMIT = 100;
11
11
  export async function readTaskLogTool(options, request) {
12
12
  const id = normalizeTaskId(request.id);
13
13
  const limit = Math.min(Math.max(1, Math.trunc(request.limit ?? DEFAULT_LIMIT)), MAX_LIMIT);
14
+ const archived = taskLogIsArchived(options.channelDir, id);
14
15
  const records = await readTaskLog(options.channelDir, id, { cycle: request.cycle, limit });
15
16
  const entries = records.map(renderTaskLogLine);
17
+ const scope = request.cycle ? `(周期 ${request.cycle})` : "";
18
+ const archivedTag = archived ? "(已归档任务)" : "";
16
19
  return {
17
20
  action: "log",
18
21
  id,
19
22
  entries,
20
23
  notice: entries.length === 0
21
- ? `任务 \`${id}\` 暂无循环日志${request.cycle ? `(周期 ${request.cycle})` : ""}。`
22
- : `任务 \`${id}\` 最近 ${entries.length} 条记录${request.cycle ? `(周期 ${request.cycle})` : ""}。`,
24
+ ? `任务 \`${id}\` 暂无循环日志${scope}${archivedTag}。`
25
+ : `任务 \`${id}\` 最近 ${entries.length} 条记录${scope}${archivedTag}。`,
23
26
  };
24
27
  }
@@ -11,10 +11,10 @@ export declare const taskCreateSchema: Type.TObject<{
11
11
  verificationRequired: Type.TOptional<Type.TBoolean>;
12
12
  schedule: Type.TOptional<Type.TString>;
13
13
  budget: Type.TOptional<Type.TObject<{
14
- steps: Type.TOptional<Type.TNumber>;
14
+ steps: Type.TOptional<Type.TInteger>;
15
15
  wallMin: Type.TOptional<Type.TNumber>;
16
16
  usd: Type.TOptional<Type.TNumber>;
17
- rounds: Type.TOptional<Type.TNumber>;
17
+ rounds: Type.TOptional<Type.TInteger>;
18
18
  until: Type.TOptional<Type.TString>;
19
19
  }>>;
20
20
  }>;
@@ -27,10 +27,10 @@ export declare const taskUpdateSchema: Type.TObject<{
27
27
  }>>>;
28
28
  schedule: Type.TOptional<Type.TString>;
29
29
  budget: Type.TOptional<Type.TObject<{
30
- steps: Type.TOptional<Type.TNumber>;
30
+ steps: Type.TOptional<Type.TInteger>;
31
31
  wallMin: Type.TOptional<Type.TNumber>;
32
32
  usd: Type.TOptional<Type.TNumber>;
33
- rounds: Type.TOptional<Type.TNumber>;
33
+ rounds: Type.TOptional<Type.TInteger>;
34
34
  until: Type.TOptional<Type.TString>;
35
35
  }>>;
36
36
  verificationRequired: Type.TOptional<Type.TBoolean>;
@@ -46,7 +46,7 @@ export declare const taskCloseSchema: Type.TObject<{
46
46
  export declare const taskLogSchema: Type.TObject<{
47
47
  id: Type.TString;
48
48
  cycle: Type.TOptional<Type.TString>;
49
- limit: Type.TOptional<Type.TNumber>;
49
+ limit: Type.TOptional<Type.TInteger>;
50
50
  }>;
51
51
  export declare const taskStepEndSchema: Type.TObject<{
52
52
  outcome: Type.TUnion<[Type.TLiteral<"continue">, Type.TLiteral<"park">, Type.TLiteral<"done">, Type.TLiteral<"blocked">]>;
@@ -57,7 +57,7 @@ export declare const taskStepEndSchema: Type.TObject<{
57
57
  text: Type.TOptional<Type.TString>;
58
58
  }>>>;
59
59
  ticket: Type.TOptional<Type.TObject<{
60
- kind: Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"schedule">, Type.TLiteral<"run">, Type.TLiteral<"job">, Type.TLiteral<"ask">, Type.TLiteral<"signal">]>;
60
+ kind: Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"run">, Type.TLiteral<"job">, Type.TLiteral<"ask">, Type.TLiteral<"signal">]>;
61
61
  at: Type.TOptional<Type.TString>;
62
62
  id: Type.TOptional<Type.TString>;
63
63
  asked: Type.TOptional<Type.TString>;
@@ -11,10 +11,10 @@ const scheduleField = Type.Optional(Type.String({
11
11
  description: "Five-field cron cadence; makes this recurring. Empty string clears it. Min every 30 minutes.",
12
12
  }));
13
13
  const budgetField = Type.Optional(Type.Object({
14
- steps: Type.Optional(Type.Number({ description: "Max model steps in one cycle." })),
15
- wallMin: Type.Optional(Type.Number({ description: "Max working minutes in one cycle." })),
14
+ steps: Type.Optional(Type.Integer({ minimum: 1, description: "Max model steps in one cycle." })),
15
+ wallMin: Type.Optional(Type.Number({ description: "Max elapsed minutes in one cycle, including parked waits." })),
16
16
  usd: Type.Optional(Type.Number({ description: "Max attributable cost in one cycle." })),
17
- rounds: Type.Optional(Type.Number({ description: "Max delegate→verify rework rounds in one cycle." })),
17
+ rounds: Type.Optional(Type.Integer({ minimum: 1, description: "Max delegate→verify rework rounds in one cycle." })),
18
18
  until: Type.Optional(Type.String({ description: "Hard local-time stop, e.g. 2026-09-06T18:00:00+08:00." })),
19
19
  }, { description: "Per-task budget; omitted keys fall back to the runtime defaults." }));
20
20
  /**
@@ -23,14 +23,7 @@ const budgetField = Type.Optional(Type.Object({
23
23
  * the model can choose is a backstop it can choose not to have.
24
24
  */
25
25
  const ticketField = Type.Object({
26
- kind: Type.Union([
27
- Type.Literal("time"),
28
- Type.Literal("schedule"),
29
- Type.Literal("run"),
30
- Type.Literal("job"),
31
- Type.Literal("ask"),
32
- Type.Literal("signal"),
33
- ], { description: "What will wake this task." }),
26
+ kind: Type.Union([Type.Literal("time"), Type.Literal("run"), Type.Literal("job"), Type.Literal("ask"), Type.Literal("signal")], { description: "What will wake this task." }),
34
27
  at: Type.Optional(Type.String({ description: 'kind=time: when, e.g. "+2h" or a local timestamp.' })),
35
28
  id: Type.Optional(Type.String({ description: "kind=run/job: the run or job id this task is waiting on." })),
36
29
  asked: Type.Optional(Type.String({ description: "kind=ask: the question the user must answer." })),
@@ -75,7 +68,7 @@ export const taskCloseSchema = Type.Object({
75
68
  export const taskLogSchema = Type.Object({
76
69
  id: idField,
77
70
  cycle: Type.Optional(Type.String({ description: "Only this cycle's records, e.g. c-2026-09-05." })),
78
- limit: Type.Optional(Type.Number({ description: "Most recent N records; default 20." })),
71
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Most recent N records; default 20." })),
79
72
  });
80
73
  export const taskStepEndSchema = Type.Object({
81
74
  outcome: Type.Union([Type.Literal("continue"), Type.Literal("park"), Type.Literal("done"), Type.Literal("blocked")], {
@@ -5,6 +5,7 @@ import { getChannelJobManager } from "../../agent/job-manager.js";
5
5
  import { createExecutor } from "../../executor.js";
6
6
  import * as log from "../../log.js";
7
7
  import { parseScheduledEventContent } from "../../runtime/events.js";
8
+ import { parseLocalTime } from "../../shared/local-time.js";
8
9
  import { errorMessage } from "../../shared/text-utils.js";
9
10
  import { getSubAgentRunManager } from "../../subagents/runs.js";
10
11
  import { createCycle, nextCycleId } from "../../tasks/cycle.js";
@@ -58,8 +59,21 @@ export function normalizeBudget(budget) {
58
59
  }
59
60
  next[key] = value;
60
61
  }
61
- if (budget.until !== undefined)
62
- next.until = budget.until.trim() || undefined;
62
+ if (budget.until !== undefined) {
63
+ const trimmed = budget.until.trim();
64
+ if (trimmed) {
65
+ // `budget.ts` runs `until` through `parseLocalTime` and silently drops the deadline on a
66
+ // parse failure, so validate it here with the same parser — a mistyped stop-time should
67
+ // be a recoverable error, not a task with no hard stop.
68
+ if (parseLocalTime(trimmed) === undefined) {
69
+ throw new RecoverableToolError(`budget.until "${budget.until}" is not a parseable local time. Use e.g. 2026-09-06T18:00:00+08:00.`);
70
+ }
71
+ next.until = trimmed;
72
+ }
73
+ else {
74
+ next.until = undefined;
75
+ }
76
+ }
63
77
  return Object.keys(next).length > 0 ? next : undefined;
64
78
  }
65
79
  export function normalizeSchedule(schedule) {
@@ -25,6 +25,10 @@ export async function endTaskStep(options, request) {
25
25
  throw new RecoverableToolError(`Task "${id}" no longer exists; nothing to end.`);
26
26
  const cycleId = document.fields.cycle?.id ?? options.cycleId ?? "-";
27
27
  const note = requiredField(request.note, "note", "task_step_end");
28
+ // Also reject stale callers that bypass the schema, which no longer exposes schedule tickets.
29
+ if (request.outcome === "park" && request.ticket?.kind === "schedule") {
30
+ throw new RecoverableToolError("To finish this cycle, use outcome=done with summary and evidence; the runtime schedules the next occurrence. To skip it, use task_close outcome=skip with a reason. Use a time ticket to wait within this cycle.");
31
+ }
28
32
  if (request.planSteps?.length) {
29
33
  document.body = applyTaskPlanPatch(document.body, request.planSteps).body;
30
34
  }
@@ -38,11 +42,21 @@ export async function endTaskStep(options, request) {
38
42
  // Steps are silent by default (D3); `notify` is the explicit opt-in the runtime delivers once
39
43
  // the step ends. `blocked` always speaks — a task waiting on the user that says nothing is the
40
44
  // same silent dead end tickets exist to prevent.
41
- if (request.notify?.trim())
42
- await queueTaskNotice(options.channelDir, id, request.notify);
43
- else if (request.outcome === "blocked") {
44
- await queueTaskNotice(options.channelDir, id, `任务 ${id} 需要你的决定:${request.reason ?? note}`);
45
- }
45
+ //
46
+ // The notice is an *outbound side effect*: it must not land before every recoverable check
47
+ // (required fields, unmet acceptance items, verification hold, ticket resolution) has passed,
48
+ // or a rejected `outcome=done` still tells the channel "task complete" and a corrected retry
49
+ // queues a second notice. So compute it here and only flush it past a successful
50
+ // `writeStoredTask` + `logStep`, right before each return.
51
+ const pendingNotice = request.notify?.trim()
52
+ ? request.notify.trim()
53
+ : request.outcome === "blocked"
54
+ ? `任务 ${id} 需要你的决定:${request.reason ?? note}`
55
+ : undefined;
56
+ const flushNotice = async () => {
57
+ if (pendingNotice)
58
+ await queueTaskNotice(options.channelDir, id, pendingNotice);
59
+ };
46
60
  if (request.outcome === "done") {
47
61
  const summary = requiredField(request.summary, "summary", "task_step_end outcome=done");
48
62
  const evidence = requiredField(request.evidence, "evidence", "task_step_end outcome=done");
@@ -88,6 +102,7 @@ export async function endTaskStep(options, request) {
88
102
  document.fields.ticket = ticket;
89
103
  await writeStoredTask(document);
90
104
  await logStep("done");
105
+ await flushNotice();
91
106
  return {
92
107
  action: "step_end",
93
108
  id,
@@ -97,6 +112,7 @@ export async function endTaskStep(options, request) {
97
112
  }
98
113
  await writeStoredTask(document);
99
114
  await logStep("done");
115
+ await flushNotice();
100
116
  const { deleted } = await cleanupTaskEvents(options, id);
101
117
  await archiveTask(options.channelDir, id, "completed");
102
118
  return {
@@ -130,5 +146,6 @@ export async function endTaskStep(options, request) {
130
146
  }
131
147
  await writeStoredTask(document);
132
148
  await logStep(request.outcome);
149
+ await flushNotice();
133
150
  return { action: "step_end", id, state: document.fields.state, notice };
134
151
  }
@@ -85,7 +85,15 @@ export function createTaskStepEndTool(options) {
85
85
  parameters: taskStepEndSchema,
86
86
  execute: async (_toolCallId, args) => {
87
87
  const result = await withLock(options, options.taskId ?? "", () => endTaskStep(options, args));
88
- return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
88
+ // A successful step_end is the last move of the step — signal the SDK to end the batch
89
+ // without another model round-trip. Recoverable failures throw before reaching here, so
90
+ // the model stays in the loop to fix them. The SDK ends early only if *every* finalized
91
+ // result in the batch sets this, so a mixed batch is still safe.
92
+ return {
93
+ content: [{ type: "text", text: JSON.stringify(result) }],
94
+ details: { ...result },
95
+ terminate: true,
96
+ };
89
97
  },
90
98
  };
91
99
  }
@@ -2,10 +2,18 @@ export declare const WEB_CACHE_TTL_MS: number;
2
2
  export interface WebCacheEntry {
3
3
  body: string;
4
4
  fetchedAt: number;
5
+ finalUrl: string;
6
+ status: number;
7
+ extractor: string;
8
+ contentType: string;
9
+ /** True when the origin returned more than the fetch cap and the body is not the whole page. */
10
+ sourceTruncated: boolean;
5
11
  }
6
12
  /** Cache key from the requested URL plus extract mode (markdown vs text render differently). */
7
13
  export declare function webCacheKey(url: string, extractMode: string): string;
8
- /** Return the cached body if present and within the TTL, else null. */
14
+ /** Return the cached entry if present and within the TTL, else null. */
9
15
  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>;
16
+ /** Persist an entry and evict the oldest beyond the cap. Best-effort; never throws. */
17
+ export declare function writeWebCache(channelDir: string, key: string, entry: WebCacheEntry): Promise<void>;
18
+ /** Remove one cached entry (used by `refresh: true` before a forced refetch). */
19
+ export declare function clearWebCacheEntry(channelDir: string, key: string): Promise<void>;
@@ -6,7 +6,9 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
6
6
  /**
7
7
  * Small per-channel cache of fetched web page bodies so a long page can be paged over with `offset`
8
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.
9
+ * — the banner and windowing are re-applied by the tool on each read. The entry also carries the
10
+ * fetch-time facts the model needs to judge the content (final URL after redirects, HTTP status,
11
+ * whether the *source* was itself truncated) — the old cache dropped all of that (fix plan §2.7).
10
12
  */
11
13
  const WEB_CACHE_DIR = "web-cache";
12
14
  export const WEB_CACHE_TTL_MS = 15 * 60 * 1000;
@@ -19,9 +21,9 @@ export function webCacheKey(url, extractMode) {
19
21
  return createHash("sha256").update(`${extractMode}\n${url}`).digest("hex").slice(0, 24);
20
22
  }
21
23
  function bodyPath(channelDir, key) {
22
- return join(cacheDir(channelDir), `${key}.txt`);
24
+ return join(cacheDir(channelDir), `${key}.json`);
23
25
  }
24
- /** Return the cached body if present and within the TTL, else null. */
26
+ /** Return the cached entry if present and within the TTL, else null. */
25
27
  export async function readWebCache(channelDir, key, ttlMs = WEB_CACHE_TTL_MS) {
26
28
  const path = bodyPath(channelDir, key);
27
29
  try {
@@ -30,28 +32,44 @@ export async function readWebCache(channelDir, key, ttlMs = WEB_CACHE_TTL_MS) {
30
32
  if (Date.now() - stats.mtimeMs >= ttlMs) {
31
33
  return null;
32
34
  }
33
- return { body: await readFile(path, "utf-8"), fetchedAt: stats.mtimeMs };
35
+ const raw = JSON.parse(await readFile(path, "utf-8"));
36
+ if (typeof raw.body !== "string") {
37
+ return null;
38
+ }
39
+ return {
40
+ body: raw.body,
41
+ fetchedAt: raw.fetchedAt ?? stats.mtimeMs,
42
+ finalUrl: raw.finalUrl ?? "",
43
+ status: raw.status ?? 0,
44
+ extractor: raw.extractor ?? "",
45
+ contentType: raw.contentType ?? "",
46
+ sourceTruncated: raw.sourceTruncated === true,
47
+ };
34
48
  }
35
49
  catch {
36
50
  return null;
37
51
  }
38
52
  }
39
- /** Persist a body and evict the oldest entries beyond the cap. Best-effort; never throws. */
40
- export async function writeWebCache(channelDir, key, body) {
53
+ /** Persist an entry and evict the oldest beyond the cap. Best-effort; never throws. */
54
+ export async function writeWebCache(channelDir, key, entry) {
41
55
  try {
42
56
  const dir = cacheDir(channelDir);
43
57
  if (!existsSync(dir)) {
44
58
  await mkdir(dir, { recursive: true });
45
59
  }
46
- await writeFileAtomically(bodyPath(channelDir, key), body);
60
+ await writeFileAtomically(bodyPath(channelDir, key), JSON.stringify(entry));
47
61
  await pruneWebCache(dir);
48
62
  }
49
63
  catch {
50
64
  // Caching is an optimization; a failure just means the next read refetches.
51
65
  }
52
66
  }
67
+ /** Remove one cached entry (used by `refresh: true` before a forced refetch). */
68
+ export async function clearWebCacheEntry(channelDir, key) {
69
+ await rm(bodyPath(channelDir, key), { force: true }).catch(() => undefined);
70
+ }
53
71
  async function pruneWebCache(dir) {
54
- const files = (await readdir(dir)).filter((name) => name.endsWith(".txt"));
72
+ const files = (await readdir(dir)).filter((name) => name.endsWith(".json"));
55
73
  if (files.length <= WEB_CACHE_MAX_FILES) {
56
74
  return;
57
75
  }
@@ -7,6 +7,7 @@ declare const webFetchSchema: Type.TObject<{
7
7
  extractMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"markdown">, Type.TLiteral<"text">]>>;
8
8
  maxChars: Type.TOptional<Type.TNumber>;
9
9
  offset: Type.TOptional<Type.TInteger>;
10
+ refresh: Type.TOptional<Type.TBoolean>;
10
11
  }>;
11
12
  export interface WebFetchToolOptions {
12
13
  webConfig: PipiclawWebToolsConfig;