@miphamai/cli 0.85.17 → 0.85.18
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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +7 -0
- package/src/config/defaults.ts +6 -1
- package/src/core/credential-masker/output-scrub.ts +8 -1
- package/src/core/engine.ts +43 -4
- package/src/core/instructions.ts +20 -1
- package/src/core/permission-rules.ts +52 -4
- package/src/core/permission.ts +6 -2
- package/src/core/session-log.ts +10 -0
- package/src/i18n-core/locales/en-US.json +1 -1
- package/src/i18n-core/locales/zh-CN.json +1 -1
- package/src/index.tsx +22 -1
- package/src/mcp/client.ts +20 -1
- package/src/mcp/http-transport.ts +48 -3
- package/src/providers/anthropic.ts +47 -12
- package/src/providers/fetch-utils.ts +48 -3
- package/src/providers/openai-compat.ts +13 -10
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +12 -0
- package/src/skills/loader.ts +13 -2
- package/src/skills/sanitizer.ts +16 -8
- package/src/tools/artifact/artifact.ts +9 -9
- package/src/tools/file/read.ts +21 -0
- package/src/tools/network/web-fetch.ts +87 -22
- package/src/tools/scheduling/schedule-wakeup.ts +156 -32
- package/src/ui/app.tsx +46 -5
|
@@ -125,10 +125,12 @@ export async function fetchWithRetry(
|
|
|
125
125
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
126
126
|
const controller = new AbortController()
|
|
127
127
|
let timedOut = false
|
|
128
|
-
|
|
128
|
+
// Awake-time, not wall-clock: a machine that slept through the window has
|
|
129
|
+
// not actually waited `timeout` ms for a first byte (see `createAwakeTimer`).
|
|
130
|
+
const cancelTimer = createAwakeTimer(timeout, () => {
|
|
129
131
|
timedOut = true
|
|
130
132
|
controller.abort()
|
|
131
|
-
}
|
|
133
|
+
})
|
|
132
134
|
// `AbortSignal.any` (node ≥22 / bun ≥1.2, both in `engines`) instead of a
|
|
133
135
|
// hand-rolled combiner: it keeps a *weak* reference to the source signals, so
|
|
134
136
|
// the combination stays live for the reader without pinning the caller's
|
|
@@ -161,7 +163,7 @@ export async function fetchWithRetry(
|
|
|
161
163
|
}
|
|
162
164
|
await sleep(baseDelay * Math.pow(2, attempt))
|
|
163
165
|
} finally {
|
|
164
|
-
|
|
166
|
+
cancelTimer()
|
|
165
167
|
// Nothing to release: the combination is natively managed. Do NOT abort
|
|
166
168
|
// anything here — `fetch` holds that signal and the caller reads the body
|
|
167
169
|
// *after* we return, so aborting it at this point errored every response at
|
|
@@ -199,3 +201,46 @@ export function streamIdleTimeoutMs(effort?: string): number {
|
|
|
199
201
|
const multiplier = effort ? (EFFORT_TIMEOUT_MULTIPLIER[effort] ?? 1) : 1
|
|
200
202
|
return STREAM_IDLE_TIMEOUT_BASE_MS * multiplier
|
|
201
203
|
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* A timeout that measures *awake* time, and so survives the machine sleeping.
|
|
207
|
+
*
|
|
208
|
+
* `setTimeout` runs on the wall clock. A laptop suspended for an hour fires every
|
|
209
|
+
* pending timer the instant it wakes, so a 90-second idle budget is reported the
|
|
210
|
+
* moment the user opens the lid — the stream is declared stalled and the turn is
|
|
211
|
+
* killed, even though the connection sat idle for zero seconds of real time.
|
|
212
|
+
*
|
|
213
|
+
* `performance.now()` is monotonic and does not advance while the host is
|
|
214
|
+
* suspended, so the difference it reports is time the machine was actually awake.
|
|
215
|
+
* When the timer fires with less than `budgetMs` of awake time behind it, the
|
|
216
|
+
* shortfall was a sleep: re-arm for the remainder instead of firing.
|
|
217
|
+
*
|
|
218
|
+
* Returns a cancel function.
|
|
219
|
+
*/
|
|
220
|
+
export function createAwakeTimer(budgetMs: number, onExpire: () => void): () => void {
|
|
221
|
+
// The epoch the budget is measured from. Kept across a re-arm so the next
|
|
222
|
+
// check compares against the total awake time, not just the last slice.
|
|
223
|
+
const start = performance.now()
|
|
224
|
+
let handle: ReturnType<typeof setTimeout> | undefined
|
|
225
|
+
let cancelled = false
|
|
226
|
+
|
|
227
|
+
const arm = (remainingMs: number): void => {
|
|
228
|
+
handle = setTimeout(() => {
|
|
229
|
+
if (cancelled) return
|
|
230
|
+
const elapsed = performance.now() - start
|
|
231
|
+
if (elapsed < budgetMs) {
|
|
232
|
+
// Woke from sleep: only part of the budget was really spent. Keep the
|
|
233
|
+
// epoch and re-arm for what is left.
|
|
234
|
+
arm(Math.max(0, budgetMs - elapsed))
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
onExpire()
|
|
238
|
+
}, remainingMs)
|
|
239
|
+
}
|
|
240
|
+
arm(budgetMs)
|
|
241
|
+
|
|
242
|
+
return () => {
|
|
243
|
+
cancelled = true
|
|
244
|
+
if (handle !== undefined) clearTimeout(handle)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { execSync } from 'node:child_process'
|
|
2
2
|
import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
|
|
3
3
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
fetchWithRetry,
|
|
6
|
+
streamIdleTimeoutMs,
|
|
7
|
+
isRetryableFailure,
|
|
8
|
+
createAwakeTimer,
|
|
9
|
+
} from './fetch-utils'
|
|
5
10
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
6
11
|
|
|
7
12
|
export class OpenAICompatProvider implements ProviderInstance {
|
|
@@ -81,19 +86,17 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
81
86
|
try {
|
|
82
87
|
while (true) {
|
|
83
88
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
84
|
-
let
|
|
89
|
+
let cancelIdle: (() => void) | undefined
|
|
85
90
|
try {
|
|
86
91
|
readResult = await Promise.race([
|
|
87
92
|
reader.read(),
|
|
88
93
|
new Promise<never>((_, reject) => {
|
|
89
|
-
|
|
90
|
-
(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
94
|
-
),
|
|
94
|
+
cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
|
|
95
|
+
reject(
|
|
96
|
+
new Error(
|
|
97
|
+
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
95
98
|
),
|
|
96
|
-
|
|
99
|
+
),
|
|
97
100
|
)
|
|
98
101
|
}),
|
|
99
102
|
])
|
|
@@ -101,7 +104,7 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
101
104
|
yield { type: 'error', error: `Stream stalled: ${String(err)}` }
|
|
102
105
|
return
|
|
103
106
|
} finally {
|
|
104
|
-
|
|
107
|
+
cancelIdle?.()
|
|
105
108
|
}
|
|
106
109
|
const { done, value } = readResult
|
|
107
110
|
if (done) break
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export const PACKAGE_NAME = '@miphamai/cli' as const
|
|
10
10
|
|
|
11
11
|
/** 当前发布版本 */
|
|
12
|
-
export const PACKAGE_VERSION = '0.85.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.18' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 4076 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -639,6 +639,18 @@ export interface ToolContext {
|
|
|
639
639
|
* the experience logs use. Absent for the main session.
|
|
640
640
|
*/
|
|
641
641
|
agentName?: string
|
|
642
|
+
/**
|
|
643
|
+
* The bucket an artifact belongs in, when that is not `sessionId`.
|
|
644
|
+
*
|
|
645
|
+
* A sub-agent's `sessionId` is the literal `'sub-agent'` — `SendMessage` keys
|
|
646
|
+
* off that literal to address the parent, so it cannot be changed. Artifacts
|
|
647
|
+
* keyed off the same field therefore put **every** sub-agent in every session
|
|
648
|
+
* into one bucket, and `archiveVersion` then treats an unrelated agent's
|
|
649
|
+
* same-named artifact as "the previous version" of this one. Set by
|
|
650
|
+
* `SubAgent.runExecution` to the parent session plus the agent's name; absent
|
|
651
|
+
* everywhere else, where `sessionId` is already the right answer.
|
|
652
|
+
*/
|
|
653
|
+
artifactSessionId?: string
|
|
642
654
|
}
|
|
643
655
|
|
|
644
656
|
export interface ToolDefinition {
|
package/src/skills/loader.ts
CHANGED
|
@@ -245,8 +245,19 @@ export class SkillsLoader implements Skills {
|
|
|
245
245
|
}
|
|
246
246
|
|
|
247
247
|
private nameFromPath(path: string): string {
|
|
248
|
-
const
|
|
249
|
-
|
|
248
|
+
const parts = path.split('/').filter(Boolean)
|
|
249
|
+
const base = parts.pop() ?? ''
|
|
250
|
+
// `foo.SKILL.md` / `foo.mipham-skill.md` — the file name carries the skill.
|
|
251
|
+
const stem = base.replace(/\.md$/i, '').replace(/\.(SKILL|mipham-skill)$/i, '')
|
|
252
|
+
if (stem && stem !== 'SKILL' && stem !== 'mipham-skill') return stem
|
|
253
|
+
// Directory layout (`skills/<name>/SKILL.md`, the Claude-plugin shape). Every
|
|
254
|
+
// one of these files is literally named `SKILL.md`, so the file name names
|
|
255
|
+
// nothing — they all collide on one key and the last loaded silently wins.
|
|
256
|
+
// The folder is the name. Skip the `skills` bucket itself so a flat
|
|
257
|
+
// `skills/SKILL.md` falls through to the plugin directory above it.
|
|
258
|
+
let dir = parts.pop()
|
|
259
|
+
while (dir === 'skills') dir = parts.pop()
|
|
260
|
+
return dir || base
|
|
250
261
|
}
|
|
251
262
|
}
|
|
252
263
|
|
package/src/skills/sanitizer.ts
CHANGED
|
@@ -71,11 +71,19 @@ const SOURCE_TAGS: Record<string, string> = {
|
|
|
71
71
|
/**
|
|
72
72
|
* Sanitize a skill body (markdown instructions) for safe execution.
|
|
73
73
|
*
|
|
74
|
-
*
|
|
75
|
-
* - `!
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
74
|
+
* Three transformations, each of which also pushes a warning:
|
|
75
|
+
* - a line starting with `!command` → `! command`. The inserted character is a
|
|
76
|
+
* **plain space**, which is what breaks the exact `!`-prefixed shape a session
|
|
77
|
+
* treats as a shell command. Deliberately *not* a zero-width space: U+200B is on
|
|
78
|
+
* the dangerous-invisible strip list in `shared/sanitize.ts`, so a ZWSP written
|
|
79
|
+
* here would be removed further down the pipe and the neutralization would undo
|
|
80
|
+
* itself.
|
|
81
|
+
* - `@file.ext` references → `@ file.ext` (a space after the `@` stops expansion)
|
|
82
|
+
* - an odd number of ``` fences → a closing fence is appended
|
|
83
|
+
*
|
|
84
|
+
* Detection is **line-scoped**: `!` must open its line, and the lookahead must find a
|
|
85
|
+
* non-space on that same line — hence `[^\S\n]*` rather than `\s*`, which would reach
|
|
86
|
+
* across the newline and report the next line's first word as a command.
|
|
79
87
|
*/
|
|
80
88
|
export function sanitizeSkillBody(body: string): SanitizeResult {
|
|
81
89
|
const warnings: string[] = []
|
|
@@ -84,15 +92,15 @@ export function sanitizeSkillBody(body: string): SanitizeResult {
|
|
|
84
92
|
|
|
85
93
|
// ── 1. Detect and warn about `!` shell command patterns ──
|
|
86
94
|
// Pattern: line starting with `!` (Bash command marker in some AI contexts)
|
|
87
|
-
const bangCommandRegex =
|
|
95
|
+
const bangCommandRegex = /^![^\S\n]*(\S+)/gm
|
|
88
96
|
let bangMatch: RegExpExecArray | null
|
|
89
97
|
const bangCommands: string[] = []
|
|
90
98
|
while ((bangMatch = bangCommandRegex.exec(text)) !== null) {
|
|
91
99
|
bangCommands.push(bangMatch[1] || '')
|
|
92
100
|
}
|
|
93
101
|
if (bangCommands.length > 0) {
|
|
94
|
-
// Escape `!` → `! ` (
|
|
95
|
-
text = text.replace(/^!(
|
|
102
|
+
// Escape `!` → `! ` (a plain space — see the docblock for why not a zero-width one)
|
|
103
|
+
text = text.replace(/^!(?=[^\S\n]*\S)/gm, '! ')
|
|
96
104
|
modified = true
|
|
97
105
|
warnings.push(
|
|
98
106
|
`Skill body contained ${bangCommands.length} shell-command-like patterns (${bangCommands.slice(0, 3).join(', ')}${bangCommands.length > 3 ? '...' : ''}). Escaped to prevent unintended command execution.`,
|
|
@@ -62,7 +62,11 @@ export const artifactTool: ToolDefinition = {
|
|
|
62
62
|
// directory are one and the same; computing it here is what made the URL a
|
|
63
63
|
// guaranteed 404 before.
|
|
64
64
|
const baseDir = artifactsRoot(ctx.cwd)
|
|
65
|
-
|
|
65
|
+
// Not always `ctx.sessionId`: a sub-agent's session id is the literal
|
|
66
|
+
// `'sub-agent'`, shared by every sub-agent in every session (see
|
|
67
|
+
// `ToolContext.artifactSessionId`).
|
|
68
|
+
const sessionId = ctx.artifactSessionId ?? ctx.sessionId
|
|
69
|
+
const sessionDir = join(baseDir, sessionId)
|
|
66
70
|
mkdirSync(sessionDir, { recursive: true })
|
|
67
71
|
|
|
68
72
|
const ext = type === 'svg' ? '.svg' : '.html'
|
|
@@ -82,9 +86,7 @@ export const artifactTool: ToolDefinition = {
|
|
|
82
86
|
const isUpdate = existsSync(filepath)
|
|
83
87
|
if (isUpdate) {
|
|
84
88
|
const manifest = readManifest(baseDir)
|
|
85
|
-
const existing = manifest.artifacts.find(
|
|
86
|
-
(a) => a.name === name && a.sessionId === ctx.sessionId,
|
|
87
|
-
)
|
|
89
|
+
const existing = manifest.artifacts.find((a) => a.name === name && a.sessionId === sessionId)
|
|
88
90
|
if (existing) {
|
|
89
91
|
archivedVersion = archiveVersion(baseDir, existing)
|
|
90
92
|
}
|
|
@@ -94,13 +96,11 @@ export const artifactTool: ToolDefinition = {
|
|
|
94
96
|
writeFileSync(filepath, content, 'utf-8')
|
|
95
97
|
|
|
96
98
|
// Build URL and manifest entry
|
|
97
|
-
const url = port
|
|
98
|
-
? `http://localhost:${port}/${ctx.sessionId}/${filename}`
|
|
99
|
-
: `file://${filepath}`
|
|
99
|
+
const url = port ? `http://localhost:${port}/${sessionId}/${filename}` : `file://${filepath}`
|
|
100
100
|
|
|
101
101
|
// Preserve existing version count
|
|
102
102
|
const manifestPre = readManifest(baseDir)
|
|
103
|
-
const prev = manifestPre.artifacts.find((a) => a.name === name && a.sessionId ===
|
|
103
|
+
const prev = manifestPre.artifacts.find((a) => a.name === name && a.sessionId === sessionId)
|
|
104
104
|
const versionCount = prev?.versionCount || (isUpdate ? 1 : undefined)
|
|
105
105
|
|
|
106
106
|
const { quarantined } = addToManifest(
|
|
@@ -112,7 +112,7 @@ export const artifactTool: ToolDefinition = {
|
|
|
112
112
|
size,
|
|
113
113
|
type: type as 'html' | 'svg',
|
|
114
114
|
createdAt: new Date().toISOString(),
|
|
115
|
-
sessionId
|
|
115
|
+
sessionId,
|
|
116
116
|
versions: prev?.versions,
|
|
117
117
|
versionCount,
|
|
118
118
|
},
|
package/src/tools/file/read.ts
CHANGED
|
@@ -193,6 +193,27 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
193
193
|
result = formatLines(lines, offset)
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
+
// ── Binary sniff ──
|
|
197
|
+
// A NUL byte is the tell `file(1)` and git both use for "this is not
|
|
198
|
+
// text". Without this, a PNG/zip/object file is decoded as UTF-8 with
|
|
199
|
+
// replacement characters and handed to the model as garbled "text" it
|
|
200
|
+
// will then reason about — a silently wrong answer, not an error.
|
|
201
|
+
//
|
|
202
|
+
// The check is on the string actually being returned, not on the head of
|
|
203
|
+
// the file: a *sparse* text file (a log preallocated with `truncate`, a
|
|
204
|
+
// hole in the middle) is real text where it was written, and reading its
|
|
205
|
+
// opening lines is exactly what a caller asking for line 1–3 wants. Only
|
|
206
|
+
// the bytes that would reach the model have to be text.
|
|
207
|
+
if (result.includes('\0')) {
|
|
208
|
+
return {
|
|
209
|
+
success: false,
|
|
210
|
+
content: '',
|
|
211
|
+
error:
|
|
212
|
+
`Not a text file (the requested window contains NUL bytes): ${filePath}. ` +
|
|
213
|
+
`Use a shell tool (e.g. \`file\`, \`xxd\`) to inspect binary content.`,
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
196
217
|
// ── Read tracking: mark file as read for Write tool safety ──
|
|
197
218
|
ctx.readFiles?.add(filePath)
|
|
198
219
|
return { success: true, content: result }
|
|
@@ -4,25 +4,37 @@ import { validateUrl } from '../../security/url'
|
|
|
4
4
|
|
|
5
5
|
// ── In-memory cache (15-min TTL per URL) ──
|
|
6
6
|
|
|
7
|
+
/** Most characters returned in one call. Past this the caller pages with `offset`. */
|
|
8
|
+
const MAX_RETURN_CHARS = 100_000
|
|
9
|
+
|
|
7
10
|
interface CacheEntry {
|
|
8
11
|
content: string
|
|
9
12
|
timestamp: number
|
|
13
|
+
/** Is `content` the whole page, or only its first `MAX_RETURN_CHARS`? */
|
|
14
|
+
complete: boolean
|
|
10
15
|
}
|
|
11
16
|
|
|
12
17
|
const CACHE_TTL = 15 * 60 * 1000 // 15 minutes
|
|
13
18
|
const cache = new Map<string, CacheEntry>()
|
|
14
19
|
|
|
15
|
-
|
|
20
|
+
/**
|
|
21
|
+
* `complete` says whether `content` is the whole page or only its first
|
|
22
|
+
* `MAX_RETURN_CHARS`. A caller asking past the end of an incomplete entry has to
|
|
23
|
+
* re-fetch: answering from the cache would report "no more content" for a page
|
|
24
|
+
* that has plenty, which is the same wrong answer a silently truncated read gave.
|
|
25
|
+
*/
|
|
26
|
+
function getCached(url: string, needFrom: number): CacheEntry | undefined {
|
|
16
27
|
const entry = cache.get(url)
|
|
17
28
|
if (!entry) return undefined
|
|
18
29
|
if (Date.now() - entry.timestamp > CACHE_TTL) {
|
|
19
30
|
cache.delete(url)
|
|
20
31
|
return undefined
|
|
21
32
|
}
|
|
22
|
-
|
|
33
|
+
if (!entry.complete && needFrom >= entry.content.length) return undefined
|
|
34
|
+
return entry
|
|
23
35
|
}
|
|
24
36
|
|
|
25
|
-
function setCache(url: string, content: string): void {
|
|
37
|
+
function setCache(url: string, content: string, complete: boolean): void {
|
|
26
38
|
// Evict oldest entries if cache grows too large (max 200 URLs)
|
|
27
39
|
if (cache.size >= 200) {
|
|
28
40
|
const oldest = [...cache.entries()].sort((a, b) => a[1].timestamp - b[1].timestamp)
|
|
@@ -30,7 +42,7 @@ function setCache(url: string, content: string): void {
|
|
|
30
42
|
cache.delete(oldest[i]![0])
|
|
31
43
|
}
|
|
32
44
|
}
|
|
33
|
-
cache.set(url, { content, timestamp: Date.now() })
|
|
45
|
+
cache.set(url, { content, timestamp: Date.now(), complete })
|
|
34
46
|
}
|
|
35
47
|
|
|
36
48
|
// ── HTTP→HTTPS upgrade ──
|
|
@@ -142,6 +154,54 @@ function resolveUrl(href: string, baseUrl: string): string {
|
|
|
142
154
|
}
|
|
143
155
|
}
|
|
144
156
|
|
|
157
|
+
// ── Result rendering ──
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Render the requested window of `full`, with the header and a notice saying how
|
|
161
|
+
* much of the page is *not* in this answer and which `offset` continues it.
|
|
162
|
+
*
|
|
163
|
+
* The notice is the point. A bare `... (truncated)` is indistinguishable from
|
|
164
|
+
* "this was the whole page", so the caller reports a partial read as a complete
|
|
165
|
+
* one; and without an `offset` to pass, everything past the first window was
|
|
166
|
+
* permanently unreachable rather than merely unread.
|
|
167
|
+
*/
|
|
168
|
+
function withOffsetNotice(
|
|
169
|
+
full: string,
|
|
170
|
+
offset: number,
|
|
171
|
+
prompt: string,
|
|
172
|
+
url: string,
|
|
173
|
+
complete: boolean,
|
|
174
|
+
): string {
|
|
175
|
+
const header = prompt
|
|
176
|
+
? `── WebFetch: ${url} ──\nPrompt: ${prompt}\n\n`
|
|
177
|
+
: `── WebFetch: ${url} ──\n\n`
|
|
178
|
+
|
|
179
|
+
if (offset >= full.length) {
|
|
180
|
+
return (
|
|
181
|
+
header +
|
|
182
|
+
`... (offset ${offset} is past the end: this page has ` +
|
|
183
|
+
`${complete ? full.length : `at least ${full.length}`} characters)`
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const window = full.slice(offset, offset + MAX_RETURN_CHARS)
|
|
188
|
+
const end = offset + window.length
|
|
189
|
+
|
|
190
|
+
// Whole page, asked for from the start — nothing to qualify.
|
|
191
|
+
if (complete && offset === 0 && end === full.length) return header + window
|
|
192
|
+
|
|
193
|
+
const total = complete ? `${full.length}` : `at least ${full.length}`
|
|
194
|
+
const remaining = complete ? full.length - end : undefined
|
|
195
|
+
const notice =
|
|
196
|
+
remaining === undefined
|
|
197
|
+
? `\n\n... (characters ${offset}–${end - 1} of ${total}; call again with offset=${end} for more)`
|
|
198
|
+
: remaining > 0
|
|
199
|
+
? `\n\n... (characters ${offset}–${end - 1} of ${total}; ${remaining} unread — call again with offset=${end} for the next part)`
|
|
200
|
+
: `\n\n... (characters ${offset}–${end - 1} of ${total}; end of page)`
|
|
201
|
+
|
|
202
|
+
return header + window + notice
|
|
203
|
+
}
|
|
204
|
+
|
|
145
205
|
// ── Tool Definition ──
|
|
146
206
|
|
|
147
207
|
export const webFetchTool: ToolDefinition = {
|
|
@@ -157,7 +217,12 @@ export const webFetchTool: ToolDefinition = {
|
|
|
157
217
|
prompt: {
|
|
158
218
|
type: 'string',
|
|
159
219
|
description:
|
|
160
|
-
'What to extract from the page (e.g., "find the API docs for authentication"). The tool returns the
|
|
220
|
+
'What to extract from the page (e.g., "find the API docs for authentication"). The tool returns the page content — truncated past 100,000 characters, with the omitted count stated — and the prompt helps focus extraction.',
|
|
221
|
+
},
|
|
222
|
+
offset: {
|
|
223
|
+
type: 'integer',
|
|
224
|
+
description:
|
|
225
|
+
'Character offset to start reading from (default 0). A long page is returned 100,000 characters at a time; the truncation notice names the offset to pass next.',
|
|
161
226
|
},
|
|
162
227
|
},
|
|
163
228
|
required: ['url'],
|
|
@@ -165,15 +230,17 @@ export const webFetchTool: ToolDefinition = {
|
|
|
165
230
|
async execute(params, _ctx) {
|
|
166
231
|
const rawUrl = params.url as string
|
|
167
232
|
const prompt = (params.prompt as string) || ''
|
|
233
|
+
const offset = Math.max(0, Number(params.offset) || 0)
|
|
168
234
|
const url = upgradeToHttps(rawUrl)
|
|
169
235
|
|
|
170
|
-
// Check cache
|
|
171
|
-
|
|
236
|
+
// Check cache — an incomplete entry (first 100k only) cannot answer a
|
|
237
|
+
// request that starts past what it holds.
|
|
238
|
+
const cached = getCached(url, offset)
|
|
172
239
|
if (cached) {
|
|
173
240
|
return {
|
|
174
241
|
success: true,
|
|
175
|
-
content: cached,
|
|
176
|
-
metadata: { cached: true, url },
|
|
242
|
+
content: withOffsetNotice(cached.content, offset, prompt, url, cached.complete),
|
|
243
|
+
metadata: { cached: true, url, offset },
|
|
177
244
|
}
|
|
178
245
|
}
|
|
179
246
|
|
|
@@ -259,20 +326,18 @@ export const webFetchTool: ToolDefinition = {
|
|
|
259
326
|
content = await response.text()
|
|
260
327
|
}
|
|
261
328
|
|
|
262
|
-
//
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
setCache(url, content)
|
|
329
|
+
// Cache the first window. The cache stays the size it always was (one
|
|
330
|
+
// `MAX_RETURN_CHARS` per URL) — `complete` is what lets a later `offset`
|
|
331
|
+
// tell "this is the whole page" apart from "this is the first slice of it",
|
|
332
|
+
// and re-fetch when it needs more.
|
|
333
|
+
const complete = content.length <= MAX_RETURN_CHARS
|
|
334
|
+
setCache(url, content.slice(0, MAX_RETURN_CHARS), complete)
|
|
269
335
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
:
|
|
274
|
-
|
|
275
|
-
return { success: true, content: header + content, metadata: { url, size: content.length } }
|
|
336
|
+
return {
|
|
337
|
+
success: true,
|
|
338
|
+
content: withOffsetNotice(content, offset, prompt, url, complete),
|
|
339
|
+
metadata: { url, offset, totalSize: content.length },
|
|
340
|
+
}
|
|
276
341
|
} catch (err) {
|
|
277
342
|
const message =
|
|
278
343
|
err instanceof Error && err.name === 'AbortError'
|