@qvac/harness 0.8.11 → 0.8.13

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 (65) hide show
  1. package/CHANGELOG.md +139 -1
  2. package/dist-lib/index.d.ts +1 -0
  3. package/dist-lib/index.js +16 -8
  4. package/dist-lib/lib/capabilities/completion.d.ts +9 -1
  5. package/dist-lib/lib/capabilities/completion.js +87 -25
  6. package/dist-lib/lib/capabilities/preview-model-source.d.ts +7 -1
  7. package/dist-lib/lib/capabilities/preview-model-source.js +80 -22
  8. package/dist-lib/lib/capabilities/tool-search.d.ts +4 -0
  9. package/dist-lib/lib/capabilities/tool-search.js +9 -0
  10. package/dist-lib/lib/capabilities/tool-selection.d.ts +3 -1
  11. package/dist-lib/lib/capabilities/tool-selection.js +3 -2
  12. package/dist-lib/lib/connect.js +3 -2
  13. package/dist-lib/lib/contract-types.d.ts +1 -0
  14. package/dist-lib/lib/errors.d.ts +4 -0
  15. package/dist-lib/lib/errors.js +6 -0
  16. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  17. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  18. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  19. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  20. package/dist-lib/lib/models/gguf-header.d.ts +11 -0
  21. package/dist-lib/lib/models/gguf-header.js +203 -15
  22. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  23. package/dist-lib/lib/models/kv-cache.js +8 -0
  24. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  25. package/dist-lib/lib/models/llm-presets.js +2 -2
  26. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  27. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  28. package/dist-lib/lib/models/model-pool.js +22 -10
  29. package/dist-lib/lib/models/model-source.d.ts +1 -0
  30. package/dist-lib/lib/models/model-source.js +20 -3
  31. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  32. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  33. package/dist-lib/lib/prompt.d.ts +2 -1
  34. package/dist-lib/lib/prompt.js +12 -12
  35. package/dist-lib/lib/serve.js +3 -2
  36. package/dist-lib/lib/tools/edit-image.js +4 -3
  37. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  38. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  39. package/dist-lib/lib/tools/exec/obsidian/guidance.js +2 -2
  40. package/dist-lib/lib/tools/exec/obsidian/vault-read.js +17 -16
  41. package/dist-lib/lib/tools/generate-image.js +4 -3
  42. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  43. package/dist-lib/lib/tools/http-request/request.js +2 -1
  44. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  45. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  46. package/dist-lib/lib/tools/http-request.js +13 -6
  47. package/dist-lib/lib/tools/mcp-call.js +1 -0
  48. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  49. package/dist-lib/lib/tools/office/ops.js +5 -1
  50. package/dist-lib/lib/tools/office.d.ts +1 -0
  51. package/dist-lib/lib/tools/office.js +197 -35
  52. package/dist-lib/lib/tools/operations/compile.js +4 -4
  53. package/dist-lib/lib/tools/pdf/build.d.ts +5 -1
  54. package/dist-lib/lib/tools/pdf/build.js +31 -6
  55. package/dist-lib/lib/tools/pdf.js +17 -2
  56. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  57. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  58. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  59. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  60. package/dist-lib/schema/harness.js +2 -1
  61. package/dist-lib/spec/hrpc/messages.js +8 -5
  62. package/dist-lib/spec/hyperschema/index.js +8 -5
  63. package/dist-lib/spec/hyperschema/schema.json +6 -1
  64. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  65. package/package.json +5 -5
@@ -3,9 +3,9 @@ import { AbortController } from 'bare-abort-controller';
3
3
  import { lookupHost } from '../dns-lookup.js';
4
4
  import { READ_METHODS } from './http-methods.js';
5
5
  import { encodeDeclaredFields } from './http-request/encode-fields.js';
6
- import { truncateResponseBody } from './http-request/truncate-response.js';
6
+ import { capResponseBody } from './http-request/truncate-response.js';
7
7
  import { AbortedError } from '../helpers/race-abort.js';
8
- import { applyQuery, buildHeaders, contentTypeOf, encodeBody, isRedirectStatus, parseJsonBody, parseObjectArg, TIMEOUT_MS } from './http-request/request.js';
8
+ import { applyQuery, buildHeaders, contentTypeOf, encodeBody, isRedirectStatus, parseJsonBody, IDLE_TIMEOUT_MS, parseObjectArg, TIMEOUT_MS } from './http-request/request.js';
9
9
  import { parseAuth, resolveBearerHeader, resolveRedirectBearerHeader } from './skills/auth-resolver.js';
10
10
  import { recordCredentialHealth } from './skills/credential-health.js';
11
11
  import { resolveOutboundUrl } from './url-guard.js';
@@ -14,7 +14,8 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
14
14
  return {
15
15
  name: 'http_request',
16
16
  toolset: 'http-request',
17
- 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.',
17
+ deferLoading: true,
18
+ description: 'Make an outbound HTTP or HTTPS request and return the response status and body as text. A body too large for the context window is cut, and `truncated` then says what share of it was read. 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',
20
21
  properties: {
@@ -133,7 +134,8 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
133
134
  body,
134
135
  signal: controller.signal,
135
136
  redirect: 'manual',
136
- validatedAddresses
137
+ validatedAddresses,
138
+ idleTimeoutMs: IDLE_TIMEOUT_MS
137
139
  });
138
140
  if (credentialKey) {
139
141
  recordCredentialHealth(credentialKey, response.status, ctx?.agentId);
@@ -174,14 +176,19 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
174
176
  credentialKey = next.credentialKey;
175
177
  }
176
178
  const text = await response.text();
179
+ if (ctx?.uncappedResponse) {
180
+ return { status: response.status, body: text };
181
+ }
177
182
  return {
178
183
  status: response.status,
179
- body: ctx?.uncappedResponse ? text : truncateResponseBody(text)
184
+ ...capResponseBody(text, ctx)
180
185
  };
181
186
  }
182
187
  catch (err) {
183
188
  const error = err instanceof Error ? err : new Error(String(err));
184
- const timedOut = error.name === 'AbortError' || error instanceof AbortedError;
189
+ const timedOut = error.name === 'AbortError' ||
190
+ error.name === 'TimeoutError' ||
191
+ error instanceof AbortedError;
185
192
  return {
186
193
  error: timedOut ? 'request timed out' : `request failed: ${error.message}`,
187
194
  code: timedOut ? 'timeout' : 'transport'
@@ -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',
@@ -4,6 +4,7 @@ export interface OpSpec {
4
4
  readonly inches?: boolean;
5
5
  readonly query?: boolean;
6
6
  readonly aliases?: Readonly<Record<string, string>>;
7
+ readonly skipsLooks?: boolean;
7
8
  }
8
9
  export declare const PPTX_OPS: Readonly<Record<string, OpSpec>>;
9
10
  export declare const DOCX_OPS: Readonly<Record<string, OpSpec>>;
@@ -7,7 +7,11 @@ export const PPTX_OPS = {
7
7
  setText: { slots: [['slide', 'shape'], 'text'] },
8
8
  setCellText: { slots: [['slide', 'shape', 'row', 'column'], 'text'] },
9
9
  setStyle: { slots: [['slide', 'shape'], 'style', ['paragraph']] },
10
- addSlide: { slots: [['like', 'layout', 'at', 'title', 'body', 'image']] },
10
+ addSlide: {
11
+ slots: [['like', 'layout', 'at', 'title', 'body', 'image']],
12
+ aliases: { subtitle: 'body' },
13
+ skipsLooks: true
14
+ },
11
15
  addPicture: { slots: ['slide', 'image', [...BOX, 'name', 'description']], inches: true },
12
16
  addTextBox: { slots: ['slide', [...BOX, 'text', 'style', 'fill', 'name']], inches: true },
13
17
  addTable: { slots: ['slide', [...BOX, 'rows', 'header', 'name']], inches: true },
@@ -4,6 +4,7 @@ type Deck = ReturnType<typeof pptx.open>;
4
4
  type Workbook = ReturnType<typeof xlsx.open>;
5
5
  type FormatName = 'pptx' | 'docx' | 'xlsx';
6
6
  type Args = Record<string, unknown>;
7
+ export declare function bodyLines(op: Args): Args;
7
8
  export declare function shapeFor(deck: Deck, op: Args): Args;
8
9
  export declare function sheetFor(book: Workbook, op: Args, created: boolean): Args;
9
10
  export declare function normalizeArgs(args: Args): Args;
@@ -2,7 +2,7 @@ import b4a from 'b4a';
2
2
  import { HarnessError } from '../errors.js';
3
3
  import { errorMessage, isRecord } from '../guards.js';
4
4
  import { DocsError, docx, pptx, units, xlsx } from '../office/engine/index.js';
5
- import { stageInputs } from './exec/adapters/python/attachments.js';
5
+ import { stageInputs, uploadsAvailable } from './exec/adapters/python/attachments.js';
6
6
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './exec/adapters/python/output-policy.js';
7
7
  import { DOCX_OPS, opArguments, opKeys, PPTX_OPS, withAliases, XLSX_OPS } from './office/ops.js';
8
8
  const READ_CELL_LIMIT = 10_000;
@@ -11,10 +11,27 @@ 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);
17
19
  }
20
+ const LOOK_KEY = /colou?r|background|^bg|font|style|theme/i;
21
+ function isLook(ops, key, value) {
22
+ return value === null || (!(key in ops) && LOOK_KEY.test(key));
23
+ }
24
+ const TYPED_BULLET = /^\s*[•◦▪●]\s+/;
25
+ export function bodyLines(op) {
26
+ const items = typeof op.body === 'string' ? [op.body] : op.body;
27
+ if (op.op !== 'addSlide' || !Array.isArray(items)) {
28
+ return op;
29
+ }
30
+ const body = items.flatMap((item) => typeof item === 'string'
31
+ ? item.split('\n').map((line) => line.replace(TYPED_BULLET, ''))
32
+ : [item]);
33
+ return { ...op, body };
34
+ }
18
35
  export function shapeFor(deck, op) {
19
36
  const { shape, slide } = op;
20
37
  if (typeof shape !== 'string' || SHAPE_ROLES.has(shape) || typeof slide !== 'number') {
@@ -27,6 +44,12 @@ export function shapeFor(deck, op) {
27
44
  const found = deck.read()[slide]?.shapes.find((entry) => entry.name.toLowerCase() === wanted);
28
45
  return found && found.id !== null ? { ...op, shape: found.id } : op;
29
46
  }
47
+ function positionFor(doc, op, created) {
48
+ if (!created || !BLOCK_POSITIONED.has(String(op.op)) || typeof op.at !== 'number') {
49
+ return op;
50
+ }
51
+ return op.at > doc.blockCount ? { ...op, at: doc.blockCount } : op;
52
+ }
30
53
  function newDeckHint(err, created) {
31
54
  return created && err instanceof DocsError && err.code === 'SLIDE_NOT_FOUND' ? NEW_DECK_HINT : '';
32
55
  }
@@ -69,28 +92,34 @@ function readWorkbook(book) {
69
92
  const PPTX_FORMAT = {
70
93
  name: 'pptx',
71
94
  noun: 'PowerPoint deck',
95
+ stem: 'presentation',
72
96
  ops: PPTX_OPS,
73
97
  createKeys: ['size', 'title', 'fonts', 'colors'],
98
+ looks: ['fonts', 'colors'],
74
99
  open: (bytes) => pptx.open(bytes),
75
100
  create: (options) => pptx.create(options),
76
101
  read: (deck) => deck.read(),
77
102
  count: (deck) => ({ slides: deck.slideCount }),
78
- prepare: (deck, op) => shapeFor(deck, op),
103
+ prepare: (deck, op) => shapeFor(deck, bodyLines(op)),
104
+ retry: withoutLayout,
79
105
  hint: newDeckHint
80
106
  };
81
107
  const DOCX_FORMAT = {
82
108
  name: 'docx',
83
109
  noun: 'Word document',
110
+ stem: 'document',
84
111
  ops: DOCX_OPS,
85
112
  createKeys: ['title', 'page', 'size', 'fonts'],
86
113
  open: (bytes) => docx.open(bytes),
87
114
  create: (options) => docx.create(options),
88
115
  read: (doc) => doc.read(),
89
- count: (doc) => ({ blocks: doc.blockCount })
116
+ count: (doc) => ({ blocks: doc.blockCount }),
117
+ prepare: (doc, op, created) => positionFor(doc, op, created)
90
118
  };
91
119
  const XLSX_FORMAT = {
92
120
  name: 'xlsx',
93
121
  noun: 'Excel workbook',
122
+ stem: 'workbook',
94
123
  ops: XLSX_OPS,
95
124
  createKeys: ['sheets', 'title'],
96
125
  open: (bytes) => xlsx.open(bytes),
@@ -125,11 +154,21 @@ export function normalizeArgs(args) {
125
154
  lifted.create = options;
126
155
  continue;
127
156
  }
157
+ if (rest.op === 'output') {
158
+ const { op: _output, ...named } = rest;
159
+ lifted.output ??= Object.values(named).find((value) => typeof value === 'string' && FILE_NAME.test(value));
160
+ continue;
161
+ }
128
162
  ops.push(rest);
129
163
  }
130
- lifted.ops = ops;
164
+ lifted.ops = lifted.attachmentId === undefined ? ops.map(insertedWhereAsked) : ops;
131
165
  return lifted;
132
166
  }
167
+ function insertedWhereAsked(op) {
168
+ return isObject(op) && op.op === 'appendParagraphs' && op.at !== undefined
169
+ ? { ...op, op: 'insertParagraphs' }
170
+ : op;
171
+ }
133
172
  function parseOp(format, op, i) {
134
173
  if (!isObject(op) || typeof op.op !== 'string') {
135
174
  return `ops[${i}] must be { op, ...args }`;
@@ -139,9 +178,16 @@ function parseOp(format, op, i) {
139
178
  return `ops[${i}]: unknown op "${op.op}"; ops are ${Object.keys(format.ops).join(', ')}`;
140
179
  }
141
180
  const keys = opKeys(spec);
142
- const unknown = Object.keys(op).filter((key) => key !== 'op' && !keys.includes(key));
181
+ const extra = Object.keys(op).filter((key) => key !== 'op' && !keys.includes(key));
182
+ const skippable = spec.skipsLooks ? extra.filter((key) => isLook(format.ops, key, op[key])) : [];
183
+ const unknown = extra.filter((key) => !skippable.includes(key));
143
184
  if (!unknown.length) {
144
- return { name: op.op, spec, args: withAliases(spec, op) };
185
+ const kept = Object.fromEntries(Object.entries(op).filter(([key]) => !skippable.includes(key)));
186
+ const shadowed = Object.entries(spec.aliases ?? {})
187
+ .filter(([alias, key]) => kept[alias] !== undefined && kept[key] !== undefined)
188
+ .map(([alias]) => alias);
189
+ const skipped = [...skippable, ...shadowed].map((key) => `ops[${i}].${key}`);
190
+ return { op: { name: op.op, spec, args: withAliases(spec, kept) }, skipped };
145
191
  }
146
192
  if (op.op === 'sheets' && 'name' in op && format.ops.addSheet) {
147
193
  return `ops[${i}] sheets lists the sheets and takes no arguments; to add a sheet use { op: "addSheet", name }`;
@@ -158,14 +204,16 @@ function parseOps(format, ops) {
158
204
  return 'ops must be an array of { op, ...args }';
159
205
  }
160
206
  const parsed = [];
207
+ const skipped = [];
161
208
  for (const [i, op] of ops.entries()) {
162
209
  const result = parseOp(format, op, i);
163
210
  if (typeof result === 'string') {
164
211
  return result;
165
212
  }
166
- parsed.push(result);
213
+ parsed.push(result.op);
214
+ skipped.push(...result.skipped);
167
215
  }
168
- return parsed;
216
+ return { ops: parsed, skipped };
169
217
  }
170
218
  function argumentError(format, args) {
171
219
  const { attachmentId, create, output } = args;
@@ -193,24 +241,25 @@ function parseRequest(format, raw) {
193
241
  if (error) {
194
242
  return error;
195
243
  }
196
- const ops = parseOps(format, args.ops ?? []);
197
- if (typeof ops === 'string') {
198
- return ops;
244
+ const parsed = parseOps(format, args.ops ?? []);
245
+ if (typeof parsed === 'string') {
246
+ return parsed;
199
247
  }
200
248
  const attachmentId = typeof args.attachmentId === 'string' ? args.attachmentId : undefined;
201
- if (attachmentId === undefined && !ops.length) {
249
+ if (attachmentId === undefined && !parsed.ops.length) {
202
250
  return `nothing to read: pass the attachmentId of a ${format.noun} (${WHERE_IDS_ARE}), or ops to build one`;
203
251
  }
204
252
  return {
205
253
  attachmentId,
206
254
  create: isObject(args.create) ? args.create : undefined,
207
- ops,
208
- output: typeof args.output === 'string' ? args.output : undefined
255
+ ops: parsed.ops,
256
+ output: typeof args.output === 'string' ? args.output : undefined,
257
+ skipped: parsed.skipped
209
258
  };
210
259
  }
211
260
  async function sourceDocument(format, request, ctx) {
212
261
  if (request.attachmentId === undefined) {
213
- return { document: format.create(request.create ?? {}), fileName: null };
262
+ return createDocument(format, request.create ?? {});
214
263
  }
215
264
  const found = await ctx.fetchAttachment?.({
216
265
  attachmentId: request.attachmentId,
@@ -221,7 +270,43 @@ async function sourceDocument(format, request, ctx) {
221
270
  error: `attachment ${request.attachmentId} not found in this chat; ${WHERE_IDS_ARE}, not a file name`
222
271
  };
223
272
  }
224
- return { document: format.open(found.bytes), fileName: found.fileName };
273
+ return { document: format.open(found.bytes), fileName: found.fileName, skipped: [] };
274
+ }
275
+ function createDocument(format, options) {
276
+ try {
277
+ return { document: format.create(options), fileName: null, skipped: [] };
278
+ }
279
+ catch (err) {
280
+ const looks = (format.looks ?? []).filter((key) => options[key] !== undefined);
281
+ if (!invalidOptions(err) || !looks.length) {
282
+ throw err;
283
+ }
284
+ const plain = withoutKeys(options, looks);
285
+ const refused = looks.filter((key) => !creates(format, { ...plain, [key]: options[key] }));
286
+ return {
287
+ document: format.create(withoutKeys(options, refused)),
288
+ fileName: null,
289
+ skipped: refused.map((key) => `create.${key}`)
290
+ };
291
+ }
292
+ }
293
+ function creates(format, options) {
294
+ try {
295
+ format.create(options);
296
+ return true;
297
+ }
298
+ catch (err) {
299
+ if (!invalidOptions(err)) {
300
+ throw err;
301
+ }
302
+ return false;
303
+ }
304
+ }
305
+ function invalidOptions(err) {
306
+ return err instanceof DocsError && err.code === 'INVALID_OPTIONS';
307
+ }
308
+ function withoutKeys(args, keys) {
309
+ return Object.fromEntries(Object.entries(args).filter(([key]) => !keys.includes(key)));
225
310
  }
226
311
  export function revisedName(format, fileName) {
227
312
  const dot = fileName.lastIndexOf('.');
@@ -236,12 +321,24 @@ export function revisedName(format, fileName) {
236
321
  }
237
322
  return `${revised[1]}_revised-${Number(revised[2] ?? 1) + 1}.${format}`;
238
323
  }
239
- function outputFor(format, output, input) {
240
- if (!input)
241
- return output;
242
- if (output && output.toLowerCase() !== input.toLowerCase())
324
+ function newFileName(format, title) {
325
+ const stem = typeof title === 'string'
326
+ ? title
327
+ .toLowerCase()
328
+ .replace(/[^a-z0-9]+/g, '_')
329
+ .replace(/^_+|_+$/g, '')
330
+ .slice(0, 48)
331
+ : '';
332
+ return `${stem || format.stem}.${format.name}`;
333
+ }
334
+ function outputFor(format, { output, create }, input) {
335
+ if (!input) {
336
+ return output ?? newFileName(format, create?.title);
337
+ }
338
+ if (output && output.toLowerCase() !== input.toLowerCase()) {
243
339
  return output;
244
- return revisedName(format, input);
340
+ }
341
+ return revisedName(format.name, input);
245
342
  }
246
343
  async function imageId(ctx, id) {
247
344
  const found = await ctx.fetchAttachment?.({ attachmentId: id, meta: true, signal: ctx.signal });
@@ -265,6 +362,44 @@ async function imageInput(op, i, ctx) {
265
362
  function takesImage(op) {
266
363
  return op.spec.slots.includes('image') || op.args.image !== undefined;
267
364
  }
365
+ async function withoutMissingUploads(request, ctx) {
366
+ if (!ctx.fetchAttachment || !request.ops.some((op) => idless(op) && optionalImage(op))) {
367
+ return request;
368
+ }
369
+ const available = await uploadsAvailable(ctx.fetchAttachment, {
370
+ turnImages: ctx.turnImages,
371
+ signal: ctx.signal
372
+ });
373
+ if (available === null) {
374
+ return request;
375
+ }
376
+ const uploading = await Promise.all(request.ops.map((op) => takesUpload(op, ctx)));
377
+ let uploads = 0;
378
+ const skipped = [];
379
+ const ops = request.ops.map((op, i) => {
380
+ if (!uploading[i] || uploads++ < available || !optionalImage(op)) {
381
+ return op;
382
+ }
383
+ skipped.push(`ops[${i}].image`);
384
+ return { ...op, args: withoutKeys(op.args, ['image']) };
385
+ });
386
+ return { ...request, ops, skipped: [...request.skipped, ...skipped] };
387
+ }
388
+ function idless(op) {
389
+ const { image } = op.args;
390
+ const noId = image === undefined || image === null || (isObject(image) && image.attachmentId === undefined);
391
+ return takesImage(op) && noId;
392
+ }
393
+ async function takesUpload(op, ctx) {
394
+ const id = isObject(op.args.image) ? op.args.image.attachmentId : undefined;
395
+ if (typeof id !== 'string' || !id) {
396
+ return idless(op);
397
+ }
398
+ return (await imageId(ctx, id)) === undefined;
399
+ }
400
+ function optionalImage({ spec }) {
401
+ return spec.slots.some((slot) => typeof slot !== 'string' && slot.includes('image'));
402
+ }
268
403
  async function stagedImages(request, ctx) {
269
404
  const wanted = request.ops.flatMap((op, i) => (takesImage(op) ? [i] : []));
270
405
  const images = new Map();
@@ -299,9 +434,6 @@ async function stagedImages(request, ctx) {
299
434
  return images;
300
435
  }
301
436
  function saveError({ format, document, output }, ctx) {
302
- if (!output) {
303
- return `the ops changed the ${format.noun}; name the file in output`;
304
- }
305
437
  if (!output.toLowerCase().endsWith(`.${format.name}`)) {
306
438
  return `output must end in .${format.name}, got "${output}"`;
307
439
  }
@@ -313,7 +445,7 @@ function saveError({ format, document, output }, ctx) {
313
445
  }
314
446
  async function attachOutput(job, ctx) {
315
447
  const refused = saveError(job, ctx);
316
- if (refused || !job.output || !ctx.attach) {
448
+ if (refused || !ctx.attach) {
317
449
  return { error: refused ?? 'nothing to save' };
318
450
  }
319
451
  const { output, document } = job;
@@ -363,6 +495,7 @@ function runOp(document, op, input) {
363
495
  }
364
496
  function runOps({ format, document, request, images }) {
365
497
  const results = [];
498
+ const skipped = [];
366
499
  const created = request.attachmentId === undefined;
367
500
  for (const [i, op] of request.ops.entries()) {
368
501
  const placed = format.prepare?.(document, op.args, created) ?? op.args;
@@ -371,11 +504,35 @@ function runOps({ format, document, request, images }) {
371
504
  results.push(runOp(document, op, input));
372
505
  }
373
506
  catch (err) {
507
+ const retry = format.retry?.(err, op, input);
508
+ const again = retry ? rerun(document, op, retry.input) : RETRY_FAILED;
509
+ if (retry && again !== RETRY_FAILED) {
510
+ results.push(again);
511
+ skipped.push(`ops[${i}].${retry.skipped}`);
512
+ continue;
513
+ }
374
514
  const hint = format.hint?.(err, created) ?? '';
375
515
  return { error: `ops[${i}] ${op.name}: ${errorMessage(err)}${hint}` };
376
516
  }
377
517
  }
378
- return results;
518
+ return { results, skipped };
519
+ }
520
+ const RETRY_FAILED = Symbol('retry failed');
521
+ function rerun(document, op, input) {
522
+ try {
523
+ return runOp(document, op, input);
524
+ }
525
+ catch {
526
+ return RETRY_FAILED;
527
+ }
528
+ }
529
+ function withoutLayout(err, op, input) {
530
+ const shapeMissing = err instanceof DocsError && err.code === 'SHAPE_NOT_FOUND';
531
+ if (op.name !== 'addSlide' || input.layout === undefined || !shapeMissing) {
532
+ return null;
533
+ }
534
+ const { layout: _layout, ...rest } = input;
535
+ return { input: rest, skipped: 'layout' };
379
536
  }
380
537
  function countLine(counts) {
381
538
  return Object.entries(counts)
@@ -424,10 +581,11 @@ function parameters(format) {
424
581
  };
425
582
  }
426
583
  async function execute(format, args, ctx) {
427
- const request = parseRequest(format, args);
428
- if (typeof request === 'string') {
429
- return { error: request };
584
+ const parsed = parseRequest(format, args);
585
+ if (typeof parsed === 'string') {
586
+ return { error: parsed };
430
587
  }
588
+ const request = await withoutMissingUploads(parsed, ctx);
431
589
  if (request.attachmentId !== undefined && !ctx.fetchAttachment) {
432
590
  return { error: 'this device cannot read chat attachments' };
433
591
  }
@@ -449,21 +607,24 @@ async function execute(format, args, ctx) {
449
607
  if (!request.ops.length) {
450
608
  return { document: format.read(document) };
451
609
  }
452
- const results = runOps({ format, document, request, images });
453
- if ('error' in results) {
454
- return results;
610
+ const ran = runOps({ format, document, request, images });
611
+ if ('error' in ran) {
612
+ return ran;
455
613
  }
456
- if (!document.changed && request.attachmentId !== undefined) {
614
+ const { results } = ran;
615
+ const onlyQueries = request.ops.every(({ spec }) => spec.query);
616
+ if (onlyQueries || (!document.changed && request.attachmentId !== undefined)) {
457
617
  return { results };
458
618
  }
459
- const output = outputFor(format.name, request.output, fileName);
619
+ const output = outputFor(format, request, fileName);
460
620
  const saved = await attachOutput({ format, document, output }, ctx);
461
621
  if ('error' in saved) {
462
622
  return saved;
463
623
  }
464
624
  const { attachment, repeated } = saved;
625
+ const skipped = [...source.skipped, ...request.skipped, ...ran.skipped];
465
626
  const counts = format.count(document);
466
- const renamed = output !== request.output
627
+ const renamed = fileName !== null && output !== request.output
467
628
  ? `Saved as ${output}, so the attached ${fileName} keeps its own name. `
468
629
  : '';
469
630
  const unplaced = !!ctx.turnImages?.length && !images.size;
@@ -471,6 +632,7 @@ async function execute(format, args, ctx) {
471
632
  results,
472
633
  attachments: [attachment],
473
634
  ...counts,
635
+ skipped: skipped.length ? skipped : undefined,
474
636
  reply: `${attachment.fileName} — ${countLine(counts)}`,
475
637
  next: renamed +
476
638
  `Done: ${attachment.fileName} ${repeated ? 'was already' : 'is'} attached to the chat and shown to the user. ` +
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { READ_METHODS } from '../http-methods.js';
3
- import { truncateResponseBody } from '../http-request/truncate-response.js';
3
+ import { capResponseBody } from '../http-request/truncate-response.js';
4
4
  import { BUILDERS } from './builders.js';
5
5
  import { DECODERS } from './decoders.js';
6
6
  export function compileOperationTools(catalog, { httpRequestTool, mcpCallTool }) {
@@ -54,17 +54,17 @@ function operationTool(owningSkill, operation, transportTool) {
54
54
  body: built.request.body,
55
55
  encode: built.request.encode
56
56
  }, response ? { ...skillContext, uncappedResponse: true } : skillContext);
57
- return response ? capBody(shapeResponse(result, response)) : result;
57
+ return response ? capBody(shapeResponse(result, response), ctx) : result;
58
58
  }
59
59
  };
60
60
  }
61
61
  const JsonResult = z.looseObject({ status: z.number().optional(), body: z.string() });
62
- function capBody(result) {
62
+ function capBody(result, ctx) {
63
63
  const parsed = JsonResult.safeParse(result);
64
64
  if (!parsed.success) {
65
65
  return result;
66
66
  }
67
- return { ...parsed.data, body: truncateResponseBody(parsed.data.body) };
67
+ return { ...parsed.data, ...capResponseBody(parsed.data.body, ctx) };
68
68
  }
69
69
  function shapeResponse(result, response) {
70
70
  const parsed = JsonResult.safeParse(result);
@@ -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',
@@ -9,6 +9,7 @@ interface CredentialCheckResponse {
9
9
  export type CredentialCheckFetch = (input: string, init: {
10
10
  method: string;
11
11
  headers: Headers;
12
+ body?: string;
12
13
  signal: BareAbortSignal;
13
14
  }) => Promise<CredentialCheckResponse>;
14
15
  export interface ValidateCredentialChecksOptions {