@oyasmi/pipiclaw 0.9.3-beta.1 → 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 (95) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +16 -0
  4. package/dist/agent/channel-runner.js +47 -6
  5. package/dist/agent/job-manager.d.ts +9 -0
  6. package/dist/agent/job-manager.js +20 -6
  7. package/dist/agent/prompt/builder.d.ts +1 -1
  8. package/dist/agent/prompt/builder.js +1 -1
  9. package/dist/agent/prompt/sections.js +3 -3
  10. package/dist/executor.d.ts +5 -1
  11. package/dist/executor.js +35 -5
  12. package/dist/file-store.d.ts +4 -1
  13. package/dist/file-store.js +5 -0
  14. package/dist/memory/journal.d.ts +13 -0
  15. package/dist/memory/journal.js +47 -4
  16. package/dist/memory/render.d.ts +5 -0
  17. package/dist/memory/render.js +9 -2
  18. package/dist/memory/search.js +13 -6
  19. package/dist/memory/session-corpus.d.ts +11 -0
  20. package/dist/memory/session-corpus.js +15 -4
  21. package/dist/memory/session-search.d.ts +3 -0
  22. package/dist/memory/session-search.js +45 -8
  23. package/dist/memory/store.d.ts +9 -0
  24. package/dist/memory/store.js +25 -2
  25. package/dist/memory/transcript.js +12 -5
  26. package/dist/playbooks/agent-delegation.md +35 -50
  27. package/dist/playbooks/background-jobs.md +14 -16
  28. package/dist/playbooks/event-scheduling.md +20 -25
  29. package/dist/playbooks/memory-and-learning.md +28 -44
  30. package/dist/playbooks/outbound-media.md +10 -12
  31. package/dist/playbooks/runtime-orientation.md +34 -53
  32. package/dist/playbooks/task-loop.md +50 -48
  33. package/dist/runtime/bootstrap.js +25 -11
  34. package/dist/security/path-guard-filter.d.ts +22 -0
  35. package/dist/security/path-guard-filter.js +35 -0
  36. package/dist/subagents/discovery.d.ts +2 -3
  37. package/dist/subagents/discovery.js +3 -1
  38. package/dist/subagents/tool.d.ts +6 -0
  39. package/dist/subagents/tool.js +10 -2
  40. package/dist/tasks/brief.d.ts +1 -1
  41. package/dist/tasks/brief.js +11 -2
  42. package/dist/tasks/log.d.ts +4 -0
  43. package/dist/tasks/log.js +13 -1
  44. package/dist/tasks/rounds.d.ts +0 -2
  45. package/dist/tasks/rounds.js +0 -4
  46. package/dist/tasks/verification.d.ts +31 -0
  47. package/dist/tasks/verification.js +20 -0
  48. package/dist/tools/bash.d.ts +13 -0
  49. package/dist/tools/bash.js +123 -20
  50. package/dist/tools/edit.js +36 -5
  51. package/dist/tools/event-manage.d.ts +25 -4
  52. package/dist/tools/event-manage.js +81 -33
  53. package/dist/tools/glob.js +57 -4
  54. package/dist/tools/grep.d.ts +2 -0
  55. package/dist/tools/grep.js +187 -14
  56. package/dist/tools/job.js +16 -4
  57. package/dist/tools/memory-manage.js +80 -41
  58. package/dist/tools/read.js +42 -5
  59. package/dist/tools/registry.d.ts +6 -0
  60. package/dist/tools/registry.js +4 -1
  61. package/dist/tools/send-media.js +6 -4
  62. package/dist/tools/session-search.js +4 -1
  63. package/dist/tools/skill.d.ts +2 -0
  64. package/dist/tools/skill.js +12 -0
  65. package/dist/tools/subagent-manage.js +1 -1
  66. package/dist/tools/subagent-tool-names.d.ts +11 -0
  67. package/dist/tools/subagent-tool-names.js +19 -0
  68. package/dist/tools/task-manage/lifecycle.js +2 -6
  69. package/dist/tools/task-manage/log-view.js +6 -3
  70. package/dist/tools/task-manage/schema.d.ts +6 -6
  71. package/dist/tools/task-manage/schema.js +5 -12
  72. package/dist/tools/task-manage/shared.d.ts +11 -0
  73. package/dist/tools/task-manage/shared.js +43 -2
  74. package/dist/tools/task-manage/step-end.js +28 -13
  75. package/dist/tools/task-manage.js +9 -1
  76. package/dist/tools/web-cache.d.ts +11 -3
  77. package/dist/tools/web-cache.js +26 -8
  78. package/dist/tools/web-fetch.d.ts +1 -0
  79. package/dist/tools/web-fetch.js +68 -15
  80. package/dist/tools/write.js +3 -0
  81. package/dist/web/fetch.d.ts +5 -0
  82. package/dist/web/fetch.js +36 -1
  83. package/examples/sub-agents/README.md +65 -39
  84. package/examples/sub-agents/builder-hard.md +12 -25
  85. package/examples/sub-agents/builder.md +12 -24
  86. package/examples/sub-agents/explorer.md +13 -17
  87. package/examples/sub-agents/git-committer.md +16 -19
  88. package/examples/sub-agents/planner.md +11 -20
  89. package/examples/sub-agents/reviewer.md +11 -30
  90. package/examples/sub-agents/verifier.md +13 -22
  91. package/examples/sub-agents/worker.md +12 -20
  92. package/package.json +7 -3
  93. package/examples/sub-agents/documenter.md +0 -50
  94. package/examples/sub-agents/log-sifter.md +0 -47
  95. package/examples/sub-agents/scout.md +0 -34
@@ -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";
@@ -12,6 +13,7 @@ import { renderStandardTaskBody, renderTaskDocument } from "../../tasks/ledger.j
12
13
  import { parseTaskEventName } from "../../tasks/task-events.js";
13
14
  import { validateTaskSchedule } from "../../tasks/task-schedule.js";
14
15
  import { describeTicket } from "../../tasks/ticket.js";
16
+ import { completionVerificationBlockReason } from "../../tasks/verification.js";
15
17
  import { RecoverableToolError } from "../tool-details.js";
16
18
  export function tasksDir(options) {
17
19
  return join(options.channelDir, "tasks");
@@ -57,8 +59,21 @@ export function normalizeBudget(budget) {
57
59
  }
58
60
  next[key] = value;
59
61
  }
60
- if (budget.until !== undefined)
61
- 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
+ }
62
77
  return Object.keys(next).length > 0 ? next : undefined;
63
78
  }
64
79
  export function normalizeSchedule(schedule) {
@@ -189,3 +204,29 @@ export async function cleanupTaskEvents(options, id) {
189
204
  }
190
205
  return { deleted };
191
206
  }
207
+ /**
208
+ * The verification gate both close entry points share (`task_step_end outcome=done` and
209
+ * `task_close outcome=complete`).
210
+ *
211
+ * It exists as one function because the two used to ask the question separately and both asked
212
+ * the weaker one — "did a PASS ever land in this cycle" — which a contract edit or a further code
213
+ * change made *after* the PASS would still satisfy. The real check is re-run here, against the
214
+ * contract and the checkout as they stand at close time.
215
+ */
216
+ export async function assertVerificationHoldsForClose(options, document, id) {
217
+ if (document.fields.verify !== "required")
218
+ return;
219
+ const runManager = getSubAgentRunManager(options.channelId);
220
+ const reason = await completionVerificationBlockReason({
221
+ channelDir: options.channelDir,
222
+ taskId: id,
223
+ taskBody: document.body,
224
+ cycleId: document.fields.cycle?.id,
225
+ findRunWorkingDirectory: (runId) => runManager.get(runId)?.workingDirectory,
226
+ fallbackWorkingDirectory: options.workingDirectory,
227
+ });
228
+ if (!reason)
229
+ return;
230
+ throw new RecoverableToolError(`Task "${id}" requires independent verification and it does not currently hold: ${reason}. ` +
231
+ `Dispatch a purpose=verify sub-agent with taskId=${id} against the artifact you are about to deliver, and let its PASS land before finishing.`);
232
+ }
@@ -1,12 +1,11 @@
1
1
  import { renderCloseSummary, writeLastResult } from "../../tasks/cycle.js";
2
2
  import { applyTaskPlanPatch, normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../tasks/ledger.js";
3
3
  import { appendTaskLog } from "../../tasks/log.js";
4
- import { hasPassingRound } from "../../tasks/rounds.js";
5
4
  import { queueTaskNotice } from "../../tasks/steer.js";
6
5
  import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
7
6
  import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
8
7
  import { RecoverableToolError } from "../tool-details.js";
9
- import { buildTicketContext, cleanupTaskEvents, requiredField } from "./shared.js";
8
+ import { assertVerificationHoldsForClose, buildTicketContext, cleanupTaskEvents, requiredField } from "./shared.js";
10
9
  /**
11
10
  * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4).
12
11
  *
@@ -26,6 +25,10 @@ export async function endTaskStep(options, request) {
26
25
  throw new RecoverableToolError(`Task "${id}" no longer exists; nothing to end.`);
27
26
  const cycleId = document.fields.cycle?.id ?? options.cycleId ?? "-";
28
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
+ }
29
32
  if (request.planSteps?.length) {
30
33
  document.body = applyTaskPlanPatch(document.body, request.planSteps).body;
31
34
  }
@@ -39,11 +42,21 @@ export async function endTaskStep(options, request) {
39
42
  // Steps are silent by default (D3); `notify` is the explicit opt-in the runtime delivers once
40
43
  // the step ends. `blocked` always speaks — a task waiting on the user that says nothing is the
41
44
  // same silent dead end tickets exist to prevent.
42
- if (request.notify?.trim())
43
- await queueTaskNotice(options.channelDir, id, request.notify);
44
- else if (request.outcome === "blocked") {
45
- await queueTaskNotice(options.channelDir, id, `任务 ${id} 需要你的决定:${request.reason ?? note}`);
46
- }
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
+ };
47
60
  if (request.outcome === "done") {
48
61
  const summary = requiredField(request.summary, "summary", "task_step_end outcome=done");
49
62
  const evidence = requiredField(request.evidence, "evidence", "task_step_end outcome=done");
@@ -52,12 +65,11 @@ export async function endTaskStep(options, request) {
52
65
  throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
53
66
  }
54
67
  // Verification is imported by the runtime when a purpose=verify run settles (D7), so what
55
- // gates `done` here is whether a PASS actually landed in this cycle — not whether the model
56
- // remembered to call an import tool.
57
- if (document.fields.verify === "required" &&
58
- !(await hasPassingRound(options.channelDir, id, document.fields.cycle?.id))) {
59
- throw new RecoverableToolError(`Task "${id}" requires independent verification; dispatch a purpose=verify sub-agent with taskId=${id} and let its PASS land before finishing.`);
60
- }
68
+ // gates `done` here is the cycle's verification ledger — not whether the model remembered to
69
+ // call an import tool. The settled verdict is re-bound to the contract and the checkout as
70
+ // they are *now*: a PASS is evidence about the artifact the verifier saw, and the loop can
71
+ // edit both after it lands.
72
+ await assertVerificationHoldsForClose(options, document, id);
61
73
  const cycle = document.fields.cycle;
62
74
  document.body = writeLastResult(document.body, renderCloseSummary({
63
75
  cycleId,
@@ -90,6 +102,7 @@ export async function endTaskStep(options, request) {
90
102
  document.fields.ticket = ticket;
91
103
  await writeStoredTask(document);
92
104
  await logStep("done");
105
+ await flushNotice();
93
106
  return {
94
107
  action: "step_end",
95
108
  id,
@@ -99,6 +112,7 @@ export async function endTaskStep(options, request) {
99
112
  }
100
113
  await writeStoredTask(document);
101
114
  await logStep("done");
115
+ await flushNotice();
102
116
  const { deleted } = await cleanupTaskEvents(options, id);
103
117
  await archiveTask(options.channelDir, id, "completed");
104
118
  return {
@@ -132,5 +146,6 @@ export async function endTaskStep(options, request) {
132
146
  }
133
147
  await writeStoredTask(document);
134
148
  await logStep(request.outcome);
149
+ await flushNotice();
135
150
  return { action: "step_end", id, state: document.fields.state, notice };
136
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;
@@ -3,7 +3,7 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
3
3
  import { resolveWebFetchRequest } from "../web/config.js";
4
4
  import { runWebFetch } from "../web/fetch.js";
5
5
  import { formatFetchedText, UNTRUSTED_WEB_CONTENT_BANNER } from "../web/format.js";
6
- import { readWebCache, webCacheKey, writeWebCache } from "./web-cache.js";
6
+ import { clearWebCacheEntry, readWebCache, webCacheKey, writeWebCache } from "./web-cache.js";
7
7
  // Large cap used to fetch the full readable body for caching; the displayed window is bounded by the
8
8
  // configured/requested maxChars. Still smaller than maxResponseBytes so a hostile page can't OOM us.
9
9
  const FULL_FETCH_MAX_CHARS = 2_000_000;
@@ -15,7 +15,10 @@ const webFetchSchema = Type.Object({
15
15
  maxChars: Type.Optional(Type.Number({ description: "Maximum extracted text characters to return per call" })),
16
16
  offset: Type.Optional(Type.Integer({
17
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.",
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 the cached snapshot with no refetch.",
19
+ })),
20
+ refresh: Type.Optional(Type.Boolean({
21
+ description: "Bypass the cached snapshot and fetch the page again. Use when you need current content.",
19
22
  })),
20
23
  });
21
24
  /** Strip the untrusted-content banner that runWebFetch prepends, so the cached body is clean. */
@@ -25,25 +28,54 @@ function stripBanner(text) {
25
28
  }
26
29
  return text;
27
30
  }
28
- function windowResult(body, offset, maxChars, url, fromCache) {
31
+ function ageHint(fetchedAt) {
32
+ const seconds = Math.max(0, Math.round((Date.now() - fetchedAt) / 1000));
33
+ if (seconds < 90)
34
+ return "just now";
35
+ if (seconds < 3600)
36
+ return `${Math.round(seconds / 60)}m ago`;
37
+ return `${Math.round(seconds / 3600)}h ago`;
38
+ }
39
+ function windowResult(entry, requestedUrl, offset, maxChars, fromCache) {
40
+ const body = entry.body;
29
41
  const start = Math.min(offset, body.length);
30
42
  const end = Math.min(start + maxChars, body.length);
31
43
  const slice = body.slice(start, end);
32
44
  let text = formatFetchedText(slice);
45
+ const notes = [];
46
+ if (entry.finalUrl && entry.finalUrl !== requestedUrl) {
47
+ notes.push(`Final URL after redirects: ${entry.finalUrl}`);
48
+ }
49
+ if (fromCache) {
50
+ notes.push(`Snapshot fetched ${ageHint(entry.fetchedAt)}; pass refresh:true for current content.`);
51
+ }
52
+ // "This page has more to page through" and "the origin gave us a partial page" are different
53
+ // facts and must not be conflated (fix plan §2.7).
33
54
  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}.]`;
55
+ notes.push(`Showing chars ${start}-${end} of ${body.length} in this snapshot. Re-call with the same url and offset=${end} to continue.`);
36
56
  }
37
57
  else if (offset >= body.length && body.length > 0) {
38
- text += `\n\n[Reached end of page (${body.length} chars). No more content.]`;
58
+ notes.push(`End of the cached snapshot (${body.length} chars).`);
59
+ }
60
+ if (entry.sourceTruncated) {
61
+ notes.push(`The origin returned more than the fetch limit — even at the end of this snapshot you have NOT seen the whole page.`);
62
+ }
63
+ if (notes.length > 0) {
64
+ text += `\n\n[${notes.join(" ")}]`;
39
65
  }
40
66
  return {
41
67
  content: [{ type: "text", text }],
42
68
  details: {
43
- url,
69
+ url: requestedUrl,
70
+ finalUrl: entry.finalUrl || requestedUrl,
71
+ status: entry.status,
72
+ extractor: entry.extractor,
73
+ contentType: entry.contentType,
44
74
  offset: start,
45
75
  shownChars: slice.length,
46
76
  totalChars: body.length,
77
+ sourceTruncated: entry.sourceTruncated,
78
+ fetchedAt: entry.fetchedAt,
47
79
  fromCache,
48
80
  untrusted: true,
49
81
  },
@@ -54,9 +86,10 @@ export function createWebFetchTool(options) {
54
86
  name: "web_fetch",
55
87
  label: "web_fetch",
56
88
  description: "Fetch a public URL and extract readable content. Returns text for HTML/JSON/text pages and image content " +
57
- "blocks for images. Long pages are cached per channel; page through them with offset (no refetch).",
89
+ "blocks for images (binary downloads like PDFs are refused — download then read). Long pages are cached " +
90
+ "per channel as a snapshot; page through with offset (no refetch), or pass refresh:true for current content.",
58
91
  parameters: webFetchSchema,
59
- execute: async (_toolCallId, { url, extractMode, maxChars, offset, }, signal) => {
92
+ execute: async (_toolCallId, { url, extractMode, maxChars, offset, refresh, }, signal) => {
60
93
  const request = resolveWebFetchRequest(options.webConfig.fetch, url, extractMode, maxChars);
61
94
  const displayMaxChars = request.maxChars;
62
95
  const startOffset = offset && offset > 0 ? offset : 0;
@@ -78,9 +111,21 @@ export function createWebFetchTool(options) {
78
111
  }, request, signal);
79
112
  }
80
113
  const key = webCacheKey(url, request.extractMode);
81
- const cached = await readWebCache(options.channelDir, key);
82
- if (cached) {
83
- return windowResult(cached.body, startOffset, displayMaxChars, url, true);
114
+ if (refresh) {
115
+ await clearWebCacheEntry(options.channelDir, key);
116
+ }
117
+ else {
118
+ const cached = await readWebCache(options.channelDir, key);
119
+ if (cached) {
120
+ return windowResult(cached, url, startOffset, displayMaxChars, true);
121
+ }
122
+ }
123
+ // Paging into a page whose snapshot has expired (or was never taken) must not silently
124
+ // stitch a window of a *fresh* snapshot onto offsets the model computed against an older
125
+ // one. Make it re-read from the top.
126
+ if (startOffset > 0) {
127
+ throw new RecoverableToolError(`The cached snapshot for ${url} is no longer available, so offset=${startOffset} would point into a different version of the page. ` +
128
+ "Re-call web_fetch with offset=0 (optionally refresh:true) to take a fresh snapshot, then page from there.");
84
129
  }
85
130
  // Cache miss: fetch the full readable body once, cache it, then serve the window.
86
131
  const result = await runWebFetch({
@@ -95,9 +140,17 @@ export function createWebFetchTool(options) {
95
140
  if (hasImage || !textPart || textPart.type !== "text") {
96
141
  return result;
97
142
  }
98
- const body = stripBanner(textPart.text);
99
- await writeWebCache(options.channelDir, key, body);
100
- return windowResult(body, startOffset, displayMaxChars, url, false);
143
+ const entry = {
144
+ body: stripBanner(textPart.text),
145
+ fetchedAt: Date.now(),
146
+ finalUrl: result.details.finalUrl,
147
+ status: result.details.status,
148
+ extractor: result.details.extractor,
149
+ contentType: result.details.contentType,
150
+ sourceTruncated: result.details.truncated === true,
151
+ };
152
+ await writeWebCache(options.channelDir, key, entry);
153
+ return windowResult(entry, url, startOffset, displayMaxChars, false);
101
154
  },
102
155
  };
103
156
  }
@@ -8,6 +8,9 @@ export function createWriteTool(fileStore, options = {}) {
8
8
  return {
9
9
  name: "write",
10
10
  label: "write",
11
+ // Serialize with other mutating tools in the same batch: two concurrent whole-file writes
12
+ // each pass the pre-write fingerprint check and then clobber each other (spec: batch 1.3).
13
+ executionMode: "sequential",
11
14
  description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
12
15
  parameters: writeSchema,
13
16
  execute: async (_toolCallId, { path, content }, signal) => {
@@ -1,5 +1,6 @@
1
1
  import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
3
4
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
4
5
  import { type FormattedFetchDetails } from "./format.js";
5
6
  export interface WebFetchExecutionContext {
@@ -12,6 +13,10 @@ export interface WebFetchOutput {
12
13
  content: Array<TextContent | ImageContent>;
13
14
  details: FormattedFetchDetails;
14
15
  }
16
+ /** Thrown when a URL serves a binary payload `web_fetch` should not try to render as text. */
17
+ export declare class WebFetchBinaryError extends RecoverableToolError {
18
+ constructor(url: string, contentType: string);
19
+ }
15
20
  export declare function runWebFetch(context: WebFetchExecutionContext, request: {
16
21
  url: string;
17
22
  extractMode: "markdown" | "text";
package/dist/web/fetch.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
1
2
  import { createWebHttpClient } from "./client.js";
2
3
  import { extractReadableContent } from "./extract.js";
3
4
  import { buildFetchedImageContent, buildFetchedTextContent } from "./format.js";
@@ -10,6 +11,31 @@ function trimToMaxChars(text, maxChars) {
10
11
  truncated: true,
11
12
  };
12
13
  }
14
+ /** Thrown when a URL serves a binary payload `web_fetch` should not try to render as text. */
15
+ export class WebFetchBinaryError extends RecoverableToolError {
16
+ constructor(url, contentType) {
17
+ super(`${url} is a binary download (${contentType.split(";")[0]}), not a readable page. ` +
18
+ "Download it with bash (curl -L -o <file>), then open it with the read tool.");
19
+ this.name = "WebFetchBinaryError";
20
+ }
21
+ }
22
+ const BINARY_CONTENT_TYPE_HINTS = [
23
+ "application/pdf",
24
+ "application/zip",
25
+ "application/gzip",
26
+ "application/x-tar",
27
+ "application/octet-stream",
28
+ "application/x-7z-compressed",
29
+ "application/vnd.openxmlformats-officedocument",
30
+ "application/msword",
31
+ "application/vnd.ms-excel",
32
+ "audio/",
33
+ "video/",
34
+ "font/",
35
+ ];
36
+ function isBinaryContentType(contentType) {
37
+ return BINARY_CONTENT_TYPE_HINTS.some((hint) => contentType.includes(hint));
38
+ }
13
39
  function decodeUtf8(body) {
14
40
  return new TextDecoder("utf-8", { fatal: false }).decode(body);
15
41
  }
@@ -95,6 +121,13 @@ async function fetchDirect(context, url, extractMode, maxChars, maxImageBytes, m
95
121
  },
96
122
  };
97
123
  }
124
+ // Non-HTML/JSON binary payloads (PDF, archives, media) would be `decodeUtf8`'d into mojibake and
125
+ // passed off as page text. Refuse them with the right next step (fix plan §2.7). `octet-stream`
126
+ // is also the default when a server sends no content-type, so let a body that sniffs as HTML
127
+ // through rather than rejecting a headerless HTML page.
128
+ if (isBinaryContentType(contentType) && !isHtmlContent(contentType, response.body)) {
129
+ throw new WebFetchBinaryError(url, contentType);
130
+ }
98
131
  let text = "";
99
132
  let extractor = "raw";
100
133
  if (contentType.includes("application/json")) {
@@ -138,7 +171,9 @@ export async function runWebFetch(context, request, signal) {
138
171
  return await fetchDirect(context, request.url, request.extractMode, request.maxChars, request.maxImageBytes, request.maxResponseBytes, signal);
139
172
  }
140
173
  catch (error) {
141
- if (!request.enableJinaFallback) {
174
+ // A binary payload is a definitive answer, not a transient direct-fetch failure — jina would
175
+ // just return the same non-text content.
176
+ if (error instanceof WebFetchBinaryError || !request.enableJinaFallback) {
142
177
  throw error;
143
178
  }
144
179
  const jinaResult = await tryFetchViaJina(context, request.url, request.maxChars, request.maxResponseBytes, signal);