@qvac/harness 0.8.10 → 0.8.12

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.
@@ -5,9 +5,15 @@ import os from 'os';
5
5
  import path from 'path';
6
6
  import { fileURLToPath } from 'url';
7
7
  import defaultFetch from '#fetch';
8
+ import { errorMessage } from '../guards.js';
9
+ import { log } from '../log.js';
8
10
  const rangeFetch = defaultFetch;
9
11
  export const GGUF_HEADER_BYTES = 1_048_576;
10
12
  export const GGUF_HEADER_TIMEOUT_MS = 30_000;
13
+ export const GGUF_HEADER_ATTEMPTS = 3;
14
+ export const GGUF_STUB_MAX_BYTES = 33_554_432;
15
+ export const GGUF_STUB_TIMEOUT_MS = 60_000;
16
+ const MAX_ALIGNMENT = 1_048_576;
11
17
  const UINT8 = 0;
12
18
  const INT8 = 1;
13
19
  const UINT16 = 2;
@@ -48,34 +54,179 @@ function filePath(src) {
48
54
  }
49
55
  export function readGgufHeaderBytes(src, opts = {}) {
50
56
  const maxBytes = opts.maxBytes ?? GGUF_HEADER_BYTES;
57
+ const fetch = opts.fetch ?? rangeFetch;
51
58
  return isRemoteSource(src)
52
- ? fetchHead(src, maxBytes, opts.fetch ?? rangeFetch)
59
+ ? withDeadline(GGUF_HEADER_TIMEOUT_MS, (signal) => fetchRange(src, { start: 0, length: maxBytes, fetch, signal }))
53
60
  : readLocalHead(src, maxBytes);
54
61
  }
55
- async function fetchHead(src, maxBytes, fetch) {
56
- const controller = new AbortController();
57
- const timeout = setTimeout(() => controller.abort(undefined), GGUF_HEADER_TIMEOUT_MS);
58
- try {
59
- const response = await fetch(src, {
60
- headers: { Range: `bytes=0-${maxBytes - 1}` },
61
- signal: controller.signal
62
- });
63
- if (!response.ok) {
62
+ export function fetchGgufStub(src, opts = {}) {
63
+ const fetch = opts.fetch ?? rangeFetch;
64
+ const maxBytes = opts.maxBytes ?? GGUF_STUB_MAX_BYTES;
65
+ return withDeadline(GGUF_STUB_TIMEOUT_MS, (signal) => readStub(src, { fetch, maxBytes, signal }));
66
+ }
67
+ async function readStub(src, { fetch, maxBytes, signal }) {
68
+ let bytes = b4a.alloc(0);
69
+ let want = Math.min(GGUF_HEADER_BYTES, maxBytes);
70
+ for (;;) {
71
+ const start = bytes.byteLength;
72
+ const more = await fetchRange(src, { start, length: want - start, fetch, signal });
73
+ if (more === null) {
64
74
  return null;
65
75
  }
66
- const length = response.headers.get('content-length');
67
- if (length === null || !(Number(length) <= maxBytes)) {
76
+ bytes = b4a.concat([bytes, more]);
77
+ const dataOffset = ggufDataOffset(bytes);
78
+ if (dataOffset !== null) {
79
+ return padded(bytes, dataOffset);
80
+ }
81
+ if (more.byteLength < want - start || want >= maxBytes) {
68
82
  return null;
69
83
  }
70
- return new Uint8Array(await response.arrayBuffer()).subarray(0, maxBytes);
84
+ want = Math.min(want * 2, maxBytes);
71
85
  }
72
- catch {
86
+ }
87
+ export function ggufDataOffset(bytes) {
88
+ if (bytes.byteLength < 24 || b4a.toString(bytes.subarray(0, 4), 'latin1') !== 'GGUF') {
89
+ return null;
90
+ }
91
+ const c = {
92
+ view: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
93
+ bytes,
94
+ offset: 8
95
+ };
96
+ const tensors = readU64(c);
97
+ const alignment = skipMetadata(c, readU64(c));
98
+ if (alignment === null || !skipTensorInfos(c, tensors)) {
73
99
  return null;
74
100
  }
101
+ return Math.ceil(c.offset / alignment) * alignment;
102
+ }
103
+ function skipTensorInfos(c, count) {
104
+ for (let i = 0; i < count; i += 1) {
105
+ if (readString(c) === null || !has(c, 4)) {
106
+ return false;
107
+ }
108
+ const dims = readU32(c);
109
+ if (!has(c, dims * 8 + 12)) {
110
+ return false;
111
+ }
112
+ c.offset += dims * 8 + 12;
113
+ }
114
+ return true;
115
+ }
116
+ function skipMetadata(c, count) {
117
+ let alignment = 32;
118
+ for (let i = 0; i < count; i += 1) {
119
+ const key = readString(c);
120
+ if (key === null || !has(c, 4)) {
121
+ return null;
122
+ }
123
+ const value = readValue(c, readU32(c));
124
+ if (!value.ok) {
125
+ return null;
126
+ }
127
+ if (key === 'general.alignment') {
128
+ if (!isAlignment(value.num)) {
129
+ return null;
130
+ }
131
+ alignment = value.num;
132
+ }
133
+ }
134
+ return alignment;
135
+ }
136
+ function isAlignment(value) {
137
+ return (value !== undefined &&
138
+ Number.isInteger(value) &&
139
+ value > 0 &&
140
+ value <= MAX_ALIGNMENT &&
141
+ (value & (value - 1)) === 0);
142
+ }
143
+ function padded(bytes, length) {
144
+ if (length <= bytes.byteLength) {
145
+ return bytes.subarray(0, length);
146
+ }
147
+ const stub = b4a.alloc(length);
148
+ stub.set(bytes);
149
+ return stub;
150
+ }
151
+ async function withDeadline(ms, run) {
152
+ const controller = new AbortController();
153
+ const timeout = setTimeout(() => controller.abort(undefined), ms);
154
+ try {
155
+ return await run(controller.signal);
156
+ }
75
157
  finally {
76
158
  clearTimeout(timeout);
77
159
  }
78
160
  }
161
+ async function fetchRange(src, range) {
162
+ for (let attempt = 1; attempt <= GGUF_HEADER_ATTEMPTS; attempt++) {
163
+ const read = await requestRange(src, range);
164
+ if (read.kind === 'read') {
165
+ return read.bytes;
166
+ }
167
+ log.warn('gguf header read failed', { host: hostOf(src), attempt, cause: read.cause });
168
+ if (!read.transient || range.signal.aborted) {
169
+ return null;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+ async function requestRange(src, { start, length, fetch, signal }) {
175
+ let response;
176
+ try {
177
+ response = await fetch(src, {
178
+ headers: { Range: `bytes=${start}-${start + length - 1}` },
179
+ signal
180
+ });
181
+ }
182
+ catch (err) {
183
+ return { kind: 'failed', transient: true, cause: failureOf(err) };
184
+ }
185
+ const refused = refusedRange(response, { start, length });
186
+ if (refused) {
187
+ return refused;
188
+ }
189
+ try {
190
+ return {
191
+ kind: 'read',
192
+ bytes: new Uint8Array(await response.arrayBuffer()).subarray(0, length)
193
+ };
194
+ }
195
+ catch (err) {
196
+ return { kind: 'failed', transient: true, cause: failureOf(err) };
197
+ }
198
+ }
199
+ function refusedRange(response, { start, length }) {
200
+ if (!response.ok) {
201
+ return {
202
+ kind: 'failed',
203
+ transient: retryableStatus(response.status),
204
+ cause: `HTTP ${response.status}`
205
+ };
206
+ }
207
+ if (start > 0 && response.status !== 206) {
208
+ return { kind: 'failed', transient: false, cause: `HTTP ${response.status} for a range` };
209
+ }
210
+ const announced = response.headers.get('content-length');
211
+ return announced === null || !(Number(announced) <= length)
212
+ ? { kind: 'failed', transient: false, cause: `content-length ${announced ?? 'missing'}` }
213
+ : null;
214
+ }
215
+ function failureOf(err) {
216
+ const cause = err instanceof Error ? err.cause : undefined;
217
+ return cause === undefined ? errorMessage(err) : `${errorMessage(err)}: ${errorMessage(cause)}`;
218
+ }
219
+ function retryableStatus(status) {
220
+ return status === 408 || status === 429 || status >= 500;
221
+ }
222
+ function hostOf(src) {
223
+ try {
224
+ return new URL(src).host;
225
+ }
226
+ catch {
227
+ return '';
228
+ }
229
+ }
79
230
  async function readLocalHead(src, maxBytes) {
80
231
  const file = localSourcePath(src);
81
232
  if (file === null) {
@@ -28,13 +28,13 @@ const PRESET_RESOLVERS = [
28
28
  { prefix: 'Qwen3.5-4B-', resolve: qwen4BPreset }
29
29
  ];
30
30
  export function resolveLlmGenerationParams(modelName, reasoningEnabled, deviceDefault) {
31
+ const effective = reasoningEnabled ?? deviceDefault;
31
32
  const resolver = modelName
32
33
  ? PRESET_RESOLVERS.find((entry) => modelName.startsWith(entry.prefix))
33
34
  : undefined;
34
35
  if (resolver) {
35
- return resolver.resolve(reasoningEnabled);
36
+ return resolver.resolve(effective);
36
37
  }
37
- const effective = reasoningEnabled ?? deviceDefault;
38
38
  if (effective === undefined) {
39
39
  return undefined;
40
40
  }
@@ -10,7 +10,7 @@ import { DEFAULT_EMBED_BATCH_SIZE } from './embed-config.js';
10
10
  import { log } from '../log.js';
11
11
  import { RUNAWAY_STOP_SEQUENCES } from '../helpers/control-tokens.js';
12
12
  import { raceTimeout } from '../helpers/race-timeout.js';
13
- import { resolveModelSrc } from './model-source.js';
13
+ import { resolveModelSrc, resolveProjectionSrc } from './model-source.js';
14
14
  import { errorMessage } from '../guards.js';
15
15
  import { AbortedError } from '../helpers/race-abort.js';
16
16
  export function createLoadTracker() {
@@ -365,7 +365,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
365
365
  const resolved = resolveLoadOptions(opts, deviceConfig);
366
366
  const tier = defaultContextSize(modelSrc, customContextLength(model));
367
367
  const projectionModelSrc = resolved.projectionModel
368
- ? await resolveModelSrc(sdk, resolved.projectionModel)
368
+ ? await resolveProjectionSrc(sdk, resolved.projectionModel)
369
369
  : undefined;
370
370
  const mainGpu = deviceConfig.device !== 'cpu' && deviceConfig.mainGpu
371
371
  ? await deviceConfig.mainGpu()
@@ -4,3 +4,4 @@ import type { ModelSrc } from './context.ts';
4
4
  export type ModelRegistrySdk = Pick<typeof QvacSdk, 'modelRegistrySearch'>;
5
5
  export type ModelAddon = ModelRegistryEntryAddon;
6
6
  export declare function resolveModelSrc(sdk: ModelRegistrySdk, model: string, addon?: ModelAddon): Promise<ModelSrc>;
7
+ export declare function resolveProjectionSrc(sdk: ModelRegistrySdk, model: string): Promise<ModelSrc>;
@@ -1,7 +1,8 @@
1
1
  import { HarnessError } from '../errors.js';
2
- import { audioGenModelByName, curatedModelAsset, customModelSrc } from './model-catalog.js';
2
+ import { audioGenModelByName, curatedListables, curatedModelAsset, customModelSrc } from './model-catalog.js';
3
+ const SOURCE_PATTERN = /^(\/|~|\.|file:|https?:|registry:|pear:|hyper:)/;
3
4
  export async function resolveModelSrc(sdk, model, addon = 'llm') {
4
- if (/^(\/|~|\.|file:|https?:|registry:|pear:|hyper:)/.test(model)) {
5
+ if (SOURCE_PATTERN.test(model)) {
5
6
  return model;
6
7
  }
7
8
  const custom = customModelSrc(model, addon);
@@ -19,9 +20,25 @@ export async function resolveModelSrc(sdk, model, addon = 'llm') {
19
20
  if (asset) {
20
21
  return asset;
21
22
  }
22
- const [entry] = await sdk.modelRegistrySearch({ filter: model, addon });
23
+ return await registryMatch(sdk, { model, addon, projection: false });
24
+ }
25
+ export async function resolveProjectionSrc(sdk, model) {
26
+ if (SOURCE_PATTERN.test(model)) {
27
+ return model;
28
+ }
29
+ return await registryMatch(sdk, { model, addon: 'llm', projection: true });
30
+ }
31
+ async function registryMatch(sdk, { model, addon, projection }) {
32
+ const entries = await sdk.modelRegistrySearch({ filter: model, addon });
33
+ const entry = bestMatch(entries.filter((candidate) => /mmproj/i.test(candidate.name) === projection), model);
23
34
  if (!entry) {
24
35
  throw new HarnessError('MODEL_NOT_IN_REGISTRY', [model, addon]);
25
36
  }
26
37
  return { ...entry, src: `registry://${entry.registrySource}/${entry.registryPath}` };
27
38
  }
39
+ function bestMatch(entries, model) {
40
+ const curated = new Set(curatedListables().map((listable) => listable.asset.registryPath));
41
+ return (entries.find((entry) => entry.name === model) ??
42
+ entries.find((entry) => curated.has(entry.registryPath)) ??
43
+ entries[0]);
44
+ }
@@ -11,8 +11,8 @@ export const OBSIDIAN_VAULT_SETUP_REQUIRED = 'Obsidian vault file mode is not se
11
11
  'to switch tools.';
12
12
  export const OBSIDIAN_VAULT_MODE_NOTE = [
13
13
  'Runtime note — Obsidian vault file mode is active (a vault folder is configured):',
14
- '- Run vault commands through the `exec` tool, e.g. `obsidian vault info=path`, `obsidian search query="..."`, `obsidian read path="Folder/Note.md"`.',
15
- '- Start with `obsidian vault info=path` to confirm the configured vault.',
14
+ '- Run vault commands through the `exec` tool, e.g. `obsidian files`, `obsidian search query="..."`, `obsidian read path="Folder/Note.md"`.',
15
+ '- To list what is in the vault, run `obsidian files`. `read` takes a note name or a path inside the vault, never the vault folder.',
16
16
  '- `obsidian vaults` returns only the configured vault folder, not every vault in the Obsidian app.',
17
17
  '- App-only actions (open in app, plugin/sync/theme commands) are unavailable in this mode; they require the official Obsidian CLI connected to the running app.'
18
18
  ].join('\n');
@@ -2,6 +2,14 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { HarnessError } from '../../../errors.js';
4
4
  import { dailyCandidates, ensureWithinRoot, FRONTMATTER_RE, getArg, listFolders, listMarkdownFiles, parseFrontmatter, readFileText, resolveNotePath, todayStamp } from './vault-paths.js';
5
+ function statOrNull(p) {
6
+ try {
7
+ return fs.statSync(p);
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
5
13
  export function handleVault(vaultPath) {
6
14
  return JSON.stringify({ name: path.basename(vaultPath), path: vaultPath });
7
15
  }
@@ -17,9 +25,14 @@ export function handleVaults(vaultPath) {
17
25
  }
18
26
  export function handleRead(vaultPath, args) {
19
27
  const notePath = resolveNotePath(vaultPath, args);
20
- if (!notePath || !fs.existsSync(notePath)) {
28
+ const stat = notePath ? statOrNull(notePath) : null;
29
+ if (!notePath || !stat) {
21
30
  throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
22
31
  }
32
+ if (stat.isDirectory()) {
33
+ const folder = path.relative(path.resolve(vaultPath), notePath).split(path.sep).join('/');
34
+ throw new HarnessError('OBSIDIAN_PATH_IS_FOLDER', [folder]);
35
+ }
23
36
  return readFileText(notePath);
24
37
  }
25
38
  export function handleFiles(vaultPath, args) {
@@ -69,11 +82,7 @@ export function handleSearch(vaultPath, args) {
69
82
  return matches.join('\n') + truncated;
70
83
  }
71
84
  export function handleProperties(vaultPath, args) {
72
- const notePath = resolveNotePath(vaultPath, args);
73
- if (!notePath || !fs.existsSync(notePath)) {
74
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
75
- }
76
- return JSON.stringify(parseFrontmatter(readFileText(notePath)), null, 2);
85
+ return JSON.stringify(parseFrontmatter(handleRead(vaultPath, args)), null, 2);
77
86
  }
78
87
  function countTags(tagCounts, content) {
79
88
  for (const match of content.matchAll(/#([a-zA-Z0-9_/-]+)/g)) {
@@ -98,20 +107,12 @@ export function handleTags(vaultPath) {
98
107
  return sorted.map(([tag, count]) => `#${tag} (${count})`).join('\n') || '(no tags)';
99
108
  }
100
109
  export function handleWordcount(vaultPath, args) {
101
- const notePath = resolveNotePath(vaultPath, args);
102
- if (!notePath || !fs.existsSync(notePath)) {
103
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
104
- }
105
- const body = readFileText(notePath).replace(FRONTMATTER_RE, '').trim();
110
+ const body = handleRead(vaultPath, args).replace(FRONTMATTER_RE, '').trim();
106
111
  const words = body.split(/\s+/).filter(Boolean).length;
107
112
  return `${words} words`;
108
113
  }
109
114
  export function handleOutline(vaultPath, args) {
110
- const notePath = resolveNotePath(vaultPath, args);
111
- if (!notePath || !fs.existsSync(notePath)) {
112
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
113
- }
114
- const headings = readFileText(notePath)
115
+ const headings = handleRead(vaultPath, args)
115
116
  .split('\n')
116
117
  .filter((line) => /^#{1,6}\s/.test(line));
117
118
  return headings.join('\n') || '(no headings)';
@@ -14,6 +14,7 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
14
14
  return {
15
15
  name: 'http_request',
16
16
  toolset: 'http-request',
17
+ deferLoading: true,
17
18
  description: 'Make an outbound HTTP or HTTPS request and return the response status and body (truncated) as text. Authorization/Cookie headers are stripped before sending. Stored skill credentials are attached automatically for their allow-listed hosts; `auth` is only needed to force a specific credential key. For APIs and text responses only: a URL that serves a file — PDF, .docx, .xlsx, an image, any binary — comes back as truncated garbage here. Use web_fetch for those; it downloads and attaches the file.',
18
19
  parameters: {
19
20
  type: 'object',
@@ -35,6 +35,7 @@ export function createMcpCallTool({ fetch: fetchImpl, credentialStore, credentia
35
35
  return {
36
36
  name: MCP_CALL_TOOL_NAME,
37
37
  toolset: 'mcp-call',
38
+ deferLoading: true,
38
39
  description: 'Make a JSON-RPC 2.0 call to a Model Context Protocol (MCP) server. Load the matching skill first — it documents the server tool names and their args. Pass a server tool name as `method` and its args as `params`; the JSON-RPC envelope, session handshake, and bearer auth are handled for you (the stored credential for the host is attached automatically, so no `auth` is needed).',
39
40
  parameters: {
40
41
  type: 'object',
@@ -11,6 +11,8 @@ const FIRST_SHEET = /^sheet ?1$/i;
11
11
  const NEW_DECK_HINT = '; a new deck has only the slides its addSlide ops make, slides count from 0, and an op on a slide goes after the addSlide that makes it';
12
12
  const SHAPE_ROLES = new Set(['title', 'subtitle', 'body']);
13
13
  const HOISTED = ['attachmentId', 'output'];
14
+ const BLOCK_POSITIONED = new Set(['insertParagraphs', 'addTable', 'addImage', 'addChart']);
15
+ const FILE_NAME = /\.\w+$/;
14
16
  const WHERE_IDS_ARE = 'copy the id from the [Attached file "…" — attachmentId: …] line or an earlier tool result';
15
17
  function isObject(value) {
16
18
  return isRecord(value) && !Array.isArray(value);
@@ -27,6 +29,12 @@ export function shapeFor(deck, op) {
27
29
  const found = deck.read()[slide]?.shapes.find((entry) => entry.name.toLowerCase() === wanted);
28
30
  return found && found.id !== null ? { ...op, shape: found.id } : op;
29
31
  }
32
+ function positionFor(doc, op, created) {
33
+ if (!created || !BLOCK_POSITIONED.has(String(op.op)) || typeof op.at !== 'number') {
34
+ return op;
35
+ }
36
+ return op.at > doc.blockCount ? { ...op, at: doc.blockCount } : op;
37
+ }
30
38
  function newDeckHint(err, created) {
31
39
  return created && err instanceof DocsError && err.code === 'SLIDE_NOT_FOUND' ? NEW_DECK_HINT : '';
32
40
  }
@@ -69,6 +77,7 @@ function readWorkbook(book) {
69
77
  const PPTX_FORMAT = {
70
78
  name: 'pptx',
71
79
  noun: 'PowerPoint deck',
80
+ stem: 'presentation',
72
81
  ops: PPTX_OPS,
73
82
  createKeys: ['size', 'title', 'fonts', 'colors'],
74
83
  open: (bytes) => pptx.open(bytes),
@@ -81,16 +90,19 @@ const PPTX_FORMAT = {
81
90
  const DOCX_FORMAT = {
82
91
  name: 'docx',
83
92
  noun: 'Word document',
93
+ stem: 'document',
84
94
  ops: DOCX_OPS,
85
95
  createKeys: ['title', 'page', 'size', 'fonts'],
86
96
  open: (bytes) => docx.open(bytes),
87
97
  create: (options) => docx.create(options),
88
98
  read: (doc) => doc.read(),
89
- count: (doc) => ({ blocks: doc.blockCount })
99
+ count: (doc) => ({ blocks: doc.blockCount }),
100
+ prepare: (doc, op, created) => positionFor(doc, op, created)
90
101
  };
91
102
  const XLSX_FORMAT = {
92
103
  name: 'xlsx',
93
104
  noun: 'Excel workbook',
105
+ stem: 'workbook',
94
106
  ops: XLSX_OPS,
95
107
  createKeys: ['sheets', 'title'],
96
108
  open: (bytes) => xlsx.open(bytes),
@@ -125,11 +137,21 @@ export function normalizeArgs(args) {
125
137
  lifted.create = options;
126
138
  continue;
127
139
  }
140
+ if (rest.op === 'output') {
141
+ const { op: _output, ...named } = rest;
142
+ lifted.output ??= Object.values(named).find((value) => typeof value === 'string' && FILE_NAME.test(value));
143
+ continue;
144
+ }
128
145
  ops.push(rest);
129
146
  }
130
- lifted.ops = ops;
147
+ lifted.ops = lifted.attachmentId === undefined ? ops.map(insertedWhereAsked) : ops;
131
148
  return lifted;
132
149
  }
150
+ function insertedWhereAsked(op) {
151
+ return isObject(op) && op.op === 'appendParagraphs' && op.at !== undefined
152
+ ? { ...op, op: 'insertParagraphs' }
153
+ : op;
154
+ }
133
155
  function parseOp(format, op, i) {
134
156
  if (!isObject(op) || typeof op.op !== 'string') {
135
157
  return `ops[${i}] must be { op, ...args }`;
@@ -236,12 +258,24 @@ export function revisedName(format, fileName) {
236
258
  }
237
259
  return `${revised[1]}_revised-${Number(revised[2] ?? 1) + 1}.${format}`;
238
260
  }
239
- function outputFor(format, output, input) {
240
- if (!input)
241
- return output;
242
- if (output && output.toLowerCase() !== input.toLowerCase())
261
+ function newFileName(format, title) {
262
+ const stem = typeof title === 'string'
263
+ ? title
264
+ .toLowerCase()
265
+ .replace(/[^a-z0-9]+/g, '_')
266
+ .replace(/^_+|_+$/g, '')
267
+ .slice(0, 48)
268
+ : '';
269
+ return `${stem || format.stem}.${format.name}`;
270
+ }
271
+ function outputFor(format, { output, create }, input) {
272
+ if (!input) {
273
+ return output ?? newFileName(format, create?.title);
274
+ }
275
+ if (output && output.toLowerCase() !== input.toLowerCase()) {
243
276
  return output;
244
- return revisedName(format, input);
277
+ }
278
+ return revisedName(format.name, input);
245
279
  }
246
280
  async function imageId(ctx, id) {
247
281
  const found = await ctx.fetchAttachment?.({ attachmentId: id, meta: true, signal: ctx.signal });
@@ -299,9 +333,6 @@ async function stagedImages(request, ctx) {
299
333
  return images;
300
334
  }
301
335
  function saveError({ format, document, output }, ctx) {
302
- if (!output) {
303
- return `the ops changed the ${format.noun}; name the file in output`;
304
- }
305
336
  if (!output.toLowerCase().endsWith(`.${format.name}`)) {
306
337
  return `output must end in .${format.name}, got "${output}"`;
307
338
  }
@@ -313,7 +344,7 @@ function saveError({ format, document, output }, ctx) {
313
344
  }
314
345
  async function attachOutput(job, ctx) {
315
346
  const refused = saveError(job, ctx);
316
- if (refused || !job.output || !ctx.attach) {
347
+ if (refused || !ctx.attach) {
317
348
  return { error: refused ?? 'nothing to save' };
318
349
  }
319
350
  const { output, document } = job;
@@ -453,17 +484,18 @@ async function execute(format, args, ctx) {
453
484
  if ('error' in results) {
454
485
  return results;
455
486
  }
456
- if (!document.changed && request.attachmentId !== undefined) {
487
+ const onlyQueries = request.ops.every(({ spec }) => spec.query);
488
+ if (onlyQueries || (!document.changed && request.attachmentId !== undefined)) {
457
489
  return { results };
458
490
  }
459
- const output = outputFor(format.name, request.output, fileName);
491
+ const output = outputFor(format, request, fileName);
460
492
  const saved = await attachOutput({ format, document, output }, ctx);
461
493
  if ('error' in saved) {
462
494
  return saved;
463
495
  }
464
496
  const { attachment, repeated } = saved;
465
497
  const counts = format.count(document);
466
- const renamed = output !== request.output
498
+ const renamed = fileName !== null && output !== request.output
467
499
  ? `Saved as ${output}, so the attached ${fileName} keeps its own name. `
468
500
  : '';
469
501
  const unplaced = !!ctx.turnImages?.length && !images.size;
@@ -38,6 +38,10 @@ export interface ReadDocuments {
38
38
  readonly documents: readonly ReadDocument[];
39
39
  }
40
40
  export declare function pagesLabel(count: number): string;
41
- export declare function readDocs(opened: readonly Opened[]): ReadDocument | ReadDocuments;
41
+ export type ShownPage = (fileName: string, page: number) => boolean;
42
+ export declare function textless({ doc }: Opened): boolean;
43
+ export declare function everyPageShown({ source, doc }: Opened, isShown: ShownPage): boolean;
44
+ export declare function shownNote({ source, doc }: Opened): string;
45
+ export declare function readDocs(opened: readonly Opened[], isShown: ShownPage): ReadDocument | ReadDocuments;
42
46
  export declare function build(pdfium: Pdfium, request: PdfRequest, opened: readonly Opened[]): Built | string;
43
47
  export {};
@@ -26,13 +26,38 @@ function describeField(field) {
26
26
  readOnly: field.readOnly || undefined
27
27
  };
28
28
  }
29
- function scannedNote(scanned) {
29
+ const SHOWN = {
30
+ one: 'shown to you as an image in the user message, so read its content from that image',
31
+ many: 'shown to you as images in the user message, so read their content from those images'
32
+ };
33
+ function scannedNote(scanned, shown) {
30
34
  if (!scanned.length)
31
35
  return undefined;
32
36
  const one = scanned.length === 1;
33
- return `${one ? 'page' : 'pages'} ${scanned.join(', ')} ${one ? 'has' : 'have'} no text layer: ${one ? 'it is a scanned image' : 'they are scanned images'}, and there is no OCR here`;
37
+ const what = one ? 'it is a scanned image' : 'they are scanned images';
38
+ const where = shown ? SHOWN[one ? 'one' : 'many'] : 'and there is no OCR here';
39
+ return `${one ? 'page' : 'pages'} ${scanned.join(', ')} ${one ? 'has' : 'have'} no text layer: ${what}, ${where}`;
34
40
  }
35
- function readOne({ source, doc }, budget) {
41
+ export function textless({ doc }) {
42
+ for (const page of doc.textPages()) {
43
+ if (page.text.trim())
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+ export function everyPageShown({ source, doc }, isShown) {
49
+ for (let page = 1; page <= doc.pageCount(); page++) {
50
+ if (!isShown(source.fileName, page))
51
+ return false;
52
+ }
53
+ return true;
54
+ }
55
+ export function shownNote({ source, doc }) {
56
+ const one = doc.pageCount() === 1;
57
+ const what = one ? 'it is a scanned image' : 'its pages are scanned images';
58
+ return `${source.fileName} has no text layer: ${what}, ${SHOWN[one ? 'one' : 'many']}`;
59
+ }
60
+ function readOne({ source, doc }, budget, isShown) {
36
61
  const pages = [];
37
62
  const scanned = [];
38
63
  let truncated = false;
@@ -54,13 +79,13 @@ function readOne({ source, doc }, budget) {
54
79
  pageCount: doc.pageCount(),
55
80
  pages,
56
81
  fields: doc.fields().map(describeField),
57
- note: scannedNote(scanned),
82
+ note: scannedNote(scanned, scanned.every((page) => isShown(source.fileName, page))),
58
83
  truncated: truncated || undefined
59
84
  };
60
85
  }
61
- export function readDocs(opened) {
86
+ export function readDocs(opened, isShown) {
62
87
  const budget = { chars: READ_TEXT_LIMIT };
63
- const documents = opened.map((one) => readOne(one, budget));
88
+ const documents = opened.map((one) => readOne(one, budget, isShown));
64
89
  const [only] = documents;
65
90
  return documents.length === 1 && only ? only : { documents };
66
91
  }
@@ -1,6 +1,6 @@
1
1
  import { errorCode, errorMessage } from '../guards.js';
2
2
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './exec/adapters/python/output-policy.js';
3
- import { build, pagesLabel, readDocs } from './pdf/build.js';
3
+ import { build, pagesLabel, everyPageShown, readDocs, shownNote, textless } from './pdf/build.js';
4
4
  import { placeImages } from './pdf/images.js';
5
5
  import { PAGE_SIZES, parseRequest, PDF_ACTIONS, WHERE_IDS_ARE } from './pdf/request.js';
6
6
  export { parsePages, parseRequest } from './pdf/request.js';
@@ -201,6 +201,13 @@ function lockOrUnlock(pdfium, request, sources) {
201
201
  }
202
202
  return { ...request, action: 'encrypt', ownerPassword: undefined, permissions: undefined };
203
203
  }
204
+ function renderedPageName(fileName, page) {
205
+ return `${fileName}.p${page - 1}.jpg`.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(-40);
206
+ }
207
+ function shownPages(ctx) {
208
+ const names = (ctx.turnImages ?? []).map((image) => image.path.split(/[\\/]/).pop()?.slice(33));
209
+ return (fileName, page) => names.includes(renderedPageName(fileName, page));
210
+ }
204
211
  async function run(pdfium, asked, ctx) {
205
212
  if (asked.action === 'create') {
206
213
  const placed = await placeImages(asked, ctx);
@@ -217,7 +224,14 @@ async function run(pdfium, asked, ctx) {
217
224
  return { error };
218
225
  }
219
226
  if (request.action === 'read') {
220
- return readDocs(opened);
227
+ return readDocs(opened, shownPages(ctx));
228
+ }
229
+ const [only] = opened;
230
+ if (request.action === 'text' &&
231
+ only &&
232
+ textless(only) &&
233
+ everyPageShown(only, shownPages(ctx))) {
234
+ return { note: shownNote(only) };
221
235
  }
222
236
  return await deliver({ pdfium, request, opened }, ctx);
223
237
  }
@@ -280,6 +294,7 @@ export function createPdfTool(load = loadPdfium) {
280
294
  name: 'pdf',
281
295
  toolset: null,
282
296
  skillGated: true,
297
+ ungatedFor: ['tiny', 'low'],
283
298
  description: DESCRIPTION,
284
299
  parameters: PARAMETERS,
285
300
  effect: () => 'read',