@qvac/harness 1.0.0-rc.16 → 1.0.0-rc.17

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 (115) hide show
  1. package/CHANGELOG.md +117 -2
  2. package/dist-lib/index.d.ts +6 -2
  3. package/dist-lib/index.js +17 -3
  4. package/dist-lib/lib/capabilities/completion-engine/actors/executing.d.ts +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +28 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +1 -0
  7. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.d.ts +1 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -8
  9. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +6 -3
  10. package/dist-lib/lib/capabilities/completion-engine/actors/run-prepare.js +1 -1
  11. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  12. package/dist-lib/lib/capabilities/completion-engine/durable.d.ts +2 -1
  13. package/dist-lib/lib/capabilities/completion-engine/durable.js +7 -1
  14. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +2 -1
  15. package/dist-lib/lib/capabilities/completion-engine/operations.js +28 -9
  16. package/dist-lib/lib/capabilities/completion-engine/ports.js +3 -2
  17. package/dist-lib/lib/capabilities/completion-engine/prepare-step.d.ts +3 -1
  18. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +1 -0
  19. package/dist-lib/lib/capabilities/completion-engine/session.js +1 -0
  20. package/dist-lib/lib/capabilities/completion-engine/tool-execution.js +2 -1
  21. package/dist-lib/lib/capabilities/completion-engine/turns.js +5 -2
  22. package/dist-lib/lib/capabilities/enhance.js +3 -3
  23. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  24. package/dist-lib/lib/capabilities/sdk-tool.js +3 -2
  25. package/dist-lib/lib/capabilities/skill-entry.d.ts +9 -1
  26. package/dist-lib/lib/capabilities/skill-entry.js +11 -7
  27. package/dist-lib/lib/capabilities/tool-turns.d.ts +5 -0
  28. package/dist-lib/lib/capabilities/tool-turns.js +24 -27
  29. package/dist-lib/lib/client/index.js +3 -2
  30. package/dist-lib/lib/connect.d.ts +2 -0
  31. package/dist-lib/lib/connect.js +33 -3
  32. package/dist-lib/lib/contract/completion.d.ts +14 -0
  33. package/dist-lib/lib/contract/exec.d.ts +1 -0
  34. package/dist-lib/lib/contract/ocr.d.ts +4 -0
  35. package/dist-lib/lib/contract/run.d.ts +8 -0
  36. package/dist-lib/lib/contract-types.d.ts +4 -1
  37. package/dist-lib/lib/guards.d.ts +2 -0
  38. package/dist-lib/lib/guards.js +7 -0
  39. package/dist-lib/lib/hardware/capability-probe.js +10 -7
  40. package/dist-lib/lib/hardware/gpu-probe-addon.js +26 -11
  41. package/dist-lib/lib/hardware/gpu-stats.native.cjs +17 -1
  42. package/dist-lib/lib/helpers/completion-params.d.ts +2 -1
  43. package/dist-lib/lib/helpers/completion-params.js +16 -1
  44. package/dist-lib/lib/helpers/control-tokens.d.ts +3 -0
  45. package/dist-lib/lib/helpers/control-tokens.js +25 -0
  46. package/dist-lib/lib/machine/completion/actions/completion.js +34 -5
  47. package/dist-lib/lib/machine/completion/actions/tools.js +4 -1
  48. package/dist-lib/lib/machine/completion/rules.d.ts +2 -0
  49. package/dist-lib/lib/machine/completion/rules.js +7 -0
  50. package/dist-lib/lib/machine/completion/types.d.ts +6 -0
  51. package/dist-lib/lib/machine/index.d.ts +2 -1
  52. package/dist-lib/lib/machine/index.js +2 -1
  53. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -1
  54. package/dist-lib/lib/no-redirect-fetch-impl.js +13 -7
  55. package/dist-lib/lib/plugins/registry.d.ts +3 -0
  56. package/dist-lib/lib/plugins/registry.js +15 -1
  57. package/dist-lib/lib/plugins/require-bare.d.ts +1 -0
  58. package/dist-lib/lib/plugins/require-bare.js +13 -0
  59. package/dist-lib/lib/run-log/request-codec.js +2 -2
  60. package/dist-lib/lib/serve.js +38 -1
  61. package/dist-lib/lib/sidecar/index.js +2 -1
  62. package/dist-lib/lib/skills-host/index.js +7 -1
  63. package/dist-lib/lib/spawn.d.ts +2 -0
  64. package/dist-lib/lib/spawn.js +5 -3
  65. package/dist-lib/lib/tools/ask-user.d.ts +2 -0
  66. package/dist-lib/lib/tools/ask-user.js +137 -0
  67. package/dist-lib/lib/tools/attachments/delivered.d.ts +5 -0
  68. package/dist-lib/lib/tools/attachments/delivered.js +16 -0
  69. package/dist-lib/lib/tools/attachments/fetched-file.d.ts +32 -0
  70. package/dist-lib/lib/tools/attachments/fetched-file.js +134 -0
  71. package/dist-lib/lib/tools/exec.js +2 -1
  72. package/dist-lib/lib/tools/fs/document-text.js +3 -26
  73. package/dist-lib/lib/tools/http-request/request.d.ts +2 -2
  74. package/dist-lib/lib/tools/http-request/request.js +1 -1
  75. package/dist-lib/lib/tools/http-request.d.ts +1 -0
  76. package/dist-lib/lib/tools/http-request.js +54 -3
  77. package/dist-lib/lib/tools/index.d.ts +2 -1
  78. package/dist-lib/lib/tools/index.js +5 -1
  79. package/dist-lib/lib/tools/office.js +20 -12
  80. package/dist-lib/lib/tools/pdf/pages.d.ts +12 -0
  81. package/dist-lib/lib/tools/pdf/pages.js +28 -0
  82. package/dist-lib/lib/tools/pdf.js +24 -9
  83. package/dist-lib/lib/tools/skills/scope-key.d.ts +1 -0
  84. package/dist-lib/lib/tools/skills/scope-key.js +4 -0
  85. package/dist-lib/lib/tools/web-fetch.js +41 -130
  86. package/dist-lib/plugins/knowledge/index.js +3 -3
  87. package/dist-lib/plugins/mcp/call.js +5 -1
  88. package/dist-lib/plugins/mcp/protocol.d.ts +6 -1
  89. package/dist-lib/plugins/mcp/protocol.js +2 -2
  90. package/dist-lib/plugins/ocr/reading-order.js +151 -4
  91. package/dist-lib/plugins/python/bare-floor.d.ts +1 -0
  92. package/dist-lib/plugins/python/bare-floor.js +2 -0
  93. package/dist-lib/plugins/python/index.d.ts +1 -0
  94. package/dist-lib/plugins/python/index.js +1 -0
  95. package/dist-lib/plugins/python/language.js +9 -8
  96. package/dist-lib/plugins/python/python-adapter.d.ts +4 -0
  97. package/dist-lib/plugins/python/python-adapter.js +26 -0
  98. package/dist-lib/plugins/python/worker/client.js +1 -1
  99. package/dist-lib/plugins/python/worker/entry.js +2 -8
  100. package/dist-lib/plugins/python/worker/preload.d.ts +1 -0
  101. package/dist-lib/plugins/python/worker/preload.js +2 -0
  102. package/dist-lib/plugins/python/worker/spawn.js +1 -1
  103. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  104. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  105. package/dist-lib/plugins/weather/lookup.js +1 -0
  106. package/dist-lib/schema/harness.js +17 -0
  107. package/dist-lib/spec/bind.js +3 -0
  108. package/dist-lib/spec/calls.js +1 -0
  109. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  110. package/dist-lib/spec/hrpc/index.js +15 -3
  111. package/dist-lib/spec/hrpc/messages.js +32 -0
  112. package/dist-lib/spec/hyperschema/index.js +32 -0
  113. package/dist-lib/spec/hyperschema/schema.json +40 -0
  114. package/dist-lib/spec/hyperschema/types.d.ts +12 -0
  115. package/package.json +17 -8
@@ -0,0 +1,137 @@
1
+ import { isRecord } from '../guards.js';
2
+ const FIELD_TYPES = [
3
+ 'single',
4
+ 'multiple',
5
+ 'date',
6
+ 'text',
7
+ 'note',
8
+ 'number'
9
+ ];
10
+ const CHOICE_TYPES = ['single', 'multiple'];
11
+ function fieldType(value) {
12
+ return FIELD_TYPES.find((type) => type === value) ?? null;
13
+ }
14
+ function fieldError(field, seen) {
15
+ if (!isRecord(field) || typeof field.id !== 'string' || !field.id) {
16
+ return 'every field needs an id';
17
+ }
18
+ if (seen.has(field.id)) {
19
+ return `field id ${field.id} is used twice`;
20
+ }
21
+ seen.add(field.id);
22
+ if (typeof field.label !== 'string' || !field.label) {
23
+ return `field ${field.id} needs a label`;
24
+ }
25
+ const type = fieldType(field.type);
26
+ if (!type) {
27
+ return `field ${field.id} has type ${String(field.type)}; use one of ${FIELD_TYPES.join(', ')}`;
28
+ }
29
+ const options = field.options;
30
+ if (CHOICE_TYPES.includes(type) &&
31
+ !(Array.isArray(options) && options.length > 0 && options.every((o) => typeof o === 'string'))) {
32
+ return `field ${field.id} is a ${type} choice and needs options`;
33
+ }
34
+ return null;
35
+ }
36
+ function formError(args) {
37
+ if (typeof args.question !== 'string' || !args.question) {
38
+ return 'question is required';
39
+ }
40
+ if (!Array.isArray(args.fields) || args.fields.length === 0) {
41
+ return 'fields needs at least one field';
42
+ }
43
+ const seen = new Set();
44
+ for (const field of args.fields) {
45
+ const error = fieldError(field, seen);
46
+ if (error) {
47
+ return error;
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+ function formFields(fields) {
53
+ const out = [];
54
+ for (const field of Array.isArray(fields) ? fields : []) {
55
+ const type = isRecord(field) ? fieldType(field.type) : null;
56
+ if (!isRecord(field) || !type) {
57
+ continue;
58
+ }
59
+ out.push({
60
+ id: String(field.id),
61
+ label: String(field.label),
62
+ type,
63
+ options: CHOICE_TYPES.includes(type) && Array.isArray(field.options)
64
+ ? field.options.map(String)
65
+ : undefined,
66
+ required: field.required === true
67
+ });
68
+ }
69
+ return out;
70
+ }
71
+ function answerOf(answer) {
72
+ try {
73
+ const values = JSON.parse(answer);
74
+ if (isRecord(values) && !Array.isArray(values)) {
75
+ return { answers: values };
76
+ }
77
+ }
78
+ catch { }
79
+ return { reply: answer };
80
+ }
81
+ const PARAMETERS = {
82
+ type: 'object',
83
+ properties: {
84
+ question: { type: 'string', description: 'One line on what you need and why' },
85
+ fields: {
86
+ type: 'array',
87
+ items: {
88
+ type: 'object',
89
+ properties: {
90
+ id: { type: 'string', description: 'Key of this answer in the result' },
91
+ label: { type: 'string', description: 'The question the user reads' },
92
+ type: {
93
+ type: 'string',
94
+ enum: [...FIELD_TYPES],
95
+ description: 'single: pick one option; multiple: pick any options; date; text: a short answer; ' +
96
+ 'note: a longer optional comment; number'
97
+ },
98
+ options: {
99
+ type: 'array',
100
+ items: { type: 'string' },
101
+ description: 'The choices, for single and multiple'
102
+ },
103
+ required: { type: 'boolean' }
104
+ },
105
+ required: ['id', 'label', 'type']
106
+ }
107
+ }
108
+ },
109
+ required: ['question', 'fields']
110
+ };
111
+ export function createAskUserTool() {
112
+ return {
113
+ name: 'ask_user',
114
+ toolset: null,
115
+ description: 'Ask the user for details you need before you act, as a short form in the chat. ' +
116
+ 'The run waits for the answers. Ask only what you cannot guess well, all in one form. ' +
117
+ 'The result is the answers by field id, a reply in the user’s own words, or skipped: ' +
118
+ 'then go on with your best guess and say what you assumed.',
119
+ parameters: PARAMETERS,
120
+ effect: () => 'read',
121
+ autoApprove: true,
122
+ validate: formError,
123
+ async execute(args, ctx) {
124
+ if (!ctx?.askUser) {
125
+ return { error: 'This chat cannot show a form; ask in your reply instead.' };
126
+ }
127
+ const answer = await ctx.askUser({
128
+ question: String(args.question),
129
+ form: formFields(args.fields)
130
+ });
131
+ if (answer === null) {
132
+ return { skipped: true, note: 'The user skipped the form; go on with your best guess.' };
133
+ }
134
+ return answerOf(answer);
135
+ }
136
+ };
137
+ }
@@ -0,0 +1,5 @@
1
+ import type { DeliveredFile, RunBudget } from '../../contract/run.ts';
2
+ export declare function sha256(bytes: Uint8Array): string;
3
+ export declare function deliveredFile(budget: RunBudget | undefined, name: string): DeliveredFile | undefined;
4
+ export declare function recordDelivered(budget: RunBudget | undefined, file: DeliveredFile): void;
5
+ export declare function attachmentOf({ attachmentId, fileName, byteLength }: DeliveredFile): Pick<DeliveredFile, 'attachmentId' | 'fileName' | 'byteLength'>;
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'crypto';
2
+ export function sha256(bytes) {
3
+ return createHash('sha256').update(bytes).digest('hex');
4
+ }
5
+ export function deliveredFile(budget, name) {
6
+ const key = name.toLowerCase();
7
+ return budget?.delivered?.find((file) => file.name === key);
8
+ }
9
+ export function recordDelivered(budget, file) {
10
+ if (budget) {
11
+ budget.delivered = [...(budget.delivered ?? []), file];
12
+ }
13
+ }
14
+ export function attachmentOf({ attachmentId, fileName, byteLength }) {
15
+ return { attachmentId, fileName, byteLength };
16
+ }
@@ -0,0 +1,32 @@
1
+ import type { AttachFn, AttachmentRecord } from '../../contract/index.ts';
2
+ export declare const MAX_FILE_BYTES = 100000000;
3
+ export declare function isFileMime(mimeType: string): boolean;
4
+ export declare function bareMime(contentType: string | null | undefined): string;
5
+ export declare function fetchedFileName(url: URL, mimeType: string): string;
6
+ export declare function dispositionFileName(header: string | null | undefined): string | null;
7
+ export interface AttachFetchedFileOptions {
8
+ readonly url: URL;
9
+ readonly mimeType: string;
10
+ readonly attach: AttachFn | undefined;
11
+ readonly maxBytes: number;
12
+ readonly fileName?: string | null | undefined;
13
+ }
14
+ export interface AttachedFile {
15
+ readonly attachmentId: string;
16
+ readonly fileName: string;
17
+ readonly mimeType: string;
18
+ readonly byteLength: number;
19
+ readonly content: string;
20
+ }
21
+ export interface FileRefused {
22
+ readonly error: string;
23
+ }
24
+ export declare function attachFetchedFile(bytes: Uint8Array | undefined, { url, mimeType, attach, maxBytes, fileName }: AttachFetchedFileOptions): Promise<AttachedFile | FileRefused>;
25
+ export interface AttachTextFileOptions {
26
+ readonly url: URL;
27
+ readonly mimeType: string;
28
+ readonly attach: AttachFn | undefined;
29
+ readonly maxBytes: number;
30
+ readonly fileName?: string | null | undefined;
31
+ }
32
+ export declare function attachTextFile(bytes: Uint8Array | undefined, { url, mimeType, attach, maxBytes, fileName }: AttachTextFileOptions): Promise<AttachmentRecord | null>;
@@ -0,0 +1,134 @@
1
+ import b4a from 'b4a';
2
+ import { checkFileName } from './output-policy.js';
3
+ export const MAX_FILE_BYTES = 100_000_000;
4
+ const BINARY_MIME_PREFIXES = ['image/', 'audio/', 'video/', 'font/', 'model/'];
5
+ const TEXT_EXTENSIONS = {
6
+ 'text/plain': 'txt',
7
+ 'text/markdown': 'md'
8
+ };
9
+ const MIME_EXTENSIONS = {
10
+ 'application/pdf': 'pdf',
11
+ 'application/msword': 'doc',
12
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
13
+ 'application/vnd.ms-excel': 'xls',
14
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
15
+ 'application/vnd.ms-powerpoint': 'ppt',
16
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
17
+ 'application/vnd.oasis.opendocument.text': 'odt',
18
+ 'application/vnd.oasis.opendocument.spreadsheet': 'ods',
19
+ 'application/epub+zip': 'epub',
20
+ 'application/zip': 'zip',
21
+ 'application/gzip': 'gz',
22
+ 'image/svg+xml': 'svg',
23
+ 'image/jpeg': 'jpg',
24
+ 'audio/mpeg': 'mp3',
25
+ 'video/quicktime': 'mov',
26
+ 'application/octet-stream': 'bin'
27
+ };
28
+ export function isFileMime(mimeType) {
29
+ if (mimeType in MIME_EXTENSIONS)
30
+ return true;
31
+ return BINARY_MIME_PREFIXES.some((prefix) => mimeType.startsWith(prefix));
32
+ }
33
+ export function bareMime(contentType) {
34
+ return contentType?.split(';')[0]?.trim().toLowerCase() ?? '';
35
+ }
36
+ export function fetchedFileName(url, mimeType) {
37
+ const last = url.pathname.split('/').filter(Boolean).pop() ?? '';
38
+ let decoded = last;
39
+ try {
40
+ decoded = decodeURIComponent(last);
41
+ }
42
+ catch { }
43
+ const base = decoded.split(/[/\\]/).filter(Boolean).pop() ?? '';
44
+ return base ? withExtension(base, mimeType) : `${url.hostname}.${extensionFor(mimeType)}`;
45
+ }
46
+ export function dispositionFileName(header) {
47
+ if (!header)
48
+ return null;
49
+ const extended = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header)?.[1];
50
+ if (extended) {
51
+ try {
52
+ return decodeURIComponent(extended.trim());
53
+ }
54
+ catch { }
55
+ }
56
+ return (/filename\s*=\s*"([^"]*)"/.exec(header)?.[1] ??
57
+ /filename\s*=\s*([^;\s]+)/.exec(header)?.[1] ??
58
+ null);
59
+ }
60
+ export async function attachFetchedFile(bytes, { url, mimeType, attach, maxBytes, fileName }) {
61
+ if (!attach || !bytes || bytes.byteLength === 0) {
62
+ return { error: 'This URL serves a file, not a readable page, and it could not be attached.' };
63
+ }
64
+ if (bytes.byteLength >= maxBytes) {
65
+ return { error: `This file is larger than ${maxBytes / 1_000_000}MB and was not attached.` };
66
+ }
67
+ const mime = isPdf(bytes) ? 'application/pdf' : mimeType || 'application/octet-stream';
68
+ const named = fileName && checkFileName(fileName) === null ? withExtension(fileName, mime) : null;
69
+ const record = await attach({
70
+ fileName: named ?? fetchedFileName(url, mime),
71
+ mimeType: mime,
72
+ bytes,
73
+ raw: !mime.startsWith('image/')
74
+ });
75
+ return {
76
+ attachmentId: record.id,
77
+ fileName: record.fileName,
78
+ mimeType: mime,
79
+ byteLength: record.byteLength,
80
+ content: `Attached the file "${record.fileName}" (${Math.round(record.byteLength / 1024)}KB, ${mime}) from ${url.toString()} — ` +
81
+ 'the user can open or save it. Its contents were NOT read, so do not describe what is inside ' +
82
+ 'yet. To read it, use the skill for its type (pdf for a PDF), or stage it with exec as ' +
83
+ `inputs [{ "attachmentId": "${record.id}", "path": "${record.fileName}" }] — never ask the ` +
84
+ 'user to attach a file this call already attached.'
85
+ };
86
+ }
87
+ function isPdf(bytes) {
88
+ return b4a.toString(bytes.subarray(0, 5), 'latin1') === '%PDF-';
89
+ }
90
+ export async function attachTextFile(bytes, { url, mimeType, attach, maxBytes, fileName }) {
91
+ if (!attach || !bytes || bytes.byteLength === 0 || bytes.byteLength >= maxBytes) {
92
+ return null;
93
+ }
94
+ const mime = mimeType || 'text/plain';
95
+ const named = fileName && checkFileName(fileName) === null ? withExtension(fileName, mime) : null;
96
+ try {
97
+ return await attach({
98
+ fileName: named ?? fetchedFileName(url, mime),
99
+ mimeType: mime,
100
+ bytes,
101
+ raw: true
102
+ });
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }
108
+ function withExtension(base, mimeType) {
109
+ const extension = /\.([\w-]{1,8})$/.exec(base)?.[1]?.toLowerCase() ?? '';
110
+ if (extension && acceptableExtensions(mimeType).has(extension)) {
111
+ return base;
112
+ }
113
+ const trustsName = mimeType === 'application/octet-stream' || !isFileMime(mimeType);
114
+ if (trustsName && /^[a-z][\w-]*$/.test(extension)) {
115
+ return base;
116
+ }
117
+ return `${base}.${extensionFor(mimeType)}`;
118
+ }
119
+ function acceptableExtensions(mimeType) {
120
+ const accepted = new Set([extensionFor(mimeType)]);
121
+ const subtype = mimeType.split('/')[1] ?? '';
122
+ if (/^[a-z0-9]{1,8}$/.test(subtype)) {
123
+ accepted.add(subtype);
124
+ }
125
+ return accepted;
126
+ }
127
+ function extensionFor(mimeType) {
128
+ const known = MIME_EXTENSIONS[mimeType] ?? TEXT_EXTENSIONS[mimeType];
129
+ if (known) {
130
+ return known;
131
+ }
132
+ const subtype = mimeType.split('/')[1] ?? '';
133
+ return /^[a-z0-9]{1,5}$/.test(subtype) ? subtype : 'bin';
134
+ }
@@ -319,7 +319,8 @@ export function createExecTool({ policyVersion, spawn, killProcess, shell: compo
319
319
  return language.validate(rawArgs, {
320
320
  sandbox,
321
321
  trusted: run.trusted,
322
- toolNames: ctx?.toolNames
322
+ toolNames: ctx?.toolNames,
323
+ offeredTools: ctx?.offeredTools
323
324
  });
324
325
  }
325
326
  return firstAnswer(languages, (each) => each.strays(rawArgs)) ?? shellStray(rawArgs);
@@ -1,11 +1,5 @@
1
- import { HarnessError } from '../../errors.js';
2
1
  import { docx, pptx } from '../../office/engine/index.js';
3
- import { recognizePages } from '../pdf/recognize.js';
4
- let pdfium = null;
5
- function loadPdfium() {
6
- pdfium ??= import('bare-pdfium').then((loaded) => loaded, () => null);
7
- return pdfium;
8
- }
2
+ import { pdfPages } from '../pdf/pages.js';
9
3
  export function isDocument(key) {
10
4
  return /\.(pdf|docx|pptx)$/i.test(key);
11
5
  }
@@ -14,25 +8,8 @@ export async function documentText(key, bytes, { ocr, signal } = {}) {
14
8
  const read = /\.docx$/i.test(key) ? docx.open(bytes).read() : pptx.open(bytes).read();
15
9
  return collectText(read).join('\n');
16
10
  }
17
- const lib = await loadPdfium();
18
- if (!lib) {
19
- throw new HarnessError('PDF_TEXT_UNAVAILABLE');
20
- }
21
- const doc = lib.open(bytes);
22
- try {
23
- const recognized = ocr
24
- ? (await recognizePages({ doc, bytes }, { ocr, signal })).pages
25
- : undefined;
26
- return [...doc.textPages()]
27
- .map(({ page, text }) => {
28
- const read = recognized?.get(page) ?? text;
29
- return `--- page ${page + 1} ---\n${read.replace(/\r\n?/g, '\n').trim()}`;
30
- })
31
- .join('\n');
32
- }
33
- finally {
34
- doc.close();
35
- }
11
+ const pages = await pdfPages(bytes, { ocr, signal });
12
+ return pages.map(({ page, text }) => `--- page ${page} ---\n${text}`).join('\n');
36
13
  }
37
14
  function collectText(value) {
38
15
  if (Array.isArray(value)) {
@@ -1,7 +1,7 @@
1
1
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  export declare const MAX_RESPONSE_CHARS = 8192;
3
3
  export declare const IDLE_TIMEOUT_MS = 10000;
4
- export declare const TIMEOUT_MS = 30000;
4
+ export declare const TIMEOUT_MS = 120000;
5
5
  export interface FetchInit {
6
6
  method: string;
7
7
  headers: Record<string, string>;
@@ -9,7 +9,7 @@ export interface FetchInit {
9
9
  signal: BareAbortSignal;
10
10
  redirect?: 'manual';
11
11
  validatedAddresses?: readonly string[] | undefined;
12
- maxBytes?: number;
12
+ maxBytes?: number | ((contentType: string) => number);
13
13
  truncate?: boolean;
14
14
  idleTimeoutMs?: number;
15
15
  }
@@ -2,7 +2,7 @@ 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
4
  export const IDLE_TIMEOUT_MS = 10_000;
5
- export const TIMEOUT_MS = 30_000;
5
+ export const TIMEOUT_MS = 120_000;
6
6
  export function isRedirectStatus(status) {
7
7
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
8
8
  }
@@ -1,3 +1,4 @@
1
+ import { URL } from 'url';
1
2
  import type { ToolDefinition } from '../contract/index.ts';
2
3
  import { type FetchInit } from './http-request/request.ts';
3
4
  import { type CredentialAllowListFn, type CredentialStoreFn } from './skills/auth-resolver.ts';
@@ -1,5 +1,6 @@
1
1
  import { noRedirectFetch } from '#no-redirect-fetch';
2
2
  import { AbortController } from 'bare-abort-controller';
3
+ import { URL } from 'url';
3
4
  import { lookupHost } from '../dns-lookup.js';
4
5
  import { READ_METHODS } from './http-methods.js';
5
6
  import { encodeDeclaredFields } from './http-request/encode-fields.js';
@@ -9,6 +10,7 @@ import { applyQuery, buildHeaders, contentTypeOf, encodeBody, isRedirectStatus,
9
10
  import { parseAuth, resolveBearerHeader, resolveRedirectBearerHeader } from './skills/auth-resolver.js';
10
11
  import { recordCredentialHealth } from './skills/credential-health.js';
11
12
  import { Policy } from '../policy/index.js';
13
+ import { attachFetchedFile, attachTextFile, bareMime, dispositionFileName, isFileMime, MAX_FILE_BYTES } from './attachments/fetched-file.js';
12
14
  import { resolveOutboundUrl } from './url-guard.js';
13
15
  const MAX_REDIRECTS = 5;
14
16
  export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credentialStore, credentialAllowList, resolveHost = lookupHost } = {}) {
@@ -17,7 +19,7 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
17
19
  policyVersion,
18
20
  toolset: 'http-request',
19
21
  defer: true,
20
- 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.',
22
+ 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. A response that is a file — PDF, .docx, .xlsx, an image, audio, video, any binary — is attached to the chat instead of returned as text: the result carries its attachmentId, and `fileName` names it.',
21
23
  parameters: {
22
24
  type: 'object',
23
25
  properties: {
@@ -43,6 +45,10 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
43
45
  auth: {
44
46
  type: 'object',
45
47
  description: 'Optional bearer auth: {"type": "bearer", "tokenCredentialKey": "<key>"}. Pass ONLY the credential key name — NEVER a token value. The tool resolves the actual secret itself; the model never sees it.'
48
+ },
49
+ fileName: {
50
+ type: 'string',
51
+ description: 'Optional. The name to attach a file response under, e.g. "report.pdf"'
46
52
  }
47
53
  },
48
54
  required: ['url']
@@ -103,6 +109,9 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
103
109
  if (!auth.ok) {
104
110
  return { error: auth.error };
105
111
  }
112
+ if (args.fileName !== undefined && typeof args.fileName !== 'string') {
113
+ return { error: 'fileName must be a string' };
114
+ }
106
115
  const hosts = Policy.hostsOf(ctx?.policy);
107
116
  const controller = new AbortController();
108
117
  let timedOut = false;
@@ -159,7 +168,9 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
159
168
  signal: controller.signal,
160
169
  redirect: 'manual',
161
170
  validatedAddresses,
162
- idleTimeoutMs: IDLE_TIMEOUT_MS
171
+ idleTimeoutMs: IDLE_TIMEOUT_MS,
172
+ maxBytes: MAX_FILE_BYTES,
173
+ truncate: true
163
174
  });
164
175
  if (credentialKey) {
165
176
  recordCredentialHealth(credentialKey, response.status, ctx?.agentId);
@@ -203,13 +214,47 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
203
214
  header = next.header;
204
215
  credentialKey = next.credentialKey;
205
216
  }
217
+ const mimeType = bareMime(response.headers?.get('content-type'));
218
+ if (ctx?.attach && isSuccess(response.status) && isFileMime(mimeType)) {
219
+ const attached = await attachFetchedFile(await response.bytes?.(), {
220
+ url: currentUrl,
221
+ mimeType,
222
+ attach: ctx.attach,
223
+ maxBytes: MAX_FILE_BYTES,
224
+ fileName: args.fileName ?? dispositionFileName(response.headers?.get('content-disposition'))
225
+ });
226
+ if ('error' in attached) {
227
+ return attached;
228
+ }
229
+ const { content, ...file } = attached;
230
+ return { status: response.status, ...file, body: content };
231
+ }
206
232
  const text = await response.text();
207
233
  if (ctx?.uncappedResponse) {
208
234
  return { status: response.status, body: text };
209
235
  }
236
+ const capped = capResponseBody(text, ctx);
237
+ const whole = capped.truncated && isSuccess(response.status) && isTextFile(mimeType, args.fileName)
238
+ ? await attachTextFile(await response.bytes?.(), {
239
+ url: currentUrl,
240
+ mimeType,
241
+ attach: ctx?.attach,
242
+ maxBytes: MAX_FILE_BYTES,
243
+ fileName: args.fileName ?? dispositionFileName(response.headers?.get('content-disposition'))
244
+ })
245
+ : null;
246
+ if (!whole || !capped.truncated) {
247
+ return { status: response.status, ...capped };
248
+ }
210
249
  return {
211
250
  status: response.status,
212
- ...capResponseBody(text, ctx)
251
+ body: capped.body,
252
+ attachmentId: whole.id,
253
+ fileName: whole.fileName,
254
+ truncated: {
255
+ ...capped.truncated,
256
+ note: `${capped.truncated.note} The whole file is attached as "${whole.fileName}": stage it with exec as inputs [{ "attachmentId": "${whole.id}", "path": "${whole.fileName}" }] to read or search past the cut.`
257
+ }
213
258
  };
214
259
  }
215
260
  catch (err) {
@@ -229,3 +274,9 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
229
274
  }
230
275
  };
231
276
  }
277
+ function isTextFile(mimeType, fileName) {
278
+ return fileName !== undefined || (mimeType.startsWith('text/') && mimeType !== 'text/html');
279
+ }
280
+ function isSuccess(status) {
281
+ return status >= 200 && status < 300;
282
+ }
@@ -12,11 +12,12 @@ export interface ProductToolsOptions {
12
12
  readonly skillCatalog?: readonly SkillCatalogEntry[] | undefined;
13
13
  readonly credentialStore?: CredentialStoreFn | undefined;
14
14
  readonly files?: boolean | undefined;
15
+ readonly ask?: boolean | undefined;
15
16
  }
16
17
  export declare class Tools {
17
18
  static deniedRoots: typeof deniedRootsFor;
18
19
  static bundledSkillsDir: typeof ensureBundledSkillsDir;
19
20
  static stageInputs: typeof stageInputs;
20
21
  static operations: typeof compileOperationTools;
21
- static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files }: ProductToolsOptions): ToolDefinition[];
22
+ static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files, ask }: ProductToolsOptions): ToolDefinition[];
22
23
  }
@@ -1,3 +1,4 @@
1
+ import { createAskUserTool } from './ask-user.js';
1
2
  import { createFileTools } from './files/index.js';
2
3
  import { deniedRootsFor } from './fs/scope.js';
3
4
  import { createHttpRequestTool } from './http-request.js';
@@ -14,7 +15,7 @@ export class Tools {
14
15
  static bundledSkillsDir = ensureBundledSkillsDir;
15
16
  static stageInputs = stageInputs;
16
17
  static operations = compileOperationTools;
17
- static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files = true }) {
18
+ static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files = true, ask = false }) {
18
19
  const deniedRoots = deniedRootsFor(sdkHome);
19
20
  const credentialed = skillCatalog
20
21
  ? { credentialStore, credentialAllowList: credentialAllowListFor(skillCatalog) }
@@ -33,6 +34,9 @@ export class Tools {
33
34
  if (skillsDir) {
34
35
  tools.push(createSkillTool({ skillsDir }));
35
36
  }
37
+ if (ask) {
38
+ tools.push(createAskUserTool());
39
+ }
36
40
  return tools;
37
41
  }
38
42
  }
@@ -1,12 +1,11 @@
1
- import b4a from 'b4a';
2
1
  import { HarnessError } from '../errors.js';
3
2
  import { errorMessage, isRecord } from '../guards.js';
4
3
  import { DocsError, docx, pptx, units, xlsx } from '../office/engine/index.js';
5
4
  import { stageInputs, uploadsAvailable } from './attachments/staging.js';
6
5
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './attachments/output-policy.js';
6
+ import { attachmentOf, deliveredFile, recordDelivered, sha256 } from './attachments/delivered.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;
9
- const attachedThisTurn = new WeakMap();
10
9
  const FIRST_SHEET = /^sheet ?1$/i;
11
10
  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
11
  const SHAPE_ROLES = new Set(['title', 'subtitle', 'body']);
@@ -466,22 +465,22 @@ async function attachOutput(job, ctx) {
466
465
  return { error: refused ?? 'nothing to save' };
467
466
  }
468
467
  const { output, document } = job;
469
- const delivered = attachedThisTurn.get(ctx.attach) ?? new Map();
470
- const earlier = delivered.get(output.toLowerCase());
468
+ const budget = ctx.runBudget;
469
+ const earlier = deliveredFile(budget, output);
471
470
  const bytes = document.save();
472
- if (earlier && b4a.equals(earlier.bytes, bytes)) {
473
- return { attachment: earlier.attachment, repeated: true };
471
+ const hash = sha256(bytes);
472
+ if (earlier?.sha256 === hash) {
473
+ return { attachment: attachmentOf(earlier), repeated: true };
474
474
  }
475
475
  if (earlier) {
476
476
  return {
477
- error: `${earlier.attachment.fileName} is already attached with different content; save this version under a new name in output`
477
+ error: `${earlier.fileName} is already attached with different content; save this version under a new name in output`
478
478
  };
479
479
  }
480
480
  const verdict = checkOutputBytes(output, bytes, 0);
481
481
  if ('error' in verdict) {
482
482
  return verdict;
483
483
  }
484
- const budget = ctx.runBudget;
485
484
  if (budget && budget.outputBytesUsed + bytes.byteLength > RUN_OUTPUT_BUDGET_BYTES) {
486
485
  return { error: 'run output budget exceeded' };
487
486
  }
@@ -499,8 +498,7 @@ async function attachOutput(job, ctx) {
499
498
  fileName: record.fileName,
500
499
  byteLength: record.byteLength
501
500
  };
502
- delivered.set(output.toLowerCase(), { attachment, bytes });
503
- attachedThisTurn.set(ctx.attach, delivered);
501
+ recordDelivered(budget, { name: output.toLowerCase(), sha256: hash, ...attachment });
504
502
  return { attachment, repeated: false };
505
503
  }
506
504
  function runOp(document, op, input) {
@@ -650,7 +648,7 @@ async function execute(format, args, ctx) {
650
648
  const renamed = fileName !== null && output !== request.output
651
649
  ? `Saved as ${output}, so the attached ${fileName} keeps its own name. `
652
650
  : '';
653
- const unplaced = !!ctx.turnImages?.length && !images.size;
651
+ const unplaced = images.size ? null : await leftOutImage(request, ctx);
654
652
  return {
655
653
  results,
656
654
  attachments: [attachment],
@@ -662,12 +660,22 @@ async function execute(format, args, ctx) {
662
660
  afterSave(format, attachment.attachmentId, unplaced)
663
661
  };
664
662
  }
663
+ async function leftOutImage(request, ctx) {
664
+ if (ctx.turnImages?.length) {
665
+ return 'The image the user attached to their message';
666
+ }
667
+ if (request.attachmentId !== undefined || !ctx.fetchAttachment) {
668
+ return null;
669
+ }
670
+ const available = await uploadsAvailable(ctx.fetchAttachment, { signal: ctx.signal });
671
+ return available ? 'An image in this chat' : null;
672
+ }
665
673
  function afterSave(format, attachmentId, unplaced) {
666
674
  const reply = 'Your answer is the reply value alone, word for word.';
667
675
  if (!unplaced) {
668
676
  return `Do not call ${format.name} again for it. ${reply}`;
669
677
  }
670
- return (`The image the user attached to their message is not in it. If they asked for that image in the ${format.noun}, ` +
678
+ return (`${unplaced} is not in it. If they asked for that image in the ${format.noun}, ` +
671
679
  `call ${format.name} once more with attachmentId "${attachmentId}" and one op that adds it with "image": {}. ` +
672
680
  `Otherwise: ${reply}`);
673
681
  }