@qvac/harness 0.8.12 → 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 (47) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist-lib/index.js +7 -3
  3. package/dist-lib/lib/capabilities/completion.d.ts +5 -1
  4. package/dist-lib/lib/capabilities/completion.js +35 -9
  5. package/dist-lib/lib/connect.js +3 -2
  6. package/dist-lib/lib/contract-types.d.ts +1 -0
  7. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  8. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  9. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  10. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  11. package/dist-lib/lib/models/gguf-header.d.ts +6 -0
  12. package/dist-lib/lib/models/gguf-header.js +38 -1
  13. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  14. package/dist-lib/lib/models/kv-cache.js +8 -0
  15. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  16. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  17. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  18. package/dist-lib/lib/models/model-pool.js +20 -8
  19. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  20. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  21. package/dist-lib/lib/prompt.d.ts +2 -1
  22. package/dist-lib/lib/prompt.js +12 -12
  23. package/dist-lib/lib/serve.js +3 -2
  24. package/dist-lib/lib/tools/edit-image.js +4 -3
  25. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  26. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  27. package/dist-lib/lib/tools/generate-image.js +4 -3
  28. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  29. package/dist-lib/lib/tools/http-request/request.js +2 -1
  30. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  31. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  32. package/dist-lib/lib/tools/http-request.js +12 -6
  33. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  34. package/dist-lib/lib/tools/office/ops.js +5 -1
  35. package/dist-lib/lib/tools/office.d.ts +1 -0
  36. package/dist-lib/lib/tools/office.js +151 -21
  37. package/dist-lib/lib/tools/operations/compile.js +4 -4
  38. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  39. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  40. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  41. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  42. package/dist-lib/schema/harness.js +2 -1
  43. package/dist-lib/spec/hrpc/messages.js +8 -5
  44. package/dist-lib/spec/hyperschema/index.js +8 -5
  45. package/dist-lib/spec/hyperschema/schema.json +6 -1
  46. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  47. package/package.json +2 -2
@@ -5,7 +5,9 @@ import ResourcePuddle from 'resource-puddle';
5
5
  import { ModelHandle } from './model-handle.js';
6
6
  import { defaultContextSize } from './context.js';
7
7
  import { customContextLength } from './model-catalog.js';
8
- import { adrenoSafeKvCache } from './kv-cache.js';
8
+ import { localWeightFile } from './custom-model-cache.js';
9
+ import { GGUF_STUB_MAX_BYTES, parseGgufHeader, readGgufHeaderBytes } from './gguf-header.js';
10
+ import { adrenoSafeKvCache, headSafeKvCache } from './kv-cache.js';
9
11
  import { DEFAULT_EMBED_BATCH_SIZE } from './embed-config.js';
10
12
  import { log } from '../log.js';
11
13
  import { RUNAWAY_STOP_SEQUENCES } from '../helpers/control-tokens.js';
@@ -358,11 +360,12 @@ export function loadClockGuard(model, sdk, { now = () => Date.now(), monoMs = mo
358
360
  };
359
361
  return { race };
360
362
  }
361
- export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold } = {}) {
363
+ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold, modelsDir } = {}) {
362
364
  const load = async (key, model, opts) => {
363
365
  const sdk = await loadSdk();
364
366
  const modelSrc = await resolveModelSrc(sdk, model);
365
367
  const resolved = resolveLoadOptions(opts, deviceConfig);
368
+ const header = await weightHeader(modelSrc, modelsDir);
366
369
  const tier = defaultContextSize(modelSrc, customContextLength(model));
367
370
  const projectionModelSrc = resolved.projectionModel
368
371
  ? await resolveProjectionSrc(sdk, resolved.projectionModel)
@@ -370,13 +373,11 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
370
373
  const mainGpu = deviceConfig.device !== 'cpu' && deviceConfig.mainGpu
371
374
  ? await deviceConfig.mainGpu()
372
375
  : undefined;
373
- const kvCache = adrenoSafeKvCache(deviceConfig.device, {
374
- k: resolved.kvCacheK,
375
- v: resolved.kvCacheV
376
- });
376
+ const kvCache = headSafeKvCache(adrenoSafeKvCache(deviceConfig.device, { k: resolved.kvCacheK, v: resolved.kvCacheV }), header?.headDims);
377
377
  const openclCache = deviceConfig.device !== 'cpu' && deviceConfig.openclCacheDir
378
378
  ? deviceConfig.openclCacheDir()
379
379
  : undefined;
380
+ const placement = deviceConfig.device === 'cpu' ? deviceConfig.cpuPlacement?.() : undefined;
380
381
  const config = definedFields({
381
382
  verbosity: llmVerbosity(),
382
383
  tools: true,
@@ -387,7 +388,9 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
387
388
  device: deviceConfig.device,
388
389
  gpu_layers: deviceConfig.gpuLayers,
389
390
  'main-gpu': mainGpu,
390
- openclCacheDir: openclCache || undefined
391
+ openclCacheDir: openclCache || undefined,
392
+ threads: placement?.threads,
393
+ 'cpu-mask': placement?.mask
391
394
  });
392
395
  const pending = { key, model, modelSrc, modelType: 'llamacpp-completion' };
393
396
  const ctxSize = resolved.ctxSize ||
@@ -406,7 +409,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
406
409
  })))
407
410
  .finally(() => admission?.release());
408
411
  log.info('llm loaded', { model, loadMs: Date.now() - loadStarted });
409
- return { model, modelId, ctxSize, bytes: admission?.bytes };
412
+ return { model, modelId, ctxSize, bytes: admission?.bytes, canThink: canThink(header) };
410
413
  };
411
414
  return new ModelPuddle({
412
415
  open: (key, model = key, opts = {}) => reportedHandle({ notify, model, addon: 'llm', hold, load: () => load(key, model, opts) }),
@@ -414,6 +417,15 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
414
417
  ...NO_IDLE_GC
415
418
  });
416
419
  }
420
+ async function weightHeader(modelSrc, modelsDir) {
421
+ const file = typeof modelSrc === 'string' ? localWeightFile(modelSrc, modelsDir) : null;
422
+ const bytes = file ? await readGgufHeaderBytes(file, { maxBytes: GGUF_STUB_MAX_BYTES }) : null;
423
+ return bytes && parseGgufHeader(bytes);
424
+ }
425
+ function canThink(header) {
426
+ const template = header?.chatTemplate;
427
+ return template === undefined ? undefined : /<think(?:ing)?>/.test(template);
428
+ }
417
429
  export function createEmbedPool(loadSdk, notify, { faults, batchSize = DEFAULT_EMBED_BATCH_SIZE, openclCacheDir, loads = createLoadTracker(), beforeLoad, hold }) {
418
430
  const load = async (key, model) => {
419
431
  const sdk = await loadSdk();
@@ -27,6 +27,7 @@ export interface NoRedirectFetchInit {
27
27
  validatedAddresses?: readonly string[] | undefined;
28
28
  maxBytes?: number;
29
29
  truncate?: boolean;
30
+ idleTimeoutMs?: number;
30
31
  }
31
32
  export interface NoRedirectFetchResponse {
32
33
  status: number;
@@ -3,7 +3,22 @@ import { HarnessError } from './errors.js';
3
3
  import { DEFAULT_USER_AGENT } from './user-agent.js';
4
4
  const UA_SNIFFING_HOSTS = new Set(['wttr.in']);
5
5
  export function runNoRedirectFetch(request, url, init = {}) {
6
- return new Promise((resolve, reject) => {
6
+ return new Promise((outerResolve, outerReject) => {
7
+ let idle = null;
8
+ const stopIdle = () => {
9
+ if (idle) {
10
+ clearTimeout(idle);
11
+ }
12
+ idle = null;
13
+ };
14
+ const resolve = (response) => {
15
+ stopIdle();
16
+ outerResolve(response);
17
+ };
18
+ const reject = (err) => {
19
+ stopIdle();
20
+ outerReject(err);
21
+ };
7
22
  const headers = { ...init.headers };
8
23
  if (init.body !== undefined &&
9
24
  !Object.keys(headers).some((h) => h.toLowerCase() === 'content-length')) {
@@ -16,6 +31,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
16
31
  }
17
32
  const method = init.method ?? 'GET';
18
33
  const req = request(url, { method, headers, validatedAddresses: init.validatedAddresses }, (res) => {
34
+ armIdle();
19
35
  const chunks = [];
20
36
  let received = 0;
21
37
  let settled = false;
@@ -45,6 +61,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
45
61
  reject(err);
46
62
  };
47
63
  res.on('data', (chunk) => {
64
+ armIdle();
48
65
  received += chunk.byteLength;
49
66
  if (init.maxBytes !== undefined && received > init.maxBytes) {
50
67
  if (init.truncate) {
@@ -67,6 +84,20 @@ export function runNoRedirectFetch(request, url, init = {}) {
67
84
  res.on('end', respond);
68
85
  });
69
86
  req.on('error', reject);
87
+ function armIdle() {
88
+ const ms = init.idleTimeoutMs;
89
+ if (ms === undefined) {
90
+ return;
91
+ }
92
+ stopIdle();
93
+ idle = setTimeout(() => {
94
+ const err = new Error(`no data received for ${ms} ms`);
95
+ err.name = 'TimeoutError';
96
+ req.destroy(err);
97
+ reject(err);
98
+ }, ms);
99
+ }
100
+ armIdle();
70
101
  if (init.signal) {
71
102
  const abort = () => {
72
103
  const err = new Error('This operation was aborted');
@@ -1,8 +1,9 @@
1
1
  export declare const RAG_CITATION_LINE = "After your answer, add one final line naming the files you used, written exactly as [Sources: file-a.pdf, file-b.md] - or [Sources: none] if the excerpts did not answer the question. This line is required, it is the only place square brackets belong, and it is removed before the user sees it.";
2
2
  export declare function currentTimeAnnotation(now?: Date): string;
3
- export declare function annotateLastUserTime<T extends {
3
+ export declare function annotateUserTimes<T extends {
4
4
  role: string;
5
5
  content: string;
6
+ sentAt?: number | undefined;
6
7
  }>(turns: ReadonlyArray<T>, now?: Date): T[];
7
8
  export interface SystemPromptInput {
8
9
  bio?: string | null | undefined;
@@ -22,25 +22,25 @@ export const RAG_CITATION_LINE = 'After your answer, add one final line naming t
22
22
  const METADATA_SECTION = `## Message Metadata
23
23
 
24
24
  User messages may include metadata such as [Current local time: ...]. This is contextual information provided by the system, not part of the user's query. Use it only when relevant and never repeat it unless the user asks about the current date or time.`;
25
+ const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
25
26
  export function currentTimeAnnotation(now = new Date()) {
26
27
  const p = (n) => String(n).padStart(2, '0');
27
- const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
28
+ const stamp = `${WEEKDAYS[now.getDay()]} ${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
28
29
  const offset = -now.getTimezoneOffset();
29
30
  const sign = offset < 0 ? '-' : '+';
30
31
  const abs = Math.abs(offset);
31
32
  return `[Current local time: ${stamp} (UTC${sign}${p(Math.floor(abs / 60))}:${p(abs % 60)})]`;
32
33
  }
33
- export function annotateLastUserTime(turns, now) {
34
- const result = [...turns];
35
- for (let i = result.length - 1; i >= 0; i--) {
36
- const turn = result[i];
37
- if (!turn || turn.role !== 'user') {
38
- continue;
39
- }
40
- result[i] = { ...turn, content: `${currentTimeAnnotation(now)}\n\n${turn.content}` };
41
- break;
42
- }
43
- return result;
34
+ export function annotateUserTimes(turns, now = new Date()) {
35
+ const lastUser = turns.findLastIndex((turn) => turn.role === 'user');
36
+ return turns.map((turn, i) => {
37
+ if (turn.role !== 'user')
38
+ return turn;
39
+ if (!turn.sentAt && i !== lastUser)
40
+ return turn;
41
+ const at = turn.sentAt ? new Date(turn.sentAt) : now;
42
+ return { ...turn, content: `${currentTimeAnnotation(at)}\n\n${turn.content}` };
43
+ });
44
44
  }
45
45
  function buildGuidelines(active) {
46
46
  const lines = [...BASE_GUIDELINES];
@@ -538,12 +538,13 @@ function completion(harness) {
538
538
  typedText: isRecord(frame.payload) && typeof frame.payload.typedText === 'string'
539
539
  ? frame.payload.typedText
540
540
  : undefined,
541
- messages: (frame.messages ?? []).map(({ role, content, attachments }) => ({
541
+ messages: (frame.messages ?? []).map(({ role, content, attachments, sentAt }) => ({
542
542
  role,
543
543
  content,
544
544
  attachments: attachments?.length
545
545
  ? attachments.map(({ path: file }) => ({ path: file }))
546
- : undefined
546
+ : undefined,
547
+ sentAt: sentAt || undefined
547
548
  })),
548
549
  toolConfigs: frame.toolConfigs ?? undefined,
549
550
  grantedDirs: frame.grantedDirs ?? undefined,
@@ -130,6 +130,7 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
130
130
  required: ['prompt']
131
131
  },
132
132
  effect: () => 'write',
133
+ deliversMany: true,
133
134
  resource: (args) => ({
134
135
  kind: 'image-edit',
135
136
  label: String(args.prompt ?? '').slice(0, 80)
@@ -264,13 +265,13 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
264
265
  'Next time write the prompt with explicit @imageN tokens in source order');
265
266
  }
266
267
  return {
267
- attachmentId: record.id,
268
+ attachments: [
269
+ { attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
270
+ ],
268
271
  ...(sources.length === 1 && sources[0].id
269
272
  ? { sourceAttachmentId: sources[0].id }
270
273
  : { sourceFileNames: sources.map((source) => source.fileName) }),
271
274
  note: notes.length ? notes.join('; ') : undefined,
272
- fileName: record.fileName,
273
- byteLength: record.byteLength,
274
275
  width,
275
276
  height
276
277
  };
@@ -19,6 +19,7 @@ export interface StageInputsOptions {
19
19
  export interface StagedInputs {
20
20
  files: readonly StagedInput[];
21
21
  }
22
+ export declare function uploadsAvailable(fetchAttachment: FetchAttachmentFn, { turnImages, signal }?: StageInputsOptions): Promise<number | null>;
22
23
  export declare function stageInputs(fetchAttachment: FetchAttachmentFn, inputs: readonly ExecInput[], opts?: StageInputsOptions): Promise<StagedInputs | ExecError>;
23
24
  export interface AttachOutputsOptions {
24
25
  readonly declared: readonly string[];
@@ -67,6 +67,17 @@ async function probeAttachment(fetchAttachment, id, { signal, deadline }) {
67
67
  }
68
68
  return { size: byteLengthOf(head), bytes: hasBytes(head) ? head.bytes : null };
69
69
  }
70
+ export async function uploadsAvailable(fetchAttachment, { turnImages = [], signal } = {}) {
71
+ if (turnImages.length) {
72
+ return turnImages.length;
73
+ }
74
+ try {
75
+ return (await bounded(fetchAttachment({ meta: true, signal }), STAGE_TIMEOUT_MS)) ? 1 : 0;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
70
81
  export async function stageInputs(fetchAttachment, inputs, opts = {}) {
71
82
  const { turnImages = [], signal } = opts;
72
83
  const files = inputs.map(() => null);
@@ -313,6 +313,7 @@ export function createGenerateImageTool(runtime, clamps) {
313
313
  required: ['prompt']
314
314
  },
315
315
  effect: () => 'read',
316
+ deliversMany: true,
316
317
  resource: (args) => ({
317
318
  kind: 'image-generation',
318
319
  label: String(args.prompt ?? '').slice(0, 80)
@@ -359,9 +360,9 @@ export function createGenerateImageTool(runtime, clamps) {
359
360
  raw: true
360
361
  });
361
362
  return {
362
- attachmentId: record.id,
363
- fileName: record.fileName,
364
- byteLength: record.byteLength,
363
+ attachments: [
364
+ { attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
365
+ ],
365
366
  width: parsed.width,
366
367
  height: parsed.height
367
368
  };
@@ -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;