@qvac/harness 1.0.0 → 1.1.0

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 (100) hide show
  1. package/CHANGELOG.md +137 -1
  2. package/README.md +28 -0
  3. package/dist-lib/index.d.ts +32 -304
  4. package/dist-lib/index.js +16 -1147
  5. package/dist-lib/lib/agent/child-run.d.ts +29 -0
  6. package/dist-lib/lib/agent/child-run.js +32 -0
  7. package/dist-lib/lib/agent/delegate.d.ts +3 -19
  8. package/dist-lib/lib/agent/delegate.js +8 -31
  9. package/dist-lib/lib/agent/index.d.ts +4 -0
  10. package/dist-lib/lib/agent/index.js +3 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +45 -0
  12. package/dist-lib/lib/agent/read-parts.js +60 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
  14. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
  15. package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
  16. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  17. package/dist-lib/lib/client/index.js +1 -3
  18. package/dist-lib/lib/connect/decode.d.ts +3 -2
  19. package/dist-lib/lib/connect/decode.js +14 -0
  20. package/dist-lib/lib/connect.d.ts +1 -0
  21. package/dist-lib/lib/connect.js +11 -5
  22. package/dist-lib/lib/context-window.d.ts +2 -0
  23. package/dist-lib/lib/context-window.js +17 -14
  24. package/dist-lib/lib/contract/models.d.ts +8 -1
  25. package/dist-lib/lib/contract-types.d.ts +9 -0
  26. package/dist-lib/lib/harness.d.ts +267 -0
  27. package/dist-lib/lib/harness.js +1154 -0
  28. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  29. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  30. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  31. package/dist-lib/lib/models/memory-cap.js +20 -0
  32. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  33. package/dist-lib/lib/models/model-catalog.js +8 -2
  34. package/dist-lib/lib/models/model-fit.d.ts +39 -7
  35. package/dist-lib/lib/models/model-fit.js +133 -18
  36. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  37. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  38. package/dist-lib/lib/models/model-pool.js +30 -13
  39. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  40. package/dist-lib/lib/models/tts-model-default.js +7 -6
  41. package/dist-lib/lib/residency/index.d.ts +21 -7
  42. package/dist-lib/lib/residency/index.js +187 -80
  43. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  44. package/dist-lib/lib/run-log/boundary.js +2 -1
  45. package/dist-lib/lib/run-log/index.d.ts +2 -1
  46. package/dist-lib/lib/run-log/index.js +2 -1
  47. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  48. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  49. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  50. package/dist-lib/lib/run-log/run-journal.js +19 -8
  51. package/dist-lib/lib/serve/requests.d.ts +3 -0
  52. package/dist-lib/lib/serve.js +3 -0
  53. package/dist-lib/lib/spawn.d.ts +4 -1
  54. package/dist-lib/lib/tools/exec/shell-guidance.d.ts +2 -0
  55. package/dist-lib/lib/tools/exec/shell-guidance.js +29 -0
  56. package/dist-lib/lib/tools/exec.js +2 -1
  57. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  58. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  59. package/dist-lib/lib/tools/fs/walk.js +64 -30
  60. package/dist-lib/lib/tools/http-request.js +5 -0
  61. package/dist-lib/lib/tools/office.js +8 -5
  62. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  63. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  64. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  65. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  66. package/dist-lib/lib/tools/tls-failure.d.ts +1 -0
  67. package/dist-lib/lib/tools/tls-failure.js +8 -0
  68. package/dist-lib/lib/tools/web-fetch.js +5 -0
  69. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  70. package/dist-lib/plugins/image/generate-image.js +9 -1
  71. package/dist-lib/plugins/image/index.js +6 -2
  72. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  73. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  74. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  75. package/dist-lib/plugins/knowledge/index.js +1 -0
  76. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  77. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  78. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  79. package/dist-lib/plugins/knowledge/store.js +44 -16
  80. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  81. package/dist-lib/plugins/lsp/rpc.js +81 -17
  82. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  83. package/dist-lib/plugins/music/generate-music.js +14 -1
  84. package/dist-lib/plugins/music/index.js +4 -1
  85. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  86. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  87. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  88. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  89. package/dist-lib/schema/harness.js +28 -2
  90. package/dist-lib/spec/bind.js +3 -0
  91. package/dist-lib/spec/calls.js +1 -0
  92. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  93. package/dist-lib/spec/hrpc/index.js +15 -3
  94. package/dist-lib/spec/hrpc/messages.js +87 -6
  95. package/dist-lib/spec/hyperschema/index.js +87 -6
  96. package/dist-lib/spec/hyperschema/schema.json +70 -2
  97. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  98. package/package.json +29 -28
  99. package/scripts/addon-externals.cjs +1 -0
  100. package/worker/harness-sidecar.mjs +12 -1
@@ -161,6 +161,7 @@ export class RunJournal {
161
161
  sealed = false;
162
162
  onFailure;
163
163
  core;
164
+ transient;
164
165
  restored = false;
165
166
  redact;
166
167
  redactShared;
@@ -196,6 +197,7 @@ export class RunJournal {
196
197
  coreRedact !== undefined;
197
198
  this.initialBoot = opts.boot ? prepareEngineBoot(opts.boot) : undefined;
198
199
  this.engineBoot = this.initialBoot ?? createEngineBoot();
200
+ this.transient = opts.transient === true;
199
201
  }
200
202
  redactValue(value) {
201
203
  return this.redactShared(value);
@@ -363,8 +365,7 @@ export class RunJournal {
363
365
  facts: this.redact(copy(facts)),
364
366
  abandoned: receipt.abandoned === true ? true : undefined
365
367
  };
366
- await this.append({ version: RUN_LOG_VERSION, type: 'operation', receipt: enriched });
367
- this.receipts.set(receiptId, copy(enriched));
368
+ await this.storeReceipt(enriched);
368
369
  }
369
370
  retryLifecycleReceipts() {
370
371
  return [...this.receipts.values()]
@@ -388,6 +389,9 @@ export class RunJournal {
388
389
  return false;
389
390
  }
390
391
  append(record) {
392
+ if (this.transient) {
393
+ return this.sealed ? Promise.reject(new AbortedError()) : Promise.resolve();
394
+ }
391
395
  let captured;
392
396
  try {
393
397
  captured = captureRunRecord(this.redactRecord ? this.redactRecord(record) : record);
@@ -458,6 +462,14 @@ export class RunJournal {
458
462
  this.failure = error instanceof Error ? error : new Error(String(error));
459
463
  this.onFailure?.(this.failure);
460
464
  }
465
+ async storeReceipt(receipt) {
466
+ if (this.sealed)
467
+ throw new AbortedError();
468
+ if (!this.transient) {
469
+ await this.append({ version: RUN_LOG_VERSION, type: 'operation', receipt });
470
+ }
471
+ this.receipts.set(receipt.id, copy(receipt));
472
+ }
461
473
  hasPendingFlush() {
462
474
  return this.failure !== null || this.tail !== this.settledTail;
463
475
  }
@@ -584,6 +596,8 @@ export class RunJournal {
584
596
  async recordRequest(request) {
585
597
  if (this.sealed)
586
598
  throw new AbortedError();
599
+ if (this.transient)
600
+ return;
587
601
  const whole = this.requests.redact(requestRecord(request), this.redactShared);
588
602
  const record = this.requests.encode(whole, this.requestHistoryBase);
589
603
  await this.append(isCapturedJson(whole) ? brandCapturedRecord(record) : record);
@@ -619,16 +633,14 @@ export class RunJournal {
619
633
  throw new RecoveryRequired(previous);
620
634
  }
621
635
  const intent = { ...operation, status: 'intent' };
622
- await this.append({ version: RUN_LOG_VERSION, type: 'operation', receipt: intent });
623
- this.receipts.set(intent.id, copy(intent));
636
+ await this.storeReceipt(intent);
624
637
  this.intentArgs.set(intent.id, copy(intent.args));
625
638
  if (this.sealed) {
626
639
  throw new AbortedError();
627
640
  }
628
641
  if (signal?.aborted) {
629
642
  const retry = { ...operation, status: 'retry' };
630
- await this.append({ version: RUN_LOG_VERSION, type: 'operation', receipt: retry });
631
- this.receipts.set(retry.id, copy(retry));
643
+ await this.storeReceipt(retry);
632
644
  throw new AbortedError();
633
645
  }
634
646
  let result;
@@ -657,8 +669,7 @@ export class RunJournal {
657
669
  resultUndefined: result === undefined ? true : undefined,
658
670
  facts: facts ? this.redact(copy(facts.capture())) : undefined
659
671
  });
660
- await this.append({ version: RUN_LOG_VERSION, type: 'operation', receipt });
661
- this.receipts.set(receipt.id, copy(receipt));
672
+ await this.storeReceipt(receipt);
662
673
  }
663
674
  catch (error) {
664
675
  this.fail(error);
@@ -76,6 +76,9 @@ export interface PreviewModelSourceRequest {
76
76
  export interface EmbedRequest extends Pick<EmbedContext, 'model'> {
77
77
  texts?: string[] | null;
78
78
  }
79
+ export interface EmbeddingWeightsRequest {
80
+ model: string;
81
+ }
79
82
  export interface TranscribeRequest {
80
83
  model?: string | null;
81
84
  audio?: Buffer | null;
@@ -114,6 +114,9 @@ function serveHarness(stream, harness) {
114
114
  }
115
115
  return Wire.packVectors(await harness.embed({ model, texts: texts ?? [] }));
116
116
  },
117
+ embeddingWeights: async ({ model }) => ({
118
+ weights: await harness.embeddingWeights?.(model)
119
+ }),
117
120
  transcribe: async ({ model, audio }) => {
118
121
  if (!harness.transcribe) {
119
122
  throw new HarnessError('CAPABILITY_UNSUPPORTED', ['transcribe']);
@@ -24,10 +24,12 @@ export interface HarnessLlmConfig {
24
24
  export interface HarnessKnowledgeConfig {
25
25
  dir: string;
26
26
  model: string;
27
+ hostVectors?: boolean;
27
28
  }
28
29
  export interface HarnessSpeechOptions {
29
- tts?: 'supertonic' | 'moss';
30
+ tts?: 'supertonic' | 'audio8' | 'moss';
30
31
  voice?: string;
32
+ voiceTranscript?: string;
31
33
  dialogue?: {
32
34
  backbone: string;
33
35
  speakers: {
@@ -59,6 +61,7 @@ export interface HarnessPluginOptions {
59
61
  };
60
62
  charts?: HarnessChartsOptions;
61
63
  ocr?: boolean;
64
+ ripgrep?: boolean;
62
65
  [name: string]: unknown;
63
66
  }
64
67
  export interface HarnessChildOptions {
@@ -15,3 +15,5 @@ export declare function shellDownloader(command: string): string | null;
15
15
  export declare const SHELL_DOWNLOAD_NOTE = "The file was saved on this device's disk, not in the chat, so the user cannot see it.";
16
16
  export declare function savesDownload(command: string): boolean;
17
17
  export declare function shellOnlyError(command: string): string | null;
18
+ export declare const TLS_BYPASS_ERROR = "This command disables TLS certificate verification. Do not retry and do not bypass certificate checks; tell the user the site's certificate is invalid.";
19
+ export declare function tlsBypassError(command: string): string | null;
@@ -107,3 +107,32 @@ export function shellOnlyError(command) {
107
107
  }
108
108
  return runsInterpreter(command) ? PYTHON_UNAVAILABLE_ERROR : null;
109
109
  }
110
+ export const TLS_BYPASS_ERROR = "This command disables TLS certificate verification. Do not retry and do not bypass certificate checks; tell the user the site's certificate is invalid.";
111
+ function curlInsecure(words) {
112
+ for (let i = 1; i < words.length; i++) {
113
+ const word = words[i] ?? '';
114
+ if (word === '--insecure') {
115
+ return true;
116
+ }
117
+ const flags = /^-[A-Za-z]/.test(word) ? word.slice(1) : '';
118
+ const valued = [...flags].findIndex((flag) => CURL_VALUED.has(flag));
119
+ const own = valued === -1 ? flags : flags.slice(0, valued);
120
+ if (own.includes('k')) {
121
+ return true;
122
+ }
123
+ i += valued !== -1 && valued === flags.length - 1 ? 1 : 0;
124
+ }
125
+ return false;
126
+ }
127
+ export function tlsBypassError(command) {
128
+ const first = ShellLine.parse(command).commands[0];
129
+ if (!first) {
130
+ return null;
131
+ }
132
+ const bin = commandBin(command);
133
+ const assignments = bin === 'env' ? [...first.assignments, ...first.argv] : first.assignments;
134
+ const bypass = assignments.some((each) => each === 'NODE_TLS_REJECT_UNAUTHORIZED=0') ||
135
+ (bin === 'curl' && curlInsecure(first.argv)) ||
136
+ (bin === 'wget' && first.argv.some((each) => each.startsWith('--no-check-cert')));
137
+ return bypass ? TLS_BYPASS_ERROR : null;
138
+ }
@@ -5,7 +5,7 @@ import { createShellAdapter } from './exec/adapters/shell/shell-adapter.js';
5
5
  import { isPythonLanguage } from './exec/python-source.js';
6
6
  import { MAX_OUTPUT_CHARS, MAX_OUTPUT_CHARS_LIMIT } from './exec/runner.js';
7
7
  import { bareBin, sanitizeCommand } from './exec/scope.js';
8
- import { LANGUAGE_UNAVAILABLE_ERROR, PYTHON_UNAVAILABLE_ERROR, SHELL_DOWNLOAD_NOTE, shellOnlyError, videoToolError } from './exec/shell-guidance.js';
8
+ import { LANGUAGE_UNAVAILABLE_ERROR, PYTHON_UNAVAILABLE_ERROR, SHELL_DOWNLOAD_NOTE, shellOnlyError, tlsBypassError, videoToolError } from './exec/shell-guidance.js';
9
9
  import { ShellLine } from './exec/shell-line.js';
10
10
  import { bareRuntime } from './exec/bare-runtime.js';
11
11
  import { canonicalDenyRoots, defaultRealpath, hostPath, resolveKey } from './fs/scope.js';
@@ -133,6 +133,7 @@ function checkExecutionScope(args, language, { toolOps, sandbox, languages }) {
133
133
  network: languages.some((each) => each.online({ sandbox }))
134
134
  });
135
135
  return (video ??
136
+ tlsBypassError(command) ??
136
137
  firstAnswer(languages, (each) => each.redirect(args, { sandbox })) ??
137
138
  shellOnlyError(command) ??
138
139
  checkShellScope(command, toolOps));
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import { relativeKey, searchTargets } from '../fs/targets.js';
3
3
  import { callDenyRoots, defaultRealpath, displayPath, hostPath, isDeniedPath } from '../fs/scope.js';
4
4
  import { anchorOf, rootedPath, stringArg } from '../fs/tool-path.js';
5
- import { WALK_SKIP_DIRS, walkFiles } from '../fs/walk.js';
5
+ import { MAX_WALK_MS, WALK_SKIP_DIRS, walkLevel } from '../fs/walk.js';
6
6
  const LIST_ENTRIES = 200;
7
7
  export function createListDirTool({ realpath = defaultRealpath, deniedRoots } = {}) {
8
8
  return {
@@ -26,22 +26,22 @@ export function createListDirTool({ realpath = defaultRealpath, deniedRoots } =
26
26
  kind: 'file',
27
27
  label: `list ${folderArg(args, ctx) ?? 'shared folder'}`
28
28
  }),
29
- async execute(args, ctx) {
30
- const roots = ctx?.fsRoots ?? [];
31
- const deny = await callDenyRoots(deniedRoots, ctx?.policy, realpath);
32
- const scoped = await searchTargets(folderArg(args, ctx), roots, { realpath, deny });
33
- if ('error' in scoped) {
34
- return scoped;
35
- }
36
- const { entries, truncated } = await collect(scoped.targets, { deny, anchor: anchorOf(ctx) });
37
- const rows = await describe([...entries].slice(0, LIST_ENTRIES));
38
- return {
39
- entries: rows.join('\n') || '(empty)',
40
- truncated: truncated || entries.size > LIST_ENTRIES || undefined
41
- };
29
+ execute(args, ctx) {
30
+ return executeListDir(args, ctx, { realpath, deniedRoots });
42
31
  }
43
32
  };
44
33
  }
34
+ async function executeListDir(args, ctx, { realpath, deniedRoots }) {
35
+ const roots = ctx?.fsRoots ?? [];
36
+ const deny = await callDenyRoots(deniedRoots, ctx?.policy, realpath);
37
+ const scoped = await searchTargets(folderArg(args, ctx), roots, { realpath, deny });
38
+ if ('error' in scoped) {
39
+ return scoped;
40
+ }
41
+ const { entries, truncated } = await collect(scoped.targets, { deny, anchor: anchorOf(ctx) });
42
+ const rows = await describe([...entries].slice(0, LIST_ENTRIES));
43
+ return { entries: rows.join('\n') || '(empty)', truncated: truncated || undefined };
44
+ }
45
45
  export function folderArg(args, grants) {
46
46
  const folder = stringArg(args, 'dir') ?? stringArg(args, 'path');
47
47
  return folder && folder !== '.' && folder !== '/'
@@ -57,16 +57,21 @@ async function collect(targets, { deny, anchor }) {
57
57
  let truncated = false;
58
58
  for (const target of targets) {
59
59
  const own = targets.length === 1 || target.root === anchor;
60
+ const deadline = Date.now() + MAX_WALK_MS;
60
61
  const level = target.root.kind === 'local'
61
62
  ? await localLevel(target.root, target.folder, deny)
62
- : await walkedLevel(target, deny);
63
+ : await remoteLevel(target, deny, { deadline });
63
64
  truncated ||= level.truncated;
64
65
  for (const child of level.children) {
65
66
  const name = own ? child.name : displayPath(target.root, child.key);
66
- entries.set(name, { ...child, drive: target.root.drive });
67
+ const expand = child.folder && target.root.kind === 'hyper' && level.rules
68
+ ? { root: target.root, rules: level.rules, deadline }
69
+ : undefined;
70
+ entries.set(name, { ...child, drive: target.root.drive, expand });
67
71
  }
68
72
  }
69
- return { entries, truncated };
73
+ const projected = await visibleEntries([...entries], deny);
74
+ return { entries: projected.entries, truncated: truncated || projected.truncated };
70
75
  }
71
76
  async function localLevel(root, folder, deny) {
72
77
  const children = [];
@@ -88,24 +93,66 @@ async function localLevel(root, folder, deny) {
88
93
  }
89
94
  return { children, truncated: false };
90
95
  }
91
- async function walkedLevel(target, deny) {
92
- const walk = await walkFiles(target.root, target.folder);
93
- const children = [];
94
- const folders = new Map();
95
- for (const file of walk.files) {
96
- if (isDeniedPath(file.path, deny))
97
- continue;
98
- const [name, below] = relativeKey(file.key, target.folder).split('/');
99
- if (below === undefined) {
100
- children.push({ name, key: file.key, folder: false, items: 0 });
96
+ async function remoteLevel(target, deny, options) {
97
+ const level = await walkLevel(target.root, target.folder, options);
98
+ const files = [];
99
+ const folders = [];
100
+ for (const child of level.children) {
101
+ if (isDeniedPath(displayPath(target.root, child.key), deny))
101
102
  continue;
103
+ const name = relativeKey(child.key, target.folder);
104
+ if ('dir' in child) {
105
+ folders.push({ name, key: child.key, folder: true, items: 0 });
102
106
  }
103
- folders.set(name, (folders.get(name) ?? new Set()).add(below));
107
+ else {
108
+ files.push({ name, key: child.key, folder: false, items: 0, stat: child });
109
+ }
110
+ }
111
+ return {
112
+ children: [...files, ...folders],
113
+ truncated: level.truncated,
114
+ rules: level.rules
115
+ };
116
+ }
117
+ async function visibleEntries(entries, deny) {
118
+ const visible = new Map();
119
+ let next = 0;
120
+ let truncated = false;
121
+ while (next < entries.length && visible.size <= LIST_ENTRIES) {
122
+ const batch = entries.slice(next, next + 8);
123
+ const results = await Promise.all(batch.map(([name, entry]) => visibleCandidate(name, entry, deny)));
124
+ for (const result of results) {
125
+ truncated ||= result.truncated;
126
+ if (!result.visible) {
127
+ continue;
128
+ }
129
+ if (visible.size > LIST_ENTRIES) {
130
+ truncated = true;
131
+ continue;
132
+ }
133
+ visible.set(result.name, result.entry);
134
+ }
135
+ next += batch.length;
136
+ }
137
+ if (next < entries.length || visible.size > LIST_ENTRIES) {
138
+ truncated = true;
139
+ }
140
+ return { entries: visible, truncated };
141
+ }
142
+ async function visibleCandidate(name, entry, deny) {
143
+ const { expand } = entry;
144
+ if (!expand) {
145
+ return { name, entry, visible: true, truncated: false };
104
146
  }
105
- for (const [name, items] of folders) {
106
- children.push({ name, key: childKey(target.folder, name), folder: true, items: items.size });
147
+ if (Date.now() > expand.deadline) {
148
+ return { name, entry, visible: false, truncated: true };
107
149
  }
108
- return { children, truncated: walk.truncated };
150
+ const level = await remoteLevel({ root: expand.root, folder: entry.key }, deny, {
151
+ deadline: expand.deadline,
152
+ inherited: expand.rules
153
+ });
154
+ entry.items = level.children.length;
155
+ return { name, entry, visible: entry.items > 0, truncated: level.truncated };
109
156
  }
110
157
  async function readdir(dir) {
111
158
  try {
@@ -125,7 +172,7 @@ async function describe(entries) {
125
172
  rows.push(`${name}/ (folder, ${entry.items} ${entry.items === 1 ? 'item' : 'items'})`);
126
173
  continue;
127
174
  }
128
- const stat = await entry.drive.entry(entry.key);
175
+ const stat = entry.stat ?? (await entry.drive.entry(entry.key));
129
176
  const size = stat?.value.blob?.byteLength ?? 0;
130
177
  const changed = stat?.mtime
131
178
  ? `, changed ${new Date(stat.mtime).toISOString().slice(0, 16)}`
@@ -1,4 +1,4 @@
1
- import type { DriveRoot, WalkSummary } from '../../contract/drive.ts';
1
+ import type { DriveDir, DriveEntry, DriveRoot, WalkSummary } from '../../contract/drive.ts';
2
2
  import { IgnoreRules } from './ignore.ts';
3
3
  export declare const WALK_SKIP_DIRS: Set<string>;
4
4
  export declare const HIDDEN_DIRS: Set<string>;
@@ -22,6 +22,16 @@ export interface WalkOptions {
22
22
  maxEntries?: number;
23
23
  maxMs?: number;
24
24
  }
25
+ export interface WalkLevelOptions {
26
+ deadline: number;
27
+ inherited?: IgnoreRules | undefined;
28
+ }
29
+ export interface WalkLevelResult {
30
+ children: Array<DriveEntry | DriveDir>;
31
+ rules: IgnoreRules;
32
+ truncated: boolean;
33
+ }
34
+ export declare function walkLevel(root: DriveRoot, folder: string, { deadline, inherited }: WalkLevelOptions): Promise<WalkLevelResult>;
25
35
  export declare function rootRules(root: DriveRoot, folder: string): Promise<IgnoreRules>;
26
36
  export declare function walkFiles(root: DriveRoot, folder?: string, opts?: WalkOptions): Promise<WalkResult>;
27
37
  export declare function streamFiles(root: DriveRoot, folder?: string, opts?: WalkOptions): WalkStream;
@@ -17,6 +17,65 @@ async function withIgnoreFile(root, rules, key) {
17
17
  const dir = key.slice(0, key.lastIndexOf('/'));
18
18
  return bytes === null ? rules : rules.add(dir.slice(1), b4a.toString(bytes, 'utf8'));
19
19
  }
20
+ export async function walkLevel(root, folder, { deadline, inherited }) {
21
+ try {
22
+ const rules = inherited ?? (await rootRules(root, folder));
23
+ const children = await listChildren(root, folder, deadline);
24
+ if (children === null) {
25
+ return { children: [], rules, truncated: true };
26
+ }
27
+ return filterLevel(children, await levelRules({ root, folder, children, inherited: rules }), deadline);
28
+ }
29
+ catch (err) {
30
+ HarnessLog.warn('warn: walk aborted mid-listing', {
31
+ root: displayPath(root, '/'),
32
+ folder,
33
+ err: errorMessage(err)
34
+ });
35
+ return { children: [], rules: inherited ?? new IgnoreRules(), truncated: true };
36
+ }
37
+ }
38
+ async function listChildren(root, dir, deadline) {
39
+ const children = [];
40
+ for await (const child of root.drive.list(dir, { skip: WALK_SKIP_DIRS, recursive: false })) {
41
+ if (Date.now() > deadline)
42
+ return null;
43
+ children.push(child);
44
+ }
45
+ return children;
46
+ }
47
+ async function levelRules({ root, folder, children, inherited }) {
48
+ let rules = inherited;
49
+ for (const name of IGNORE_FILES) {
50
+ const key = childKey(folder, name);
51
+ if (children.some((child) => isIgnoreFile(child, key))) {
52
+ rules = await withIgnoreFile(root, rules, key);
53
+ }
54
+ }
55
+ return rules;
56
+ }
57
+ function keeps(child, rules) {
58
+ const isDir = 'dir' in child;
59
+ const name = child.key.slice(child.key.lastIndexOf('/') + 1);
60
+ return !(isDir && HIDDEN_DIRS.has(name)) && !rules.ignored(child.key.slice(1), isDir);
61
+ }
62
+ function filterLevel(listed, rules, deadline) {
63
+ const children = [];
64
+ let kept = 0;
65
+ let truncated = false;
66
+ for (const child of listed) {
67
+ if (!keeps(child, rules))
68
+ continue;
69
+ if (++kept > MAX_WALK_ENTRIES || Date.now() > deadline) {
70
+ truncated = true;
71
+ break;
72
+ }
73
+ if ('dir' in child || child.value.linkname === null) {
74
+ children.push(child);
75
+ }
76
+ }
77
+ return { children, rules, truncated };
78
+ }
20
79
  export async function rootRules(root, folder) {
21
80
  let rules = new IgnoreRules();
22
81
  const parts = folder.split('/').filter(Boolean);
@@ -49,41 +108,16 @@ class Walk {
49
108
  rootRules(folder) {
50
109
  return this.#includeIgnored ? Promise.resolve(new IgnoreRules()) : rootRules(this.#root, folder);
51
110
  }
52
- async #list(dir) {
53
- const children = [];
54
- const listing = this.#root.drive.list(dir, { skip: WALK_SKIP_DIRS, recursive: false });
55
- for await (const child of listing) {
56
- if (Date.now() > this.#deadline)
57
- return null;
58
- children.push(child);
59
- }
60
- return children;
61
- }
62
- #keeps(child, rules) {
63
- if (this.#includeIgnored)
64
- return true;
65
- const isDir = 'dir' in child;
66
- const name = child.key.slice(child.key.lastIndexOf('/') + 1);
67
- return !(isDir && HIDDEN_DIRS.has(name)) && !rules.ignored(child.key.slice(1), isDir);
68
- }
69
- async #rulesFor(dir, children, inherited) {
70
- let rules = inherited;
71
- for (const name of IGNORE_FILES) {
72
- const key = childKey(dir, name);
73
- if (!this.#includeIgnored && children.some((child) => isIgnoreFile(child, key))) {
74
- rules = await withIgnoreFile(this.#root, rules, key);
75
- }
76
- }
77
- return rules;
78
- }
79
111
  async visit(dir, inherited) {
80
- const children = await this.#list(dir);
112
+ const children = await listChildren(this.#root, dir, this.#deadline);
81
113
  if (children === null) {
82
114
  return false;
83
115
  }
84
- const rules = await this.#rulesFor(dir, children, inherited);
116
+ const rules = this.#includeIgnored
117
+ ? inherited
118
+ : await levelRules({ root: this.#root, folder: dir, children, inherited });
85
119
  for (const child of children) {
86
- if (!this.#keeps(child, rules))
120
+ if (!this.#includeIgnored && !keeps(child, rules))
87
121
  continue;
88
122
  if (++this.kept > this.#maxEntries || Date.now() > this.#deadline) {
89
123
  return false;
@@ -12,6 +12,7 @@ import { recordCredentialHealth } from './skills/credential-health.js';
12
12
  import { Policy } from '../policy/index.js';
13
13
  import { attachFetchedFile, attachTextFile, bareMime, dispositionFileName, isFileMime, MAX_FILE_BYTES } from './attachments/fetched-file.js';
14
14
  import { resolveOutboundUrl } from './url-guard.js';
15
+ import { tlsFailure } from './tls-failure.js';
15
16
  const MAX_REDIRECTS = 5;
16
17
  export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credentialStore, credentialAllowList, resolveHost = lookupHost } = {}) {
17
18
  return {
@@ -265,6 +266,10 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
265
266
  if (timedOut || error.name === 'TimeoutError') {
266
267
  return { error: 'request timed out', code: 'timeout' };
267
268
  }
269
+ const tls = tlsFailure(err, url.hostname);
270
+ if (tls) {
271
+ return { error: tls, code: 'tls' };
272
+ }
268
273
  return { error: `request failed: ${error.message}`, code: 'transport' };
269
274
  }
270
275
  finally {
@@ -94,6 +94,7 @@ const PPTX_FORMAT = {
94
94
  stem: 'presentation',
95
95
  ops: PPTX_OPS,
96
96
  createKeys: ['size', 'title', 'fonts', 'colors'],
97
+ imageOp: () => ({ op: 'addPicture', slide: 0, image: {} }),
97
98
  looks: ['fonts', 'colors'],
98
99
  open: (bytes) => pptx.open(bytes),
99
100
  create: (options) => pptx.create(options),
@@ -109,6 +110,7 @@ const DOCX_FORMAT = {
109
110
  stem: 'document',
110
111
  ops: DOCX_OPS,
111
112
  createKeys: ['title', 'page', 'size', 'fonts'],
113
+ imageOp: (doc) => ({ op: 'addImage', at: doc.blockCount, image: {} }),
112
114
  open: (bytes) => docx.open(bytes),
113
115
  create: (options) => docx.create(options),
114
116
  read: (doc) => doc.read(),
@@ -121,6 +123,7 @@ const XLSX_FORMAT = {
121
123
  stem: 'workbook',
122
124
  ops: XLSX_OPS,
123
125
  createKeys: ['sheets', 'title'],
126
+ imageOp: () => ({ op: 'addImage', sheet: 0, image: {} }),
124
127
  open: (bytes) => xlsx.open(bytes),
125
128
  create: (options) => xlsx.create(options),
126
129
  read: readWorkbook,
@@ -657,7 +660,7 @@ async function execute(format, args, ctx) {
657
660
  reply: `${attachment.fileName} — ${countLine(counts)}`,
658
661
  next: renamed +
659
662
  `Done: ${attachment.fileName} ${repeated ? 'was already' : 'is'} attached to the chat and shown to the user. ` +
660
- afterSave(format, attachment.attachmentId, unplaced)
663
+ afterSave(format, { document, attachmentId: attachment.attachmentId, unplaced })
661
664
  };
662
665
  }
663
666
  async function leftOutImage(request, ctx) {
@@ -670,14 +673,14 @@ async function leftOutImage(request, ctx) {
670
673
  const available = await uploadsAvailable(ctx.fetchAttachment, { signal: ctx.signal });
671
674
  return available ? 'An image in this chat' : null;
672
675
  }
673
- function afterSave(format, attachmentId, unplaced) {
676
+ function afterSave(format, { document, attachmentId, unplaced }) {
674
677
  const reply = 'Your answer is the reply value alone, word for word.';
675
678
  if (!unplaced) {
676
679
  return `Do not call ${format.name} again for it. ${reply}`;
677
680
  }
678
- return (`${unplaced} is not in it. If they asked for that image in the ${format.noun}, ` +
679
- `call ${format.name} once more with attachmentId "${attachmentId}" and one op that adds it with "image": {}. ` +
680
- `Otherwise: ${reply}`);
681
+ const call = JSON.stringify({ attachmentId, ops: [format.imageOp(document)] });
682
+ return (`${unplaced} is not in it. If the user asked for that image in the ${format.noun}, call ${format.name} now with ` +
683
+ `exactly ${call} — no create. Otherwise: ${reply}`);
681
684
  }
682
685
  function createOfficeTool(format) {
683
686
  return {
@@ -9,4 +9,4 @@ export interface PdfPagesOptions {
9
9
  readonly ocr?: OcrService | undefined;
10
10
  readonly signal?: BareAbortSignal | undefined;
11
11
  }
12
- export declare function pdfPages(bytes: Uint8Array, { ocr, signal }?: PdfPagesOptions): Promise<PdfPage[]>;
12
+ export declare function pdfPages(bytes: Uint8Array, options?: PdfPagesOptions): Promise<PdfPage[]>;
@@ -1,29 +1,18 @@
1
1
  import { HarnessError } from '../../errors.js';
2
- import { cleanText } from './build.js';
3
- import { recognizePages } from './recognize.js';
2
+ import { readPdfPages } from './recognize.js';
4
3
  let pdfium = null;
5
4
  function loadPdfium() {
6
5
  pdfium ??= import('bare-pdfium').then((loaded) => loaded, () => null);
7
6
  return pdfium;
8
7
  }
9
- export async function pdfPages(bytes, { ocr, signal } = {}) {
8
+ export async function pdfPages(bytes, options = {}) {
10
9
  const lib = await loadPdfium();
11
10
  if (!lib) {
12
11
  throw new HarnessError('PDF_TEXT_UNAVAILABLE');
13
12
  }
14
13
  const doc = lib.open(bytes);
15
14
  try {
16
- const recognized = ocr
17
- ? (await recognizePages({ doc, bytes }, { ocr, signal })).pages
18
- : undefined;
19
- const pages = [];
20
- for await (const { page, text } of doc.textPagesAsync()) {
21
- signal?.throwIfAborted();
22
- const read = recognized?.get(page) ?? cleanText(text);
23
- const unread = !read && !recognized?.has(page) && doc.pageFlags(page).hasImage;
24
- pages.push({ page: page + 1, text: read, unread });
25
- }
26
- return pages;
15
+ return await readPdfPages(doc, bytes, options);
27
16
  }
28
17
  finally {
29
18
  doc.close();
@@ -1,6 +1,7 @@
1
1
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { OcrService } from '../../contract/ocr.ts';
3
3
  import { type Doc, type ReadBudget, type Recognized } from './build.ts';
4
+ import type { PdfPage, PdfPagesOptions } from './pages.ts';
4
5
  export interface ScannedDocument {
5
6
  readonly doc: Doc;
6
7
  readonly bytes: Uint8Array;
@@ -11,3 +12,5 @@ export interface RecognizeOptions {
11
12
  readonly budget?: ReadBudget | undefined;
12
13
  }
13
14
  export declare function recognizePages({ doc, bytes }: ScannedDocument, { ocr, signal, budget }: RecognizeOptions): Promise<Recognized>;
15
+ export declare function pageRecognizer({ doc, bytes }: ScannedDocument, { ocr, signal }: RecognizeOptions): (page: number) => Promise<string | null>;
16
+ export declare function readPdfPages(doc: Doc, bytes: Uint8Array, { ocr, signal }?: PdfPagesOptions): Promise<PdfPage[]>;