@qvac/harness 0.8.12 → 0.8.14

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 (49) hide show
  1. package/CHANGELOG.md +101 -1
  2. package/dist-lib/index.js +9 -4
  3. package/dist-lib/lib/capabilities/completion.d.ts +6 -1
  4. package/dist-lib/lib/capabilities/completion.js +135 -66
  5. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  6. package/dist-lib/lib/capabilities/tool-turns.js +14 -3
  7. package/dist-lib/lib/connect.js +3 -2
  8. package/dist-lib/lib/contract-types.d.ts +1 -0
  9. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  10. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  11. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  12. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  13. package/dist-lib/lib/models/gguf-header.d.ts +6 -0
  14. package/dist-lib/lib/models/gguf-header.js +38 -1
  15. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  16. package/dist-lib/lib/models/kv-cache.js +8 -0
  17. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  18. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  19. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  20. package/dist-lib/lib/models/model-pool.js +20 -8
  21. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  22. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  23. package/dist-lib/lib/prompt.d.ts +6 -3
  24. package/dist-lib/lib/prompt.js +28 -17
  25. package/dist-lib/lib/serve.js +3 -2
  26. package/dist-lib/lib/tools/edit-image.js +4 -3
  27. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  28. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  29. package/dist-lib/lib/tools/generate-image.js +4 -3
  30. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  31. package/dist-lib/lib/tools/http-request/request.js +2 -1
  32. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  33. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  34. package/dist-lib/lib/tools/http-request.js +12 -6
  35. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  36. package/dist-lib/lib/tools/office/ops.js +5 -1
  37. package/dist-lib/lib/tools/office.d.ts +1 -0
  38. package/dist-lib/lib/tools/office.js +151 -21
  39. package/dist-lib/lib/tools/operations/compile.js +4 -4
  40. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  41. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  42. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  43. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  44. package/dist-lib/schema/harness.js +2 -1
  45. package/dist-lib/spec/hrpc/messages.js +8 -5
  46. package/dist-lib/spec/hyperschema/index.js +8 -5
  47. package/dist-lib/spec/hyperschema/schema.json +6 -1
  48. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  49. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  export declare const MAX_RESPONSE_CHARS = 8192;
3
- export declare const TIMEOUT_MS = 10000;
3
+ export declare const IDLE_TIMEOUT_MS = 10000;
4
+ export declare const TIMEOUT_MS = 30000;
4
5
  export interface FetchInit {
5
6
  method: string;
6
7
  headers: Record<string, string>;
@@ -10,6 +11,7 @@ export interface FetchInit {
10
11
  validatedAddresses?: readonly string[] | undefined;
11
12
  maxBytes?: number;
12
13
  truncate?: boolean;
14
+ idleTimeoutMs?: number;
13
15
  }
14
16
  export declare function isRedirectStatus(status: number): boolean;
15
17
  export type ParseResult<T> = {
@@ -1,7 +1,8 @@
1
1
  import { isRecord } from '../../guards.js';
2
2
  const BLOCKED_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
3
3
  export const MAX_RESPONSE_CHARS = 8192;
4
- export const TIMEOUT_MS = 10_000;
4
+ export const IDLE_TIMEOUT_MS = 10_000;
5
+ export const TIMEOUT_MS = 30_000;
5
6
  export function isRedirectStatus(status) {
6
7
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
7
8
  }
@@ -1,2 +1,18 @@
1
- export declare function truncateResponseBody(body: string): string;
1
+ import type { ToolExecuteContext } from '../../capabilities/completion.ts';
2
+ export declare function responseRoomChars(ctxSize: number | undefined, cacheTokens: number | undefined): number | undefined;
3
+ type BudgetContext = Pick<ToolExecuteContext, 'ctxSize' | 'runBudget'> | undefined;
4
+ export declare function responseBudgetChars(ctx: BudgetContext): number;
5
+ export declare function capResponseBody(body: string, ctx: BudgetContext): CappedBody;
6
+ export interface ResponseCoverage {
7
+ readonly keptChars: number;
8
+ readonly totalChars: number;
9
+ readonly percent: number;
10
+ readonly note: string;
11
+ }
12
+ export interface CappedBody {
13
+ readonly body: string;
14
+ readonly truncated?: ResponseCoverage;
15
+ }
16
+ export declare function truncateResponseBody(body: string, budget: number): CappedBody;
2
17
  export declare const ELISION = "\u2026 [truncated]";
18
+ export {};
@@ -1,19 +1,61 @@
1
1
  import { MAX_RESPONSE_CHARS } from './request.js';
2
2
  import { isRecord } from '../../guards.js';
3
- export function truncateResponseBody(body) {
4
- if (body.length <= MAX_RESPONSE_CHARS)
5
- return body;
6
- return fitJson(body) ?? `${body.slice(0, MAX_RESPONSE_CHARS)}… [truncated]`;
3
+ const RESPONSE_FLOOR_CHARS = 2048;
4
+ export function responseRoomChars(ctxSize, cacheTokens) {
5
+ if (!ctxSize || !cacheTokens) {
6
+ return undefined;
7
+ }
8
+ return Math.floor(Math.max(0, ctxSize - cacheTokens) / 2);
9
+ }
10
+ export function responseBudgetChars(ctx) {
11
+ const room = ctx?.runBudget?.responseRoomChars;
12
+ if (room !== undefined) {
13
+ return Math.max(RESPONSE_FLOOR_CHARS, room);
14
+ }
15
+ const ctxSize = ctx?.ctxSize;
16
+ return ctxSize ? Math.max(MAX_RESPONSE_CHARS, Math.floor(ctxSize / 4)) : MAX_RESPONSE_CHARS;
17
+ }
18
+ export function capResponseBody(body, ctx) {
19
+ const capped = truncateResponseBody(body, responseBudgetChars(ctx));
20
+ const budget = ctx?.runBudget;
21
+ if (budget?.responseRoomChars !== undefined) {
22
+ budget.responseRoomChars = Math.max(0, budget.responseRoomChars - capped.body.length);
23
+ }
24
+ return capped;
25
+ }
26
+ const NOT_JSON = Symbol('not-json');
27
+ export function truncateResponseBody(body, budget) {
28
+ if (body.length <= budget) {
29
+ return { body };
30
+ }
31
+ const parsed = parseJson(body);
32
+ if (parsed !== NOT_JSON) {
33
+ const compact = JSON.stringify(parsed);
34
+ if (compact.length <= budget) {
35
+ return { body: compact };
36
+ }
37
+ const kept = JSON.stringify(fit(parsed, budget));
38
+ return { body: kept, truncated: coverageOf(Math.min(kept.length, budget), compact.length) };
39
+ }
40
+ const kept = `${body.slice(0, budget)}${ELISION}`;
41
+ return { body: kept, truncated: coverageOf(budget, body.length) };
42
+ }
43
+ function coverageOf(keptChars, totalChars) {
44
+ const percent = Math.max(1, Math.floor((keptChars / totalChars) * 100));
45
+ return {
46
+ keptChars,
47
+ totalChars,
48
+ percent,
49
+ note: `Only the first ${percent}% of this response was read, to fit the context window. Tell the user that your answer covers that part only.`
50
+ };
7
51
  }
8
- function fitJson(body) {
9
- let parsed;
52
+ function parseJson(body) {
10
53
  try {
11
- parsed = JSON.parse(body);
54
+ return JSON.parse(body);
12
55
  }
13
56
  catch {
14
- return null;
57
+ return NOT_JSON;
15
58
  }
16
- return JSON.stringify(fit(parsed, MAX_RESPONSE_CHARS));
17
59
  }
18
60
  const MARKER_CHARS = 64;
19
61
  function shrinkable(value) {
@@ -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';
@@ -15,7 +15,7 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
15
15
  name: 'http_request',
16
16
  toolset: 'http-request',
17
17
  deferLoading: true,
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
+ 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.',
19
19
  parameters: {
20
20
  type: 'object',
21
21
  properties: {
@@ -134,7 +134,8 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
134
134
  body,
135
135
  signal: controller.signal,
136
136
  redirect: 'manual',
137
- validatedAddresses
137
+ validatedAddresses,
138
+ idleTimeoutMs: IDLE_TIMEOUT_MS
138
139
  });
139
140
  if (credentialKey) {
140
141
  recordCredentialHealth(credentialKey, response.status, ctx?.agentId);
@@ -175,14 +176,19 @@ export function createHttpRequestTool({ fetch: fetchImpl, credentialStore, crede
175
176
  credentialKey = next.credentialKey;
176
177
  }
177
178
  const text = await response.text();
179
+ if (ctx?.uncappedResponse) {
180
+ return { status: response.status, body: text };
181
+ }
178
182
  return {
179
183
  status: response.status,
180
- body: ctx?.uncappedResponse ? text : truncateResponseBody(text)
184
+ ...capResponseBody(text, ctx)
181
185
  };
182
186
  }
183
187
  catch (err) {
184
188
  const error = err instanceof Error ? err : new Error(String(err));
185
- const timedOut = error.name === 'AbortError' || error instanceof AbortedError;
189
+ const timedOut = error.name === 'AbortError' ||
190
+ error.name === 'TimeoutError' ||
191
+ error instanceof AbortedError;
186
192
  return {
187
193
  error: timedOut ? 'request timed out' : `request failed: ${error.message}`,
188
194
  code: timedOut ? 'timeout' : 'transport'
@@ -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;
@@ -17,6 +17,21 @@ const WHERE_IDS_ARE = 'copy the id from the [Attached file "…" — attachmentI
17
17
  function isObject(value) {
18
18
  return isRecord(value) && !Array.isArray(value);
19
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
+ }
20
35
  export function shapeFor(deck, op) {
21
36
  const { shape, slide } = op;
22
37
  if (typeof shape !== 'string' || SHAPE_ROLES.has(shape) || typeof slide !== 'number') {
@@ -80,11 +95,13 @@ const PPTX_FORMAT = {
80
95
  stem: 'presentation',
81
96
  ops: PPTX_OPS,
82
97
  createKeys: ['size', 'title', 'fonts', 'colors'],
98
+ looks: ['fonts', 'colors'],
83
99
  open: (bytes) => pptx.open(bytes),
84
100
  create: (options) => pptx.create(options),
85
101
  read: (deck) => deck.read(),
86
102
  count: (deck) => ({ slides: deck.slideCount }),
87
- prepare: (deck, op) => shapeFor(deck, op),
103
+ prepare: (deck, op) => shapeFor(deck, bodyLines(op)),
104
+ retry: withoutLayout,
88
105
  hint: newDeckHint
89
106
  };
90
107
  const DOCX_FORMAT = {
@@ -161,9 +178,16 @@ function parseOp(format, op, i) {
161
178
  return `ops[${i}]: unknown op "${op.op}"; ops are ${Object.keys(format.ops).join(', ')}`;
162
179
  }
163
180
  const keys = opKeys(spec);
164
- 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));
165
184
  if (!unknown.length) {
166
- 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 };
167
191
  }
168
192
  if (op.op === 'sheets' && 'name' in op && format.ops.addSheet) {
169
193
  return `ops[${i}] sheets lists the sheets and takes no arguments; to add a sheet use { op: "addSheet", name }`;
@@ -180,14 +204,16 @@ function parseOps(format, ops) {
180
204
  return 'ops must be an array of { op, ...args }';
181
205
  }
182
206
  const parsed = [];
207
+ const skipped = [];
183
208
  for (const [i, op] of ops.entries()) {
184
209
  const result = parseOp(format, op, i);
185
210
  if (typeof result === 'string') {
186
211
  return result;
187
212
  }
188
- parsed.push(result);
213
+ parsed.push(result.op);
214
+ skipped.push(...result.skipped);
189
215
  }
190
- return parsed;
216
+ return { ops: parsed, skipped };
191
217
  }
192
218
  function argumentError(format, args) {
193
219
  const { attachmentId, create, output } = args;
@@ -215,24 +241,25 @@ function parseRequest(format, raw) {
215
241
  if (error) {
216
242
  return error;
217
243
  }
218
- const ops = parseOps(format, args.ops ?? []);
219
- if (typeof ops === 'string') {
220
- return ops;
244
+ const parsed = parseOps(format, args.ops ?? []);
245
+ if (typeof parsed === 'string') {
246
+ return parsed;
221
247
  }
222
248
  const attachmentId = typeof args.attachmentId === 'string' ? args.attachmentId : undefined;
223
- if (attachmentId === undefined && !ops.length) {
249
+ if (attachmentId === undefined && !parsed.ops.length) {
224
250
  return `nothing to read: pass the attachmentId of a ${format.noun} (${WHERE_IDS_ARE}), or ops to build one`;
225
251
  }
226
252
  return {
227
253
  attachmentId,
228
254
  create: isObject(args.create) ? args.create : undefined,
229
- ops,
230
- 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
231
258
  };
232
259
  }
233
260
  async function sourceDocument(format, request, ctx) {
234
261
  if (request.attachmentId === undefined) {
235
- return { document: format.create(request.create ?? {}), fileName: null };
262
+ return createDocument(format, request.create ?? {});
236
263
  }
237
264
  const found = await ctx.fetchAttachment?.({
238
265
  attachmentId: request.attachmentId,
@@ -243,7 +270,43 @@ async function sourceDocument(format, request, ctx) {
243
270
  error: `attachment ${request.attachmentId} not found in this chat; ${WHERE_IDS_ARE}, not a file name`
244
271
  };
245
272
  }
246
- 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)));
247
310
  }
248
311
  export function revisedName(format, fileName) {
249
312
  const dot = fileName.lastIndexOf('.');
@@ -299,6 +362,44 @@ async function imageInput(op, i, ctx) {
299
362
  function takesImage(op) {
300
363
  return op.spec.slots.includes('image') || op.args.image !== undefined;
301
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
+ }
302
403
  async function stagedImages(request, ctx) {
303
404
  const wanted = request.ops.flatMap((op, i) => (takesImage(op) ? [i] : []));
304
405
  const images = new Map();
@@ -394,6 +495,7 @@ function runOp(document, op, input) {
394
495
  }
395
496
  function runOps({ format, document, request, images }) {
396
497
  const results = [];
498
+ const skipped = [];
397
499
  const created = request.attachmentId === undefined;
398
500
  for (const [i, op] of request.ops.entries()) {
399
501
  const placed = format.prepare?.(document, op.args, created) ?? op.args;
@@ -402,11 +504,35 @@ function runOps({ format, document, request, images }) {
402
504
  results.push(runOp(document, op, input));
403
505
  }
404
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
+ }
405
514
  const hint = format.hint?.(err, created) ?? '';
406
515
  return { error: `ops[${i}] ${op.name}: ${errorMessage(err)}${hint}` };
407
516
  }
408
517
  }
409
- 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' };
410
536
  }
411
537
  function countLine(counts) {
412
538
  return Object.entries(counts)
@@ -455,10 +581,11 @@ function parameters(format) {
455
581
  };
456
582
  }
457
583
  async function execute(format, args, ctx) {
458
- const request = parseRequest(format, args);
459
- if (typeof request === 'string') {
460
- return { error: request };
584
+ const parsed = parseRequest(format, args);
585
+ if (typeof parsed === 'string') {
586
+ return { error: parsed };
461
587
  }
588
+ const request = await withoutMissingUploads(parsed, ctx);
462
589
  if (request.attachmentId !== undefined && !ctx.fetchAttachment) {
463
590
  return { error: 'this device cannot read chat attachments' };
464
591
  }
@@ -480,10 +607,11 @@ async function execute(format, args, ctx) {
480
607
  if (!request.ops.length) {
481
608
  return { document: format.read(document) };
482
609
  }
483
- const results = runOps({ format, document, request, images });
484
- if ('error' in results) {
485
- return results;
610
+ const ran = runOps({ format, document, request, images });
611
+ if ('error' in ran) {
612
+ return ran;
486
613
  }
614
+ const { results } = ran;
487
615
  const onlyQueries = request.ops.every(({ spec }) => spec.query);
488
616
  if (onlyQueries || (!document.changed && request.attachmentId !== undefined)) {
489
617
  return { results };
@@ -494,6 +622,7 @@ async function execute(format, args, ctx) {
494
622
  return saved;
495
623
  }
496
624
  const { attachment, repeated } = saved;
625
+ const skipped = [...source.skipped, ...request.skipped, ...ran.skipped];
497
626
  const counts = format.count(document);
498
627
  const renamed = fileName !== null && output !== request.output
499
628
  ? `Saved as ${output}, so the attached ${fileName} keeps its own name. `
@@ -503,6 +632,7 @@ async function execute(format, args, ctx) {
503
632
  results,
504
633
  attachments: [attachment],
505
634
  ...counts,
635
+ skipped: skipped.length ? skipped : undefined,
506
636
  reply: `${attachment.fileName} — ${countLine(counts)}`,
507
637
  next: renamed +
508
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);
@@ -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 {
@@ -68,6 +68,7 @@ async function runCheck(key, check, { skill, credentialStore, agentId, fetchImpl
68
68
  const response = await fetchImpl(check.url, {
69
69
  method: check.method ?? 'GET',
70
70
  headers: headers,
71
+ body: check.body,
71
72
  signal: controller.signal
72
73
  });
73
74
  const rejected = response.status === 401 || response.status === 403 || (await hasMcpAuthError(response));
@@ -5,9 +5,9 @@ export function parseManifestBlock(block, key = 'metadata') {
5
5
  return {};
6
6
  }
7
7
  const oc = json.openclaw;
8
- const requires = readRequires(oc.requires);
9
- const install = readInstall(oc.install);
10
8
  const setup = readSetup(oc.setup);
9
+ const requires = deriveCredentialChecks(readRequires(oc.requires), setup);
10
+ const install = readInstall(oc.install);
11
11
  return {
12
12
  requires,
13
13
  install,
@@ -127,11 +127,35 @@ function readCredentialChecks(v) {
127
127
  out[key] = {
128
128
  url: check.url,
129
129
  method: typeof check.method === 'string' ? check.method : undefined,
130
- headers
130
+ headers,
131
+ body: typeof check.body === 'string' ? check.body : undefined
131
132
  };
132
133
  }
133
134
  return Object.keys(out).length > 0 ? out : undefined;
134
135
  }
136
+ function deriveCredentialChecks(requires, setup) {
137
+ const derived = {};
138
+ for (const route of setup?.routes ?? []) {
139
+ const verify = route.oauth?.verify;
140
+ const key = route.credentialKey;
141
+ if (route.kind !== 'oauth' || !key || !verify || requires?.credentialChecks?.[key]) {
142
+ continue;
143
+ }
144
+ const accept = 'application/json, text/event-stream';
145
+ derived[key] = {
146
+ url: verify.url,
147
+ method: verify.method ?? (verify.body ? 'POST' : 'GET'),
148
+ body: verify.body,
149
+ headers: verify.body
150
+ ? { Accept: accept, 'Content-Type': 'application/json' }
151
+ : { Accept: accept }
152
+ };
153
+ }
154
+ if (Object.keys(derived).length === 0) {
155
+ return requires;
156
+ }
157
+ return { ...requires, credentialChecks: { ...requires?.credentialChecks, ...derived } };
158
+ }
135
159
  function readStringRecord(v) {
136
160
  if (!isObj(v))
137
161
  return undefined;
@@ -11,6 +11,7 @@ export interface SkillRequires {
11
11
  readonly url: string;
12
12
  readonly method?: string;
13
13
  readonly headers?: Readonly<Record<string, string>>;
14
+ readonly body?: string;
14
15
  }>>;
15
16
  }
16
17
  export interface InstallStep {
@@ -41,7 +41,8 @@ export function registerHarnessTypes(ns) {
41
41
  fields: [
42
42
  { name: 'role', type: '@harness/message-role', required: true },
43
43
  { name: 'content', type: 'string', required: true },
44
- { name: 'attachments', type: '@harness/message-attachment', array: true }
44
+ { name: 'attachments', type: '@harness/message-attachment', array: true },
45
+ { name: 'sentAt', type: 'uint' }
45
46
  ]
46
47
  });
47
48
  ns.register({
@@ -1,12 +1,12 @@
1
1
  // This file is autogenerated by the hyperschema compiler
2
- // Schema Version: 21
2
+ // Schema Version: 22
3
3
  /* eslint-disable camelcase */
4
4
  /* eslint-disable quotes */
5
5
  /* eslint-disable space-before-function-paren */
6
6
 
7
7
  import { c } from 'hyperschema/runtime'
8
8
 
9
- const VERSION = 21
9
+ const VERSION = 22
10
10
 
11
11
  // eslint-disable-next-line no-unused-vars
12
12
  let version = VERSION
@@ -303,18 +303,20 @@ const encoding7 = {
303
303
  preencode(state, m) {
304
304
  encoding5.preencode(state, m.role)
305
305
  c.string.preencode(state, m.content)
306
- state.end++ // max flag is 1 so always one byte
306
+ state.end++ // max flag is 2 so always one byte
307
307
 
308
308
  if (m.attachments) encoding7_2.preencode(state, m.attachments)
309
+ if (version >= 22 && m.sentAt) c.uint.preencode(state, m.sentAt)
309
310
  },
310
311
  encode(state, m) {
311
- const flags = m.attachments ? 1 : 0
312
+ const flags = (m.attachments ? 1 : 0) | ((version >= 22 && m.sentAt) ? 2 : 0)
312
313
 
313
314
  encoding5.encode(state, m.role)
314
315
  c.string.encode(state, m.content)
315
316
  c.uint.encode(state, flags)
316
317
 
317
318
  if (m.attachments) encoding7_2.encode(state, m.attachments)
319
+ if (version >= 22 && m.sentAt) c.uint.encode(state, m.sentAt)
318
320
  },
319
321
  decode(state) {
320
322
  const r0 = encoding5.decode(state)
@@ -324,7 +326,8 @@ const encoding7 = {
324
326
  return {
325
327
  role: r0,
326
328
  content: r1,
327
- attachments: (flags & 1) !== 0 ? encoding7_2.decode(state) : null
329
+ attachments: (flags & 1) !== 0 ? encoding7_2.decode(state) : null,
330
+ sentAt: (version >= 22 && (flags & 2) !== 0) ? c.uint.decode(state) : 0
328
331
  }
329
332
  }
330
333
  }