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

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 (148) hide show
  1. package/dist/agent/channel-runner.d.ts +4 -18
  2. package/dist/agent/channel-runner.js +25 -120
  3. package/dist/agent/context-budget.js +1 -1
  4. package/dist/agent/job-manager.d.ts +20 -17
  5. package/dist/agent/job-manager.js +95 -70
  6. package/dist/agent/prompt/builder.d.ts +1 -1
  7. package/dist/agent/prompt/builder.js +2 -18
  8. package/dist/agent/prompt/manifest.d.ts +0 -1
  9. package/dist/agent/prompt/manifest.js +2 -2
  10. package/dist/agent/prompt/sections.js +3 -12
  11. package/dist/agent/prompt/types.d.ts +2 -18
  12. package/dist/agent/prompt/types.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +4 -0
  14. package/dist/agent/session-adapter.d.ts +19 -0
  15. package/dist/agent/session-adapter.js +77 -0
  16. package/dist/app-services.d.ts +18 -0
  17. package/dist/app-services.js +43 -0
  18. package/dist/{runtime → events}/events.d.ts +1 -1
  19. package/dist/executor.d.ts +5 -1
  20. package/dist/executor.js +35 -5
  21. package/dist/file-store.d.ts +4 -1
  22. package/dist/file-store.js +5 -0
  23. package/dist/memory/journal.d.ts +13 -0
  24. package/dist/memory/journal.js +47 -4
  25. package/dist/memory/maintenance-gates.d.ts +0 -3
  26. package/dist/memory/maintenance-gates.js +2 -2
  27. package/dist/memory/maintenance-migration.d.ts +5 -0
  28. package/dist/memory/maintenance-migration.js +91 -0
  29. package/dist/memory/maintenance-state.js +5 -44
  30. package/dist/memory/migrate.js +1 -1
  31. package/dist/memory/reflect-job.d.ts +1 -9
  32. package/dist/memory/reflect-job.js +1 -3
  33. package/dist/memory/reflect.js +1 -1
  34. package/dist/memory/search.js +13 -6
  35. package/dist/memory/session-corpus.d.ts +11 -0
  36. package/dist/memory/session-corpus.js +16 -5
  37. package/dist/memory/session-search.d.ts +3 -0
  38. package/dist/memory/session-search.js +45 -8
  39. package/dist/memory/store.d.ts +9 -0
  40. package/dist/memory/store.js +26 -3
  41. package/dist/models/auth-cli.js +1 -1
  42. package/dist/playbooks/agent-delegation.md +35 -76
  43. package/dist/playbooks/background-jobs.md +14 -16
  44. package/dist/playbooks/event-scheduling.md +20 -25
  45. package/dist/playbooks/memory-and-learning.md +28 -61
  46. package/dist/playbooks/outbound-media.md +10 -12
  47. package/dist/playbooks/runtime-orientation.md +34 -53
  48. package/dist/playbooks/task-loop.md +49 -69
  49. package/dist/runtime/bootstrap.d.ts +5 -15
  50. package/dist/runtime/bootstrap.js +57 -67
  51. package/dist/runtime/subagent-commands.d.ts +2 -1
  52. package/dist/runtime/subagent-commands.js +10 -12
  53. package/dist/runtime/task-wake.d.ts +4 -5
  54. package/dist/runtime/task-wake.js +2 -12
  55. package/dist/security/path-guard-filter.d.ts +22 -0
  56. package/dist/security/path-guard-filter.js +35 -0
  57. package/dist/security/types.d.ts +7 -0
  58. package/dist/security/types.js +16 -1
  59. package/dist/settings.d.ts +8 -0
  60. package/dist/settings.js +24 -1
  61. package/dist/shared/exact-keys.d.ts +13 -0
  62. package/dist/shared/exact-keys.js +1 -0
  63. package/dist/shared/format.d.ts +20 -0
  64. package/dist/shared/format.js +64 -0
  65. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  66. package/dist/shared/{fs-utils.js → os.js} +8 -0
  67. package/dist/subagents/discovery.d.ts +18 -6
  68. package/dist/subagents/discovery.js +12 -8
  69. package/dist/subagents/external/run.d.ts +2 -1
  70. package/dist/subagents/external/run.js +1 -2
  71. package/dist/subagents/external/settlement.js +10 -5
  72. package/dist/subagents/format.d.ts +1 -1
  73. package/dist/subagents/format.js +1 -1
  74. package/dist/subagents/runs.d.ts +13 -12
  75. package/dist/subagents/runs.js +108 -89
  76. package/dist/subagents/tool.d.ts +13 -7
  77. package/dist/subagents/tool.js +21 -13
  78. package/dist/tasks/brief.d.ts +1 -1
  79. package/dist/tasks/brief.js +12 -2
  80. package/dist/tasks/log.d.ts +4 -0
  81. package/dist/tasks/log.js +13 -1
  82. package/dist/tools/bash.d.ts +13 -0
  83. package/dist/tools/bash.js +123 -20
  84. package/dist/tools/command-optimizer.js +1 -1
  85. package/dist/tools/config.d.ts +7 -0
  86. package/dist/tools/config.js +16 -1
  87. package/dist/tools/edit.js +36 -5
  88. package/dist/tools/event-manage.d.ts +26 -5
  89. package/dist/tools/event-manage.js +84 -36
  90. package/dist/tools/glob.js +57 -4
  91. package/dist/tools/grep.d.ts +2 -0
  92. package/dist/tools/grep.js +188 -15
  93. package/dist/tools/index.d.ts +4 -0
  94. package/dist/tools/index.js +4 -2
  95. package/dist/tools/job.js +17 -5
  96. package/dist/tools/memory-manage.js +80 -41
  97. package/dist/tools/read.js +43 -6
  98. package/dist/tools/registry.d.ts +9 -3
  99. package/dist/tools/registry.js +22 -57
  100. package/dist/tools/send-media.js +6 -4
  101. package/dist/tools/session-search.js +4 -1
  102. package/dist/tools/skill.d.ts +2 -0
  103. package/dist/tools/skill.js +13 -1
  104. package/dist/tools/subagent-manage.d.ts +2 -0
  105. package/dist/tools/subagent-manage.js +8 -8
  106. package/dist/tools/subagent-tool-names.d.ts +11 -0
  107. package/dist/tools/subagent-tool-names.js +19 -0
  108. package/dist/tools/task-manage/log-view.js +6 -3
  109. package/dist/tools/task-manage/schema.d.ts +6 -6
  110. package/dist/tools/task-manage/schema.js +5 -12
  111. package/dist/tools/task-manage/shared.js +20 -11
  112. package/dist/tools/task-manage/step-end.js +22 -5
  113. package/dist/tools/task-manage/types.d.ts +4 -0
  114. package/dist/tools/task-manage.js +9 -1
  115. package/dist/tools/web-cache.d.ts +11 -3
  116. package/dist/tools/web-cache.js +26 -8
  117. package/dist/tools/web-fetch.d.ts +1 -0
  118. package/dist/tools/web-fetch.js +68 -15
  119. package/dist/tools/write.js +3 -0
  120. package/dist/tui/app.js +22 -7
  121. package/dist/web/config.js +1 -1
  122. package/dist/web/fetch.d.ts +5 -0
  123. package/dist/web/fetch.js +36 -1
  124. package/examples/sub-agents/README.md +14 -4
  125. package/examples/sub-agents/builder-hard.md +12 -34
  126. package/examples/sub-agents/builder.md +11 -31
  127. package/examples/sub-agents/explorer.md +10 -16
  128. package/examples/sub-agents/git-committer.md +15 -20
  129. package/examples/sub-agents/planner.md +11 -21
  130. package/examples/sub-agents/reviewer.md +10 -31
  131. package/examples/sub-agents/verifier.md +12 -27
  132. package/examples/sub-agents/worker.md +11 -35
  133. package/package.json +8 -3
  134. package/dist/shared/duration.d.ts +0 -2
  135. package/dist/shared/duration.js +0 -7
  136. package/dist/shared/file-stamp.d.ts +0 -10
  137. package/dist/shared/file-stamp.js +0 -19
  138. package/dist/shared/numeric.d.ts +0 -7
  139. package/dist/shared/numeric.js +0 -19
  140. package/dist/shared/shell-escape.d.ts +0 -5
  141. package/dist/shared/shell-escape.js +0 -7
  142. package/dist/shared/token-estimate.d.ts +0 -1
  143. package/dist/shared/token-estimate.js +0 -19
  144. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  145. /package/dist/{runtime → events}/event-commands.js +0 -0
  146. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  147. /package/dist/{runtime → events}/event-validation.js +0 -0
  148. /package/dist/{runtime → events}/events.js +0 -0
@@ -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,7 +4,8 @@ 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 { isNodeError } from "../shared/fs-utils.js";
7
+ import { readGuardAllows } from "../security/path-guard-filter.js";
8
+ import { isNodeError } from "../shared/os.js";
8
9
  import { RecoverableToolError } from "../shared/recoverable-error.js";
9
10
  import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./skill-security.js";
10
11
  import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.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);
@@ -2,6 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { SecurityConfig } from "../security/types.js";
4
4
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
5
+ import type { SubAgentRunManager } from "../subagents/runs.js";
5
6
  declare const subagentListSchema: Type.TObject<{}>;
6
7
  declare const subagentRunSchema: Type.TObject<{
7
8
  op: Type.TUnion<[Type.TLiteral<"show">, Type.TLiteral<"cancel">, Type.TLiteral<"follow_up">]>;
@@ -9,6 +10,7 @@ declare const subagentRunSchema: Type.TObject<{
9
10
  task: Type.TOptional<Type.TString>;
10
11
  }>;
11
12
  export interface SubAgentManageToolOptions {
13
+ runManager: SubAgentRunManager;
12
14
  channelId: string;
13
15
  /**
14
16
  * Spec 042 D7: required, not defaulted. `follow_up` dispatches a new external process through
@@ -6,7 +6,6 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
6
6
  import { externalRoleFingerprint, validateSubAgentTask } from "../subagents/discovery.js";
7
7
  import { launchExternalRun } from "../subagents/external/run.js";
8
8
  import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
9
- import { getSubAgentRunManager } from "../subagents/runs.js";
10
9
  import { assertVerifyAdmissible, assertWithinProjectBoundary, buildContextualBlocks, buildSubAgentTask, } from "../subagents/tool.js";
11
10
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "../subagents/workspace-lease.js";
12
11
  // Spec 047, P3: `subagent_list` is zero-argument and shape-independent (like `task_list`); the
@@ -91,18 +90,18 @@ function resumableHarnessOf(record) {
91
90
  return record.harness === "codex-cli" || record.harness === "claude-code" ? record.harness : undefined;
92
91
  }
93
92
  export function createSubAgentListTool(options) {
94
- const manager = () => getSubAgentRunManager(options.channelId);
93
+ const manager = options.runManager;
95
94
  return {
96
95
  name: "subagent_list",
97
96
  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.",
97
+ 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
98
  parameters: subagentListSchema,
100
99
  execute: async () => {
101
100
  // Spec 042 D9: this used to return every run on the channel, unbounded, in both the
102
101
  // text and `details.runs` — a long-lived channel could dump thousands of historical
103
102
  // records into a single tool result. Running runs (the ones a decision might depend
104
103
  // on) are never dropped; only the terminal tail is capped, newest first.
105
- const allRuns = manager().list();
104
+ const allRuns = manager.list();
106
105
  const running = allRuns.filter((record) => record.status === "running");
107
106
  const terminal = allRuns
108
107
  .filter((record) => record.status !== "running")
@@ -121,7 +120,7 @@ export function createSubAgentListTool(options) {
121
120
  };
122
121
  }
123
122
  export function createSubAgentRunTool(options) {
124
- const manager = () => getSubAgentRunManager(options.channelId);
123
+ const manager = options.runManager;
125
124
  return {
126
125
  name: "subagent_run",
127
126
  label: "subagent_run",
@@ -129,7 +128,7 @@ export function createSubAgentRunTool(options) {
129
128
  "(no wake — your decision, not a failure). follow_up: continue a resumable run with a new instruction (new runId).",
130
129
  parameters: subagentRunSchema,
131
130
  execute: async (_toolCallId, { op, runId, task }) => {
132
- const resolution = manager().resolveRef(runId);
131
+ const resolution = manager.resolveRef(runId);
133
132
  if (resolution.kind === "ambiguous") {
134
133
  throw new RecoverableToolError(`"${runId}" matches multiple runs on this channel: ${resolution.candidates.map((candidate) => candidate.runId).join(", ")}. Use the full runId.`);
135
134
  }
@@ -145,7 +144,7 @@ export function createSubAgentRunTool(options) {
145
144
  };
146
145
  }
147
146
  if (op === "cancel") {
148
- const status = await manager().cancel(resolvedRunId);
147
+ const status = await manager.cancel(resolvedRunId);
149
148
  return {
150
149
  content: [{ type: "text", text: `Cancel requested for run ${resolvedRunId}: ${status}` }],
151
150
  details: { op, runId: resolvedRunId, status },
@@ -213,7 +212,7 @@ export function createSubAgentRunTool(options) {
213
212
  }
214
213
  // A short, human-typeable id (spec 041) — the follow-up gets a fresh identity, not the
215
214
  // dispatching tool call's own id.
216
- const newRunId = manager().mintRunId();
215
+ const newRunId = manager.mintRunId();
217
216
  let leaseKey;
218
217
  if (role.mutates === "write") {
219
218
  const lease = acquireWorkspaceLease({
@@ -250,6 +249,7 @@ export function createSubAgentRunTool(options) {
250
249
  });
251
250
  const envelopedTask = buildSubAgentTask(task, role, { workspaceDir: options.workspaceDir, channelId: options.channelId }, contextualBlocks, runContext);
252
251
  launchResult = await launchExternalRun({
252
+ runManager: manager,
253
253
  runId: newRunId,
254
254
  channelId: options.channelId,
255
255
  channelDir: options.channelDir,
@@ -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` filters the sub-agent tool set through it, 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 checks that every allowed name has a registered implementation.
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` filters the sub-agent tool set through it, 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 checks that every allowed name has a registered implementation.
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")], {
@@ -1,12 +1,10 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { getChannelJobManager } from "../../agent/job-manager.js";
5
- import { createExecutor } from "../../executor.js";
4
+ import { parseScheduledEventContent } from "../../events/events.js";
6
5
  import * as log from "../../log.js";
7
- import { parseScheduledEventContent } from "../../runtime/events.js";
6
+ import { parseLocalTime } from "../../shared/local-time.js";
8
7
  import { errorMessage } from "../../shared/text-utils.js";
9
- import { getSubAgentRunManager } from "../../subagents/runs.js";
10
8
  import { createCycle, nextCycleId } from "../../tasks/cycle.js";
11
9
  import { renderStandardTaskBody, renderTaskDocument } from "../../tasks/ledger.js";
12
10
  import { parseTaskEventName } from "../../tasks/task-events.js";
@@ -58,8 +56,21 @@ export function normalizeBudget(budget) {
58
56
  }
59
57
  next[key] = value;
60
58
  }
61
- if (budget.until !== undefined)
62
- next.until = budget.until.trim() || undefined;
59
+ if (budget.until !== undefined) {
60
+ const trimmed = budget.until.trim();
61
+ if (trimmed) {
62
+ // `budget.ts` runs `until` through `parseLocalTime` and silently drops the deadline on a
63
+ // parse failure, so validate it here with the same parser — a mistyped stop-time should
64
+ // be a recoverable error, not a task with no hard stop.
65
+ if (parseLocalTime(trimmed) === undefined) {
66
+ throw new RecoverableToolError(`budget.until "${budget.until}" is not a parseable local time. Use e.g. 2026-09-06T18:00:00+08:00.`);
67
+ }
68
+ next.until = trimmed;
69
+ }
70
+ else {
71
+ next.until = undefined;
72
+ }
73
+ }
63
74
  return Object.keys(next).length > 0 ? next : undefined;
64
75
  }
65
76
  export function normalizeSchedule(schedule) {
@@ -114,10 +125,8 @@ export function describeTaskState(fields) {
114
125
  * validation matrix unit-testable against plain fakes.
115
126
  */
116
127
  export async function buildTicketContext(options, taskId, schedule, now = new Date()) {
117
- const runManager = getSubAgentRunManager(options.channelId);
118
- const jobs = await getChannelJobManager(options.channelId, createExecutor())
119
- .list()
120
- .catch(() => []);
128
+ const runManager = options.runManager;
129
+ const jobs = await options.jobManager.list().catch(() => []);
121
130
  const events = await readChannelEvents(options);
122
131
  return {
123
132
  now,
@@ -202,7 +211,7 @@ export async function cleanupTaskEvents(options, id) {
202
211
  export async function assertVerificationHoldsForClose(options, document, id) {
203
212
  if (document.fields.verify !== "required")
204
213
  return;
205
- const runManager = getSubAgentRunManager(options.channelId);
214
+ const runManager = options.runManager;
206
215
  const reason = await completionVerificationBlockReason({
207
216
  channelDir: options.channelDir,
208
217
  taskId: id,
@@ -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
  }
@@ -1,4 +1,6 @@
1
1
  import type { Static } from "typebox";
2
+ import type { ChannelJobManager } from "../../agent/job-manager.js";
3
+ import type { SubAgentRunManager } from "../../subagents/runs.js";
2
4
  import type { taskCloseSchema, taskCreateSchema, taskLogSchema, taskStepEndSchema, taskUpdateSchema } from "./schema.js";
3
5
  export interface TaskManageResult {
4
6
  action: "create" | "update" | "close" | "list" | "log" | "step_end";
@@ -31,6 +33,8 @@ export type TaskCloseRequest = Static<typeof taskCloseSchema>;
31
33
  export type TaskLogRequest = Static<typeof taskLogSchema>;
32
34
  export type TaskStepEndRequest = Static<typeof taskStepEndSchema>;
33
35
  export interface TaskManageToolOptions {
36
+ jobManager: ChannelJobManager;
37
+ runManager: SubAgentRunManager;
34
38
  workspaceDir: string;
35
39
  channelDir: string;
36
40
  channelId: string;
@@ -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;