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

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 (125) hide show
  1. package/CHANGELOG.md +139 -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/errors.d.ts +4 -0
  38. package/dist-lib/lib/errors.js +5 -1
  39. package/dist-lib/lib/guards.d.ts +2 -0
  40. package/dist-lib/lib/guards.js +7 -0
  41. package/dist-lib/lib/hardware/capability-probe.js +10 -7
  42. package/dist-lib/lib/hardware/gpu-probe-addon.js +26 -11
  43. package/dist-lib/lib/hardware/gpu-stats.native.cjs +17 -1
  44. package/dist-lib/lib/helpers/completion-params.d.ts +2 -1
  45. package/dist-lib/lib/helpers/completion-params.js +16 -1
  46. package/dist-lib/lib/helpers/control-tokens.d.ts +3 -0
  47. package/dist-lib/lib/helpers/control-tokens.js +25 -0
  48. package/dist-lib/lib/machine/completion/actions/completion.js +34 -5
  49. package/dist-lib/lib/machine/completion/actions/tools.js +4 -1
  50. package/dist-lib/lib/machine/completion/rules.d.ts +2 -0
  51. package/dist-lib/lib/machine/completion/rules.js +7 -0
  52. package/dist-lib/lib/machine/completion/types.d.ts +6 -0
  53. package/dist-lib/lib/machine/index.d.ts +2 -1
  54. package/dist-lib/lib/machine/index.js +2 -1
  55. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -1
  56. package/dist-lib/lib/no-redirect-fetch-impl.js +13 -7
  57. package/dist-lib/lib/office/engine/xlsx/sheet.js +10 -4
  58. package/dist-lib/lib/plugins/registry.d.ts +3 -0
  59. package/dist-lib/lib/plugins/registry.js +15 -1
  60. package/dist-lib/lib/plugins/require-bare.d.ts +1 -0
  61. package/dist-lib/lib/plugins/require-bare.js +13 -0
  62. package/dist-lib/lib/run-log/request-codec.js +2 -2
  63. package/dist-lib/lib/serve.js +38 -1
  64. package/dist-lib/lib/sidecar/index.d.ts +1 -1
  65. package/dist-lib/lib/sidecar/index.js +5 -6
  66. package/dist-lib/lib/skills-host/index.js +13 -8
  67. package/dist-lib/lib/spawn.d.ts +2 -0
  68. package/dist-lib/lib/spawn.js +5 -3
  69. package/dist-lib/lib/tools/ask-user.d.ts +2 -0
  70. package/dist-lib/lib/tools/ask-user.js +137 -0
  71. package/dist-lib/lib/tools/attachments/delivered.d.ts +5 -0
  72. package/dist-lib/lib/tools/attachments/delivered.js +16 -0
  73. package/dist-lib/lib/tools/attachments/fetched-file.d.ts +32 -0
  74. package/dist-lib/lib/tools/attachments/fetched-file.js +134 -0
  75. package/dist-lib/lib/tools/exec.js +2 -1
  76. package/dist-lib/lib/tools/fs/document-text.js +3 -26
  77. package/dist-lib/lib/tools/http-request/request.d.ts +2 -2
  78. package/dist-lib/lib/tools/http-request/request.js +1 -1
  79. package/dist-lib/lib/tools/http-request.d.ts +1 -0
  80. package/dist-lib/lib/tools/http-request.js +54 -3
  81. package/dist-lib/lib/tools/index.d.ts +3 -1
  82. package/dist-lib/lib/tools/index.js +6 -2
  83. package/dist-lib/lib/tools/office.js +20 -12
  84. package/dist-lib/lib/tools/pdf/pages.d.ts +12 -0
  85. package/dist-lib/lib/tools/pdf/pages.js +28 -0
  86. package/dist-lib/lib/tools/pdf.js +24 -9
  87. package/dist-lib/lib/tools/skills/bundled-dir.d.ts +5 -1
  88. package/dist-lib/lib/tools/skills/bundled-dir.js +23 -20
  89. package/dist-lib/lib/tools/skills/catalog.d.ts +1 -1
  90. package/dist-lib/lib/tools/skills/catalog.js +1 -1
  91. package/dist-lib/lib/tools/skills/overlay-crud.d.ts +3 -3
  92. package/dist-lib/lib/tools/skills/overlay-crud.js +4 -4
  93. package/dist-lib/lib/tools/skills/scope-key.d.ts +1 -0
  94. package/dist-lib/lib/tools/skills/scope-key.js +4 -0
  95. package/dist-lib/lib/tools/web-fetch.js +41 -130
  96. package/dist-lib/plugins/knowledge/index.js +3 -3
  97. package/dist-lib/plugins/mcp/call.js +5 -1
  98. package/dist-lib/plugins/mcp/protocol.d.ts +6 -1
  99. package/dist-lib/plugins/mcp/protocol.js +2 -2
  100. package/dist-lib/plugins/ocr/reading-order.js +151 -4
  101. package/dist-lib/plugins/python/bare-floor.d.ts +1 -0
  102. package/dist-lib/plugins/python/bare-floor.js +2 -0
  103. package/dist-lib/plugins/python/index.d.ts +1 -0
  104. package/dist-lib/plugins/python/index.js +1 -0
  105. package/dist-lib/plugins/python/language.js +9 -8
  106. package/dist-lib/plugins/python/python-adapter.d.ts +4 -0
  107. package/dist-lib/plugins/python/python-adapter.js +26 -0
  108. package/dist-lib/plugins/python/worker/client.js +1 -1
  109. package/dist-lib/plugins/python/worker/entry.js +2 -8
  110. package/dist-lib/plugins/python/worker/preload.d.ts +1 -0
  111. package/dist-lib/plugins/python/worker/preload.js +2 -0
  112. package/dist-lib/plugins/python/worker/spawn.js +1 -1
  113. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  114. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  115. package/dist-lib/plugins/weather/lookup.js +1 -0
  116. package/dist-lib/schema/harness.js +17 -0
  117. package/dist-lib/spec/bind.js +3 -0
  118. package/dist-lib/spec/calls.js +1 -0
  119. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  120. package/dist-lib/spec/hrpc/index.js +15 -3
  121. package/dist-lib/spec/hrpc/messages.js +32 -0
  122. package/dist-lib/spec/hyperschema/index.js +32 -0
  123. package/dist-lib/spec/hyperschema/schema.json +40 -0
  124. package/dist-lib/spec/hyperschema/types.d.ts +12 -0
  125. package/package.json +18 -9
@@ -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
+ }
@@ -6,17 +6,19 @@ import type { CredentialStoreFn } from './skills/auth-resolver.ts';
6
6
  import { ensureBundledSkillsDir } from './skills/bundled-dir.ts';
7
7
  import type { SkillCatalogEntry } from './skills/catalog.ts';
8
8
  export type { ExecInput } from './attachments/staging.ts';
9
+ export type { SkillsBundle } from './skills/bundled-dir.ts';
9
10
  export interface ProductToolsOptions {
10
11
  readonly sdkHome: string;
11
12
  readonly skillsDir?: string | undefined;
12
13
  readonly skillCatalog?: readonly SkillCatalogEntry[] | undefined;
13
14
  readonly credentialStore?: CredentialStoreFn | undefined;
14
15
  readonly files?: boolean | undefined;
16
+ readonly ask?: boolean | undefined;
15
17
  }
16
18
  export declare class Tools {
17
19
  static deniedRoots: typeof deniedRootsFor;
18
20
  static bundledSkillsDir: typeof ensureBundledSkillsDir;
19
21
  static stageInputs: typeof stageInputs;
20
22
  static operations: typeof compileOperationTools;
21
- static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files }: ProductToolsOptions): ToolDefinition[];
23
+ static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files, ask }: ProductToolsOptions): ToolDefinition[];
22
24
  }
@@ -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) }
@@ -30,9 +31,12 @@ export class Tools {
30
31
  if (skillCatalog) {
31
32
  tools.push(...compileOperationTools(skillCatalog, { httpRequestTool }));
32
33
  }
33
- if (skillsDir) {
34
+ if (skillsDir || skillCatalog?.length) {
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
  }
@@ -0,0 +1,12 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { OcrService } from '../../contract/ocr.ts';
3
+ export interface PdfPage {
4
+ readonly page: number;
5
+ readonly text: string;
6
+ readonly unread: boolean;
7
+ }
8
+ export interface PdfPagesOptions {
9
+ readonly ocr?: OcrService | undefined;
10
+ readonly signal?: BareAbortSignal | undefined;
11
+ }
12
+ export declare function pdfPages(bytes: Uint8Array, { ocr, signal }?: PdfPagesOptions): Promise<PdfPage[]>;
@@ -0,0 +1,28 @@
1
+ import { HarnessError } from '../../errors.js';
2
+ import { cleanText } from './build.js';
3
+ import { recognizePages } from './recognize.js';
4
+ let pdfium = null;
5
+ function loadPdfium() {
6
+ pdfium ??= import('bare-pdfium').then((loaded) => loaded, () => null);
7
+ return pdfium;
8
+ }
9
+ export async function pdfPages(bytes, { ocr, signal } = {}) {
10
+ const lib = await loadPdfium();
11
+ if (!lib) {
12
+ throw new HarnessError('PDF_TEXT_UNAVAILABLE');
13
+ }
14
+ const doc = lib.open(bytes);
15
+ try {
16
+ const recognized = ocr
17
+ ? (await recognizePages({ doc, bytes }, { ocr, signal })).pages
18
+ : undefined;
19
+ return [...doc.textPages()].map(({ page, text }) => {
20
+ const read = recognized?.get(page) ?? cleanText(text);
21
+ const unread = !read && !recognized?.has(page) && doc.pageFlags(page).hasImage;
22
+ return { page: page + 1, text: read, unread };
23
+ });
24
+ }
25
+ finally {
26
+ doc.close();
27
+ }
28
+ }
@@ -1,5 +1,7 @@
1
+ import b4a from 'b4a';
1
2
  import { errorCode, errorMessage } from '../guards.js';
2
3
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './attachments/output-policy.js';
4
+ import { attachmentOf, deliveredFile, recordDelivered, sha256 } from './attachments/delivered.js';
3
5
  import { build, pagesLabel, everyPageShown, readDocs, READ_TEXT_LIMIT, shownNote, textless } from './pdf/build.js';
4
6
  import { placeImages } from './pdf/images.js';
5
7
  import { recognizePages } from './pdf/recognize.js';
@@ -17,7 +19,6 @@ const SUFFIXES = {
17
19
  text: 'text',
18
20
  read: 'copy'
19
21
  };
20
- const attachedThisTurn = new WeakMap();
21
22
  let loaded = null;
22
23
  function loadPdfium() {
23
24
  loaded ??= import('bare-pdfium').then((pdfium) => pdfium, () => null);
@@ -103,20 +104,35 @@ function openAll(pdfium, sources, request) {
103
104
  }
104
105
  return { opened, error: null };
105
106
  }
106
- async function attachOutput(fileName, bytes, ctx) {
107
+ function madeFrom({ request, opened }) {
108
+ const sources = opened.map(({ source }) => sha256(source.bytes));
109
+ const made = JSON.stringify({ ...request, output: undefined, sources }, sortedKeys);
110
+ return sha256(b4a.from(made));
111
+ }
112
+ function sortedKeys(_key, value) {
113
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
114
+ return value;
115
+ }
116
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)));
117
+ }
118
+ async function attachOutput(fileName, { bytes, hash }, ctx) {
107
119
  if (!ctx.attach) {
108
120
  return { error: 'this device cannot attach a file to the chat' };
109
121
  }
110
- const delivered = attachedThisTurn.get(ctx.attach) ?? new Map();
111
- const earlier = delivered.get(fileName.toLowerCase());
122
+ const budget = ctx.runBudget;
123
+ const earlier = deliveredFile(budget, fileName);
124
+ if (earlier?.sha256 === hash) {
125
+ return { attachment: attachmentOf(earlier), repeated: true };
126
+ }
112
127
  if (earlier) {
113
- return { attachment: earlier, repeated: true };
128
+ return {
129
+ error: `${earlier.fileName} is already attached with different content; save this version under a new name in output`
130
+ };
114
131
  }
115
132
  const verdict = checkOutputBytes(fileName, bytes, 0);
116
133
  if ('error' in verdict) {
117
134
  return verdict;
118
135
  }
119
- const budget = ctx.runBudget;
120
136
  if (budget && budget.outputBytesUsed + bytes.byteLength > RUN_OUTPUT_BUDGET_BYTES) {
121
137
  return { error: 'run output budget exceeded' };
122
138
  }
@@ -129,8 +145,7 @@ async function attachOutput(fileName, bytes, ctx) {
129
145
  fileName: record.fileName,
130
146
  byteLength: record.byteLength
131
147
  };
132
- delivered.set(fileName.toLowerCase(), attachment);
133
- attachedThisTurn.set(ctx.attach, delivered);
148
+ recordDelivered(budget, { name: fileName.toLowerCase(), sha256: hash, ...attachment });
134
149
  return { attachment, repeated: false };
135
150
  }
136
151
  const UNDRAWABLE = /^('[^']+' \(U\+[0-9A-F]+\)(?:, '[^']+' \(U\+[0-9A-F]+\))*) cannot be drawn by the built-in fonts/;
@@ -179,7 +194,7 @@ async function deliver(job, ctx) {
179
194
  if (typeof built === 'string') {
180
195
  return { error: built };
181
196
  }
182
- const delivered = await attachOutput(output, built.bytes, ctx);
197
+ const delivered = await attachOutput(output, { bytes: built.bytes, hash: madeFrom(job) }, ctx);
183
198
  return 'error' in delivered ? delivered : reply(request, { output, built, delivered });
184
199
  }
185
200
  function isLocked(pdfium, source) {
@@ -1,2 +1,6 @@
1
- export declare function ensureBundledSkillsDir(): Promise<string>;
1
+ export interface SkillsBundle {
2
+ readonly skills: Readonly<Record<string, string>>;
3
+ readonly hash: string;
4
+ }
5
+ export declare function ensureBundledSkillsDir(bundle: SkillsBundle): Promise<string>;
2
6
  export declare function randomSuffix(): string;
@@ -5,18 +5,21 @@ import process from 'process';
5
5
  import { HarnessError } from '../../errors.js';
6
6
  import { userTmpPath } from '../../tmp-path.js';
7
7
  import { hashBundledSkills } from './bundled-hash.js';
8
- import { SKILLS as BUNDLED_SKILLS } from '@qvac/skills/bundled';
9
- import { SKILLS_HASH as BUNDLED_SKILLS_HASH } from '@qvac/skills/hash';
10
- let inflight = null;
11
- export function ensureBundledSkillsDir() {
12
- inflight ??= materialize().finally(() => {
13
- inflight = null;
14
- });
15
- return inflight;
8
+ const inflight = new Map();
9
+ export function ensureBundledSkillsDir(bundle) {
10
+ if (!/^[0-9a-f]{16}$/.test(bundle.hash)) {
11
+ return Promise.reject(new HarnessError('BUNDLED_SKILLS_HASH_INVALID', [bundle.hash]));
12
+ }
13
+ let pending = inflight.get(bundle.hash);
14
+ if (!pending) {
15
+ pending = materialize(bundle).finally(() => inflight.delete(bundle.hash));
16
+ inflight.set(bundle.hash, pending);
17
+ }
18
+ return pending;
16
19
  }
17
- async function materialize() {
18
- const dir = userTmpPath('qvac-harness-skills-' + BUNDLED_SKILLS_HASH);
19
- if (await validTree(dir)) {
20
+ async function materialize(bundle) {
21
+ const dir = userTmpPath('qvac-harness-skills-' + bundle.hash);
22
+ if (await validTree(dir, bundle.hash)) {
20
23
  return dir;
21
24
  }
22
25
  const staging = `${dir}-staging-${process.pid}-${randomSuffix()}`;
@@ -25,14 +28,14 @@ async function materialize() {
25
28
  await fs.promises.chmod(staging, 0o700);
26
29
  }
27
30
  try {
28
- await writeTree(staging);
29
- if (!(await validTree(staging))) {
31
+ await writeTree(staging, bundle.skills);
32
+ if (!(await validTree(staging, bundle.hash))) {
30
33
  throw new HarnessError('BUNDLED_SKILLS_INVALID', [staging]);
31
34
  }
32
35
  if (await tryRename(staging, dir)) {
33
36
  return dir;
34
37
  }
35
- if (await validTree(dir)) {
38
+ if (await validTree(dir, bundle.hash)) {
36
39
  return dir;
37
40
  }
38
41
  const trash = `${dir}.trash-${process.pid}-${randomSuffix()}`;
@@ -40,7 +43,7 @@ async function materialize() {
40
43
  await fs.promises.rename(dir, trash);
41
44
  }
42
45
  catch (err) {
43
- if (await validTree(dir)) {
46
+ if (await validTree(dir, bundle.hash)) {
44
47
  return dir;
45
48
  }
46
49
  throw occupiedError(dir, err);
@@ -49,7 +52,7 @@ async function materialize() {
49
52
  if (await tryRename(staging, dir)) {
50
53
  return dir;
51
54
  }
52
- if (await validTree(dir)) {
55
+ if (await validTree(dir, bundle.hash)) {
53
56
  return dir;
54
57
  }
55
58
  throw tamperError(dir);
@@ -77,14 +80,14 @@ async function tryRename(from, to) {
77
80
  return false;
78
81
  }
79
82
  }
80
- async function writeTree(dir) {
81
- for (const [relPath, content] of Object.entries(BUNDLED_SKILLS)) {
83
+ async function writeTree(dir, skills) {
84
+ for (const [relPath, content] of Object.entries(skills)) {
82
85
  const target = path.join(dir, relPath);
83
86
  await fs.promises.mkdir(path.dirname(target), { recursive: true });
84
87
  await fs.promises.writeFile(target, content);
85
88
  }
86
89
  }
87
- async function validTree(dir) {
90
+ async function validTree(dir, hash) {
88
91
  try {
89
92
  if (os.platform() !== 'win32') {
90
93
  const stat = await fs.promises.lstat(dir);
@@ -96,7 +99,7 @@ async function validTree(dir) {
96
99
  if (files === null) {
97
100
  return false;
98
101
  }
99
- return hashBundledSkills(files) === BUNDLED_SKILLS_HASH;
102
+ return hashBundledSkills(files) === hash;
100
103
  }
101
104
  catch {
102
105
  return false;
@@ -66,6 +66,6 @@ export interface LoadSkillCatalogOptions {
66
66
  platform?: string | null;
67
67
  overlayDir?: string | null;
68
68
  }
69
- export declare function loadSkillCatalog(skillsDir: string, { platform, overlayDir }?: LoadSkillCatalogOptions): Promise<SkillCatalogEntry[]>;
69
+ export declare function loadSkillCatalog(skillsDir: string | null, { platform, overlayDir }?: LoadSkillCatalogOptions): Promise<SkillCatalogEntry[]>;
70
70
  export declare function mcpReadMethods(catalog: readonly SkillCatalogEntry[]): ReadonlyMap<string, ReadonlySet<string>>;
71
71
  export declare function detectPlatform(): string;
@@ -65,7 +65,7 @@ function stripCredentialChecks(requires) {
65
65
  return rest;
66
66
  }
67
67
  export async function loadSkillCatalog(skillsDir, { platform = detectPlatform(), overlayDir = resolveSkillsOverlayDir() } = {}) {
68
- const byName = await loadRoot(skillsDir);
68
+ const byName = skillsDir ? await loadRoot(skillsDir) : new Map();
69
69
  if (overlayDir) {
70
70
  for (const [name, overlay] of await loadRoot(overlayDir, 'overlay')) {
71
71
  byName.set(name, mergeOverlay(byName.get(name), overlay));
@@ -7,13 +7,13 @@ export interface SkillFileContent {
7
7
  readonly content: string;
8
8
  readonly origin: 'base' | 'overlay';
9
9
  }
10
- export declare function listManagedSkills(baseDir: string, overlayDir: string | null): Promise<ManagedSkill[]>;
11
- export declare function readSkillFile(baseDir: string, overlayDir: string | null, name: string): Promise<SkillFileContent | null>;
10
+ export declare function listManagedSkills(baseDir: string | null, overlayDir: string | null): Promise<ManagedSkill[]>;
11
+ export declare function readSkillFile(baseDir: string | null, overlayDir: string | null, name: string): Promise<SkillFileContent | null>;
12
12
  export declare function writeSkillFile(overlayDir: string, name: string, content: string): Promise<string>;
13
13
  export interface CopyBaseResult {
14
14
  copied: boolean;
15
15
  }
16
- export declare function copyBaseForEdit(baseDir: string, overlayDir: string, name: string): Promise<CopyBaseResult>;
16
+ export declare function copyBaseForEdit(baseDir: string | null, overlayDir: string, name: string): Promise<CopyBaseResult>;
17
17
  export interface DeleteOverlayResult {
18
18
  removed: boolean;
19
19
  }
@@ -26,7 +26,7 @@ async function readIfPresent(file) {
26
26
  }
27
27
  }
28
28
  export async function listManagedSkills(baseDir, overlayDir) {
29
- const base = await dirNames(baseDir);
29
+ const base = baseDir ? await dirNames(baseDir) : new Set();
30
30
  const overlay = overlayDir ? await dirNames(overlayDir) : new Set();
31
31
  const names = [...new Set([...base, ...overlay])].sort((a, b) => a.localeCompare(b));
32
32
  return names.map((name) => {
@@ -46,7 +46,7 @@ export async function readSkillFile(baseDir, overlayDir, name) {
46
46
  return { content: over, origin: 'overlay' };
47
47
  }
48
48
  }
49
- const base = await readIfPresent(path.join(baseDir, name, 'SKILL.md'));
49
+ const base = baseDir ? await readIfPresent(path.join(baseDir, name, 'SKILL.md')) : null;
50
50
  return base !== null ? { content: base, origin: 'base' } : null;
51
51
  }
52
52
  export async function writeSkillFile(overlayDir, name, content) {
@@ -65,8 +65,8 @@ export async function copyBaseForEdit(baseDir, overlayDir, name) {
65
65
  if (await exists(dest)) {
66
66
  return { copied: false };
67
67
  }
68
- const src = path.join(baseDir, name);
69
- if (!(await exists(src))) {
68
+ const src = baseDir && path.join(baseDir, name);
69
+ if (!src || !(await exists(src))) {
70
70
  throw new HarnessError('SKILL_NOT_FOUND', [name]);
71
71
  }
72
72
  await copyDir(src, dest);
@@ -5,4 +5,5 @@ export interface CredentialScope {
5
5
  readonly key: string;
6
6
  }
7
7
  export declare function scopeKey({ agentId, skill, key }: CredentialScope): string;
8
+ export declare function parseScopeKey(scoped: string): CredentialScope;
8
9
  export declare function deviceSharedKeys(readiness: Iterable<SkillReadiness>): Set<string>;
@@ -1,6 +1,10 @@
1
1
  export function scopeKey({ agentId, skill, key }) {
2
2
  return `${agentId ?? ''}\0${skill ?? ''}\0${key}`;
3
3
  }
4
+ export function parseScopeKey(scoped) {
5
+ const [agentId, skill, key] = scoped.split('\0');
6
+ return { agentId: agentId || null, skill: skill || null, key };
7
+ }
4
8
  export function deviceSharedKeys(readiness) {
5
9
  return new Set([...readiness].flatMap((entry) => entry.deviceSharedKeys ?? []));
6
10
  }