@qvac/harness 0.8.11 → 0.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +139 -1
  2. package/dist-lib/index.d.ts +1 -0
  3. package/dist-lib/index.js +16 -8
  4. package/dist-lib/lib/capabilities/completion.d.ts +9 -1
  5. package/dist-lib/lib/capabilities/completion.js +87 -25
  6. package/dist-lib/lib/capabilities/preview-model-source.d.ts +7 -1
  7. package/dist-lib/lib/capabilities/preview-model-source.js +80 -22
  8. package/dist-lib/lib/capabilities/tool-search.d.ts +4 -0
  9. package/dist-lib/lib/capabilities/tool-search.js +9 -0
  10. package/dist-lib/lib/capabilities/tool-selection.d.ts +3 -1
  11. package/dist-lib/lib/capabilities/tool-selection.js +3 -2
  12. package/dist-lib/lib/connect.js +3 -2
  13. package/dist-lib/lib/contract-types.d.ts +1 -0
  14. package/dist-lib/lib/errors.d.ts +4 -0
  15. package/dist-lib/lib/errors.js +6 -0
  16. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  17. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  18. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  19. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  20. package/dist-lib/lib/models/gguf-header.d.ts +11 -0
  21. package/dist-lib/lib/models/gguf-header.js +203 -15
  22. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  23. package/dist-lib/lib/models/kv-cache.js +8 -0
  24. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  25. package/dist-lib/lib/models/llm-presets.js +2 -2
  26. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  27. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  28. package/dist-lib/lib/models/model-pool.js +22 -10
  29. package/dist-lib/lib/models/model-source.d.ts +1 -0
  30. package/dist-lib/lib/models/model-source.js +20 -3
  31. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  32. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  33. package/dist-lib/lib/prompt.d.ts +2 -1
  34. package/dist-lib/lib/prompt.js +12 -12
  35. package/dist-lib/lib/serve.js +3 -2
  36. package/dist-lib/lib/tools/edit-image.js +4 -3
  37. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  38. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  39. package/dist-lib/lib/tools/exec/obsidian/guidance.js +2 -2
  40. package/dist-lib/lib/tools/exec/obsidian/vault-read.js +17 -16
  41. package/dist-lib/lib/tools/generate-image.js +4 -3
  42. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  43. package/dist-lib/lib/tools/http-request/request.js +2 -1
  44. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  45. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  46. package/dist-lib/lib/tools/http-request.js +13 -6
  47. package/dist-lib/lib/tools/mcp-call.js +1 -0
  48. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  49. package/dist-lib/lib/tools/office/ops.js +5 -1
  50. package/dist-lib/lib/tools/office.d.ts +1 -0
  51. package/dist-lib/lib/tools/office.js +197 -35
  52. package/dist-lib/lib/tools/operations/compile.js +4 -4
  53. package/dist-lib/lib/tools/pdf/build.d.ts +5 -1
  54. package/dist-lib/lib/tools/pdf/build.js +31 -6
  55. package/dist-lib/lib/tools/pdf.js +17 -2
  56. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  57. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  58. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  59. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  60. package/dist-lib/schema/harness.js +2 -1
  61. package/dist-lib/spec/hrpc/messages.js +8 -5
  62. package/dist-lib/spec/hyperschema/index.js +8 -5
  63. package/dist-lib/spec/hyperschema/schema.json +6 -1
  64. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  65. package/package.json +5 -5
@@ -1,5 +1,7 @@
1
+ import type { HeadDims } from './gguf-header.ts';
1
2
  export interface KvCacheTypes {
2
3
  k: string | undefined;
3
4
  v: string | undefined;
4
5
  }
6
+ export declare function headSafeKvCache({ k, v }: KvCacheTypes, heads: HeadDims | undefined): KvCacheTypes;
5
7
  export declare function adrenoSafeKvCache(device: 'cpu' | 'gpu' | undefined, { k, v }: KvCacheTypes, hostPlatform?: string): KvCacheTypes;
@@ -1,4 +1,12 @@
1
1
  import { platform } from 'os';
2
+ const QUANT_BLOCK = 32;
3
+ const UNBLOCKED = new Set(['f32', 'f16', 'bf16']);
4
+ export function headSafeKvCache({ k, v }, heads) {
5
+ return { k: blockFits(k, heads?.k) ? k : 'f16', v: blockFits(v, heads?.v) ? v : 'f16' };
6
+ }
7
+ function blockFits(type, width) {
8
+ return !type || !width || UNBLOCKED.has(type) || width % QUANT_BLOCK === 0;
9
+ }
2
10
  export function adrenoSafeKvCache(device, { k, v }, hostPlatform = platform()) {
3
11
  if (device === 'cpu' || hostPlatform !== 'android') {
4
12
  return { k, v };
@@ -5,6 +5,7 @@ export interface LlmGenerationParams {
5
5
  presence_penalty?: number;
6
6
  repeat_penalty?: number;
7
7
  frequency_penalty?: number;
8
- reasoning_budget: -1 | 0;
8
+ reasoning_budget?: -1 | 0;
9
+ tool_choice?: 'none';
9
10
  }
10
11
  export declare function resolveLlmGenerationParams(modelName: string | undefined, reasoningEnabled: boolean | undefined, deviceDefault?: boolean): LlmGenerationParams | undefined;
@@ -28,13 +28,13 @@ const PRESET_RESOLVERS = [
28
28
  { prefix: 'Qwen3.5-4B-', resolve: qwen4BPreset }
29
29
  ];
30
30
  export function resolveLlmGenerationParams(modelName, reasoningEnabled, deviceDefault) {
31
+ const effective = reasoningEnabled ?? deviceDefault;
31
32
  const resolver = modelName
32
33
  ? PRESET_RESOLVERS.find((entry) => modelName.startsWith(entry.prefix))
33
34
  : undefined;
34
35
  if (resolver) {
35
- return resolver.resolve(reasoningEnabled);
36
+ return resolver.resolve(effective);
36
37
  }
37
- const effective = reasoningEnabled ?? deviceDefault;
38
38
  if (effective === undefined) {
39
39
  return undefined;
40
40
  }
@@ -4,6 +4,7 @@ export interface ModelResource {
4
4
  modelId: string;
5
5
  ctxSize?: number;
6
6
  bytes?: number;
7
+ canThink?: boolean | undefined;
7
8
  }
8
9
  export interface ModelHandleOptions {
9
10
  load(signal: AbortSignal): Promise<ModelResource>;
@@ -1,6 +1,7 @@
1
1
  import ResourcePuddle from 'resource-puddle';
2
2
  import { ModelHandle } from './model-handle.ts';
3
3
  import { type ModelSrc } from './context.ts';
4
+ import type { CpuPlacement } from '../hardware/cpu-placement.ts';
4
5
  import { type ModelAddon } from './model-source.ts';
5
6
  import type { GpuFaultState } from './sdk-faults.ts';
6
7
  import type { HoldFn } from './download-gate.ts';
@@ -34,6 +35,7 @@ export interface LlmDeviceConfig {
34
35
  kvCacheV?: string;
35
36
  mainGpu?: () => Promise<string | undefined>;
36
37
  openclCacheDir?: () => string | undefined;
38
+ cpuPlacement?: () => CpuPlacement | undefined;
37
39
  }
38
40
  export type TrackedLoad = Promise<string> & {
39
41
  requestId?: string;
@@ -66,6 +68,8 @@ export type ModelLifecycleSdk = Pick<SdkModule, 'unloadModel' | 'modelRegistrySe
66
68
  gpu_layers?: number;
67
69
  'main-gpu'?: string;
68
70
  openclCacheDir?: string;
71
+ threads?: number;
72
+ 'cpu-mask'?: string;
69
73
  };
70
74
  onProgress?: (progress: Record<string, unknown>) => void;
71
75
  }): TrackedLoad;
@@ -160,8 +164,9 @@ export interface ModelPoolOptions {
160
164
  beforeLoad?: BeforeLoad;
161
165
  chooseContext?: ChooseContext;
162
166
  hold?: HoldFn;
167
+ modelsDir?: string | undefined;
163
168
  }
164
- export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold }?: ModelPoolOptions): ModelPuddle;
169
+ export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold, modelsDir }?: ModelPoolOptions): ModelPuddle;
165
170
  export interface EmbedPoolOptions {
166
171
  faults: GpuFaultState;
167
172
  batchSize?: number;
@@ -5,12 +5,14 @@ import ResourcePuddle from 'resource-puddle';
5
5
  import { ModelHandle } from './model-handle.js';
6
6
  import { defaultContextSize } from './context.js';
7
7
  import { customContextLength } from './model-catalog.js';
8
- import { adrenoSafeKvCache } from './kv-cache.js';
8
+ import { localWeightFile } from './custom-model-cache.js';
9
+ import { GGUF_STUB_MAX_BYTES, parseGgufHeader, readGgufHeaderBytes } from './gguf-header.js';
10
+ import { adrenoSafeKvCache, headSafeKvCache } from './kv-cache.js';
9
11
  import { DEFAULT_EMBED_BATCH_SIZE } from './embed-config.js';
10
12
  import { log } from '../log.js';
11
13
  import { RUNAWAY_STOP_SEQUENCES } from '../helpers/control-tokens.js';
12
14
  import { raceTimeout } from '../helpers/race-timeout.js';
13
- import { resolveModelSrc } from './model-source.js';
15
+ import { resolveModelSrc, resolveProjectionSrc } from './model-source.js';
14
16
  import { errorMessage } from '../guards.js';
15
17
  import { AbortedError } from '../helpers/race-abort.js';
16
18
  export function createLoadTracker() {
@@ -358,25 +360,24 @@ export function loadClockGuard(model, sdk, { now = () => Date.now(), monoMs = mo
358
360
  };
359
361
  return { race };
360
362
  }
361
- export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold } = {}) {
363
+ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold, modelsDir } = {}) {
362
364
  const load = async (key, model, opts) => {
363
365
  const sdk = await loadSdk();
364
366
  const modelSrc = await resolveModelSrc(sdk, model);
365
367
  const resolved = resolveLoadOptions(opts, deviceConfig);
368
+ const header = await weightHeader(modelSrc, modelsDir);
366
369
  const tier = defaultContextSize(modelSrc, customContextLength(model));
367
370
  const projectionModelSrc = resolved.projectionModel
368
- ? await resolveModelSrc(sdk, resolved.projectionModel)
371
+ ? await resolveProjectionSrc(sdk, resolved.projectionModel)
369
372
  : undefined;
370
373
  const mainGpu = deviceConfig.device !== 'cpu' && deviceConfig.mainGpu
371
374
  ? await deviceConfig.mainGpu()
372
375
  : undefined;
373
- const kvCache = adrenoSafeKvCache(deviceConfig.device, {
374
- k: resolved.kvCacheK,
375
- v: resolved.kvCacheV
376
- });
376
+ const kvCache = headSafeKvCache(adrenoSafeKvCache(deviceConfig.device, { k: resolved.kvCacheK, v: resolved.kvCacheV }), header?.headDims);
377
377
  const openclCache = deviceConfig.device !== 'cpu' && deviceConfig.openclCacheDir
378
378
  ? deviceConfig.openclCacheDir()
379
379
  : undefined;
380
+ const placement = deviceConfig.device === 'cpu' ? deviceConfig.cpuPlacement?.() : undefined;
380
381
  const config = definedFields({
381
382
  verbosity: llmVerbosity(),
382
383
  tools: true,
@@ -387,7 +388,9 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
387
388
  device: deviceConfig.device,
388
389
  gpu_layers: deviceConfig.gpuLayers,
389
390
  'main-gpu': mainGpu,
390
- openclCacheDir: openclCache || undefined
391
+ openclCacheDir: openclCache || undefined,
392
+ threads: placement?.threads,
393
+ 'cpu-mask': placement?.mask
391
394
  });
392
395
  const pending = { key, model, modelSrc, modelType: 'llamacpp-completion' };
393
396
  const ctxSize = resolved.ctxSize ||
@@ -406,7 +409,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
406
409
  })))
407
410
  .finally(() => admission?.release());
408
411
  log.info('llm loaded', { model, loadMs: Date.now() - loadStarted });
409
- return { model, modelId, ctxSize, bytes: admission?.bytes };
412
+ return { model, modelId, ctxSize, bytes: admission?.bytes, canThink: canThink(header) };
410
413
  };
411
414
  return new ModelPuddle({
412
415
  open: (key, model = key, opts = {}) => reportedHandle({ notify, model, addon: 'llm', hold, load: () => load(key, model, opts) }),
@@ -414,6 +417,15 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
414
417
  ...NO_IDLE_GC
415
418
  });
416
419
  }
420
+ async function weightHeader(modelSrc, modelsDir) {
421
+ const file = typeof modelSrc === 'string' ? localWeightFile(modelSrc, modelsDir) : null;
422
+ const bytes = file ? await readGgufHeaderBytes(file, { maxBytes: GGUF_STUB_MAX_BYTES }) : null;
423
+ return bytes && parseGgufHeader(bytes);
424
+ }
425
+ function canThink(header) {
426
+ const template = header?.chatTemplate;
427
+ return template === undefined ? undefined : /<think(?:ing)?>/.test(template);
428
+ }
417
429
  export function createEmbedPool(loadSdk, notify, { faults, batchSize = DEFAULT_EMBED_BATCH_SIZE, openclCacheDir, loads = createLoadTracker(), beforeLoad, hold }) {
418
430
  const load = async (key, model) => {
419
431
  const sdk = await loadSdk();
@@ -4,3 +4,4 @@ import type { ModelSrc } from './context.ts';
4
4
  export type ModelRegistrySdk = Pick<typeof QvacSdk, 'modelRegistrySearch'>;
5
5
  export type ModelAddon = ModelRegistryEntryAddon;
6
6
  export declare function resolveModelSrc(sdk: ModelRegistrySdk, model: string, addon?: ModelAddon): Promise<ModelSrc>;
7
+ export declare function resolveProjectionSrc(sdk: ModelRegistrySdk, model: string): Promise<ModelSrc>;
@@ -1,7 +1,8 @@
1
1
  import { HarnessError } from '../errors.js';
2
- import { audioGenModelByName, curatedModelAsset, customModelSrc } from './model-catalog.js';
2
+ import { audioGenModelByName, curatedListables, curatedModelAsset, customModelSrc } from './model-catalog.js';
3
+ const SOURCE_PATTERN = /^(\/|~|\.|file:|https?:|registry:|pear:|hyper:)/;
3
4
  export async function resolveModelSrc(sdk, model, addon = 'llm') {
4
- if (/^(\/|~|\.|file:|https?:|registry:|pear:|hyper:)/.test(model)) {
5
+ if (SOURCE_PATTERN.test(model)) {
5
6
  return model;
6
7
  }
7
8
  const custom = customModelSrc(model, addon);
@@ -19,9 +20,25 @@ export async function resolveModelSrc(sdk, model, addon = 'llm') {
19
20
  if (asset) {
20
21
  return asset;
21
22
  }
22
- const [entry] = await sdk.modelRegistrySearch({ filter: model, addon });
23
+ return await registryMatch(sdk, { model, addon, projection: false });
24
+ }
25
+ export async function resolveProjectionSrc(sdk, model) {
26
+ if (SOURCE_PATTERN.test(model)) {
27
+ return model;
28
+ }
29
+ return await registryMatch(sdk, { model, addon: 'llm', projection: true });
30
+ }
31
+ async function registryMatch(sdk, { model, addon, projection }) {
32
+ const entries = await sdk.modelRegistrySearch({ filter: model, addon });
33
+ const entry = bestMatch(entries.filter((candidate) => /mmproj/i.test(candidate.name) === projection), model);
23
34
  if (!entry) {
24
35
  throw new HarnessError('MODEL_NOT_IN_REGISTRY', [model, addon]);
25
36
  }
26
37
  return { ...entry, src: `registry://${entry.registrySource}/${entry.registryPath}` };
27
38
  }
39
+ function bestMatch(entries, model) {
40
+ const curated = new Set(curatedListables().map((listable) => listable.asset.registryPath));
41
+ return (entries.find((entry) => entry.name === model) ??
42
+ entries.find((entry) => curated.has(entry.registryPath)) ??
43
+ entries[0]);
44
+ }
@@ -27,6 +27,7 @@ export interface NoRedirectFetchInit {
27
27
  validatedAddresses?: readonly string[] | undefined;
28
28
  maxBytes?: number;
29
29
  truncate?: boolean;
30
+ idleTimeoutMs?: number;
30
31
  }
31
32
  export interface NoRedirectFetchResponse {
32
33
  status: number;
@@ -3,7 +3,22 @@ import { HarnessError } from './errors.js';
3
3
  import { DEFAULT_USER_AGENT } from './user-agent.js';
4
4
  const UA_SNIFFING_HOSTS = new Set(['wttr.in']);
5
5
  export function runNoRedirectFetch(request, url, init = {}) {
6
- return new Promise((resolve, reject) => {
6
+ return new Promise((outerResolve, outerReject) => {
7
+ let idle = null;
8
+ const stopIdle = () => {
9
+ if (idle) {
10
+ clearTimeout(idle);
11
+ }
12
+ idle = null;
13
+ };
14
+ const resolve = (response) => {
15
+ stopIdle();
16
+ outerResolve(response);
17
+ };
18
+ const reject = (err) => {
19
+ stopIdle();
20
+ outerReject(err);
21
+ };
7
22
  const headers = { ...init.headers };
8
23
  if (init.body !== undefined &&
9
24
  !Object.keys(headers).some((h) => h.toLowerCase() === 'content-length')) {
@@ -16,6 +31,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
16
31
  }
17
32
  const method = init.method ?? 'GET';
18
33
  const req = request(url, { method, headers, validatedAddresses: init.validatedAddresses }, (res) => {
34
+ armIdle();
19
35
  const chunks = [];
20
36
  let received = 0;
21
37
  let settled = false;
@@ -45,6 +61,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
45
61
  reject(err);
46
62
  };
47
63
  res.on('data', (chunk) => {
64
+ armIdle();
48
65
  received += chunk.byteLength;
49
66
  if (init.maxBytes !== undefined && received > init.maxBytes) {
50
67
  if (init.truncate) {
@@ -67,6 +84,20 @@ export function runNoRedirectFetch(request, url, init = {}) {
67
84
  res.on('end', respond);
68
85
  });
69
86
  req.on('error', reject);
87
+ function armIdle() {
88
+ const ms = init.idleTimeoutMs;
89
+ if (ms === undefined) {
90
+ return;
91
+ }
92
+ stopIdle();
93
+ idle = setTimeout(() => {
94
+ const err = new Error(`no data received for ${ms} ms`);
95
+ err.name = 'TimeoutError';
96
+ req.destroy(err);
97
+ reject(err);
98
+ }, ms);
99
+ }
100
+ armIdle();
70
101
  if (init.signal) {
71
102
  const abort = () => {
72
103
  const err = new Error('This operation was aborted');
@@ -1,8 +1,9 @@
1
1
  export declare const RAG_CITATION_LINE = "After your answer, add one final line naming the files you used, written exactly as [Sources: file-a.pdf, file-b.md] - or [Sources: none] if the excerpts did not answer the question. This line is required, it is the only place square brackets belong, and it is removed before the user sees it.";
2
2
  export declare function currentTimeAnnotation(now?: Date): string;
3
- export declare function annotateLastUserTime<T extends {
3
+ export declare function annotateUserTimes<T extends {
4
4
  role: string;
5
5
  content: string;
6
+ sentAt?: number | undefined;
6
7
  }>(turns: ReadonlyArray<T>, now?: Date): T[];
7
8
  export interface SystemPromptInput {
8
9
  bio?: string | null | undefined;
@@ -22,25 +22,25 @@ export const RAG_CITATION_LINE = 'After your answer, add one final line naming t
22
22
  const METADATA_SECTION = `## Message Metadata
23
23
 
24
24
  User messages may include metadata such as [Current local time: ...]. This is contextual information provided by the system, not part of the user's query. Use it only when relevant and never repeat it unless the user asks about the current date or time.`;
25
+ const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
25
26
  export function currentTimeAnnotation(now = new Date()) {
26
27
  const p = (n) => String(n).padStart(2, '0');
27
- const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
28
+ const stamp = `${WEEKDAYS[now.getDay()]} ${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
28
29
  const offset = -now.getTimezoneOffset();
29
30
  const sign = offset < 0 ? '-' : '+';
30
31
  const abs = Math.abs(offset);
31
32
  return `[Current local time: ${stamp} (UTC${sign}${p(Math.floor(abs / 60))}:${p(abs % 60)})]`;
32
33
  }
33
- export function annotateLastUserTime(turns, now) {
34
- const result = [...turns];
35
- for (let i = result.length - 1; i >= 0; i--) {
36
- const turn = result[i];
37
- if (!turn || turn.role !== 'user') {
38
- continue;
39
- }
40
- result[i] = { ...turn, content: `${currentTimeAnnotation(now)}\n\n${turn.content}` };
41
- break;
42
- }
43
- return result;
34
+ export function annotateUserTimes(turns, now = new Date()) {
35
+ const lastUser = turns.findLastIndex((turn) => turn.role === 'user');
36
+ return turns.map((turn, i) => {
37
+ if (turn.role !== 'user')
38
+ return turn;
39
+ if (!turn.sentAt && i !== lastUser)
40
+ return turn;
41
+ const at = turn.sentAt ? new Date(turn.sentAt) : now;
42
+ return { ...turn, content: `${currentTimeAnnotation(at)}\n\n${turn.content}` };
43
+ });
44
44
  }
45
45
  function buildGuidelines(active) {
46
46
  const lines = [...BASE_GUIDELINES];
@@ -538,12 +538,13 @@ function completion(harness) {
538
538
  typedText: isRecord(frame.payload) && typeof frame.payload.typedText === 'string'
539
539
  ? frame.payload.typedText
540
540
  : undefined,
541
- messages: (frame.messages ?? []).map(({ role, content, attachments }) => ({
541
+ messages: (frame.messages ?? []).map(({ role, content, attachments, sentAt }) => ({
542
542
  role,
543
543
  content,
544
544
  attachments: attachments?.length
545
545
  ? attachments.map(({ path: file }) => ({ path: file }))
546
- : undefined
546
+ : undefined,
547
+ sentAt: sentAt || undefined
547
548
  })),
548
549
  toolConfigs: frame.toolConfigs ?? undefined,
549
550
  grantedDirs: frame.grantedDirs ?? undefined,
@@ -130,6 +130,7 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
130
130
  required: ['prompt']
131
131
  },
132
132
  effect: () => 'write',
133
+ deliversMany: true,
133
134
  resource: (args) => ({
134
135
  kind: 'image-edit',
135
136
  label: String(args.prompt ?? '').slice(0, 80)
@@ -264,13 +265,13 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
264
265
  'Next time write the prompt with explicit @imageN tokens in source order');
265
266
  }
266
267
  return {
267
- attachmentId: record.id,
268
+ attachments: [
269
+ { attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
270
+ ],
268
271
  ...(sources.length === 1 && sources[0].id
269
272
  ? { sourceAttachmentId: sources[0].id }
270
273
  : { sourceFileNames: sources.map((source) => source.fileName) }),
271
274
  note: notes.length ? notes.join('; ') : undefined,
272
- fileName: record.fileName,
273
- byteLength: record.byteLength,
274
275
  width,
275
276
  height
276
277
  };
@@ -19,6 +19,7 @@ export interface StageInputsOptions {
19
19
  export interface StagedInputs {
20
20
  files: readonly StagedInput[];
21
21
  }
22
+ export declare function uploadsAvailable(fetchAttachment: FetchAttachmentFn, { turnImages, signal }?: StageInputsOptions): Promise<number | null>;
22
23
  export declare function stageInputs(fetchAttachment: FetchAttachmentFn, inputs: readonly ExecInput[], opts?: StageInputsOptions): Promise<StagedInputs | ExecError>;
23
24
  export interface AttachOutputsOptions {
24
25
  readonly declared: readonly string[];
@@ -67,6 +67,17 @@ async function probeAttachment(fetchAttachment, id, { signal, deadline }) {
67
67
  }
68
68
  return { size: byteLengthOf(head), bytes: hasBytes(head) ? head.bytes : null };
69
69
  }
70
+ export async function uploadsAvailable(fetchAttachment, { turnImages = [], signal } = {}) {
71
+ if (turnImages.length) {
72
+ return turnImages.length;
73
+ }
74
+ try {
75
+ return (await bounded(fetchAttachment({ meta: true, signal }), STAGE_TIMEOUT_MS)) ? 1 : 0;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
70
81
  export async function stageInputs(fetchAttachment, inputs, opts = {}) {
71
82
  const { turnImages = [], signal } = opts;
72
83
  const files = inputs.map(() => null);
@@ -11,8 +11,8 @@ export const OBSIDIAN_VAULT_SETUP_REQUIRED = 'Obsidian vault file mode is not se
11
11
  'to switch tools.';
12
12
  export const OBSIDIAN_VAULT_MODE_NOTE = [
13
13
  'Runtime note — Obsidian vault file mode is active (a vault folder is configured):',
14
- '- Run vault commands through the `exec` tool, e.g. `obsidian vault info=path`, `obsidian search query="..."`, `obsidian read path="Folder/Note.md"`.',
15
- '- Start with `obsidian vault info=path` to confirm the configured vault.',
14
+ '- Run vault commands through the `exec` tool, e.g. `obsidian files`, `obsidian search query="..."`, `obsidian read path="Folder/Note.md"`.',
15
+ '- To list what is in the vault, run `obsidian files`. `read` takes a note name or a path inside the vault, never the vault folder.',
16
16
  '- `obsidian vaults` returns only the configured vault folder, not every vault in the Obsidian app.',
17
17
  '- App-only actions (open in app, plugin/sync/theme commands) are unavailable in this mode; they require the official Obsidian CLI connected to the running app.'
18
18
  ].join('\n');
@@ -2,6 +2,14 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { HarnessError } from '../../../errors.js';
4
4
  import { dailyCandidates, ensureWithinRoot, FRONTMATTER_RE, getArg, listFolders, listMarkdownFiles, parseFrontmatter, readFileText, resolveNotePath, todayStamp } from './vault-paths.js';
5
+ function statOrNull(p) {
6
+ try {
7
+ return fs.statSync(p);
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
5
13
  export function handleVault(vaultPath) {
6
14
  return JSON.stringify({ name: path.basename(vaultPath), path: vaultPath });
7
15
  }
@@ -17,9 +25,14 @@ export function handleVaults(vaultPath) {
17
25
  }
18
26
  export function handleRead(vaultPath, args) {
19
27
  const notePath = resolveNotePath(vaultPath, args);
20
- if (!notePath || !fs.existsSync(notePath)) {
28
+ const stat = notePath ? statOrNull(notePath) : null;
29
+ if (!notePath || !stat) {
21
30
  throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
22
31
  }
32
+ if (stat.isDirectory()) {
33
+ const folder = path.relative(path.resolve(vaultPath), notePath).split(path.sep).join('/');
34
+ throw new HarnessError('OBSIDIAN_PATH_IS_FOLDER', [folder]);
35
+ }
23
36
  return readFileText(notePath);
24
37
  }
25
38
  export function handleFiles(vaultPath, args) {
@@ -69,11 +82,7 @@ export function handleSearch(vaultPath, args) {
69
82
  return matches.join('\n') + truncated;
70
83
  }
71
84
  export function handleProperties(vaultPath, args) {
72
- const notePath = resolveNotePath(vaultPath, args);
73
- if (!notePath || !fs.existsSync(notePath)) {
74
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
75
- }
76
- return JSON.stringify(parseFrontmatter(readFileText(notePath)), null, 2);
85
+ return JSON.stringify(parseFrontmatter(handleRead(vaultPath, args)), null, 2);
77
86
  }
78
87
  function countTags(tagCounts, content) {
79
88
  for (const match of content.matchAll(/#([a-zA-Z0-9_/-]+)/g)) {
@@ -98,20 +107,12 @@ export function handleTags(vaultPath) {
98
107
  return sorted.map(([tag, count]) => `#${tag} (${count})`).join('\n') || '(no tags)';
99
108
  }
100
109
  export function handleWordcount(vaultPath, args) {
101
- const notePath = resolveNotePath(vaultPath, args);
102
- if (!notePath || !fs.existsSync(notePath)) {
103
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
104
- }
105
- const body = readFileText(notePath).replace(FRONTMATTER_RE, '').trim();
110
+ const body = handleRead(vaultPath, args).replace(FRONTMATTER_RE, '').trim();
106
111
  const words = body.split(/\s+/).filter(Boolean).length;
107
112
  return `${words} words`;
108
113
  }
109
114
  export function handleOutline(vaultPath, args) {
110
- const notePath = resolveNotePath(vaultPath, args);
111
- if (!notePath || !fs.existsSync(notePath)) {
112
- throw new HarnessError('OBSIDIAN_NOTE_NOT_FOUND', [args]);
113
- }
114
- const headings = readFileText(notePath)
115
+ const headings = handleRead(vaultPath, args)
115
116
  .split('\n')
116
117
  .filter((line) => /^#{1,6}\s/.test(line));
117
118
  return headings.join('\n') || '(no headings)';
@@ -313,6 +313,7 @@ export function createGenerateImageTool(runtime, clamps) {
313
313
  required: ['prompt']
314
314
  },
315
315
  effect: () => 'read',
316
+ deliversMany: true,
316
317
  resource: (args) => ({
317
318
  kind: 'image-generation',
318
319
  label: String(args.prompt ?? '').slice(0, 80)
@@ -359,9 +360,9 @@ export function createGenerateImageTool(runtime, clamps) {
359
360
  raw: true
360
361
  });
361
362
  return {
362
- attachmentId: record.id,
363
- fileName: record.fileName,
364
- byteLength: record.byteLength,
363
+ attachments: [
364
+ { attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
365
+ ],
365
366
  width: parsed.width,
366
367
  height: parsed.height
367
368
  };
@@ -1,6 +1,7 @@
1
1
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  export declare const MAX_RESPONSE_CHARS = 8192;
3
- export declare const TIMEOUT_MS = 10000;
3
+ export declare const IDLE_TIMEOUT_MS = 10000;
4
+ export declare const TIMEOUT_MS = 30000;
4
5
  export interface FetchInit {
5
6
  method: string;
6
7
  headers: Record<string, string>;
@@ -10,6 +11,7 @@ export interface FetchInit {
10
11
  validatedAddresses?: readonly string[] | undefined;
11
12
  maxBytes?: number;
12
13
  truncate?: boolean;
14
+ idleTimeoutMs?: number;
13
15
  }
14
16
  export declare function isRedirectStatus(status: number): boolean;
15
17
  export type ParseResult<T> = {
@@ -1,7 +1,8 @@
1
1
  import { isRecord } from '../../guards.js';
2
2
  const BLOCKED_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
3
3
  export const MAX_RESPONSE_CHARS = 8192;
4
- export const TIMEOUT_MS = 10_000;
4
+ export const IDLE_TIMEOUT_MS = 10_000;
5
+ export const TIMEOUT_MS = 30_000;
5
6
  export function isRedirectStatus(status) {
6
7
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
7
8
  }
@@ -1,2 +1,18 @@
1
- export declare function truncateResponseBody(body: string): string;
1
+ import type { ToolExecuteContext } from '../../capabilities/completion.ts';
2
+ export declare function responseRoomChars(ctxSize: number | undefined, cacheTokens: number | undefined): number | undefined;
3
+ type BudgetContext = Pick<ToolExecuteContext, 'ctxSize' | 'runBudget'> | undefined;
4
+ export declare function responseBudgetChars(ctx: BudgetContext): number;
5
+ export declare function capResponseBody(body: string, ctx: BudgetContext): CappedBody;
6
+ export interface ResponseCoverage {
7
+ readonly keptChars: number;
8
+ readonly totalChars: number;
9
+ readonly percent: number;
10
+ readonly note: string;
11
+ }
12
+ export interface CappedBody {
13
+ readonly body: string;
14
+ readonly truncated?: ResponseCoverage;
15
+ }
16
+ export declare function truncateResponseBody(body: string, budget: number): CappedBody;
2
17
  export declare const ELISION = "\u2026 [truncated]";
18
+ export {};
@@ -1,19 +1,61 @@
1
1
  import { MAX_RESPONSE_CHARS } from './request.js';
2
2
  import { isRecord } from '../../guards.js';
3
- export function truncateResponseBody(body) {
4
- if (body.length <= MAX_RESPONSE_CHARS)
5
- return body;
6
- return fitJson(body) ?? `${body.slice(0, MAX_RESPONSE_CHARS)}… [truncated]`;
3
+ const RESPONSE_FLOOR_CHARS = 2048;
4
+ export function responseRoomChars(ctxSize, cacheTokens) {
5
+ if (!ctxSize || !cacheTokens) {
6
+ return undefined;
7
+ }
8
+ return Math.floor(Math.max(0, ctxSize - cacheTokens) / 2);
9
+ }
10
+ export function responseBudgetChars(ctx) {
11
+ const room = ctx?.runBudget?.responseRoomChars;
12
+ if (room !== undefined) {
13
+ return Math.max(RESPONSE_FLOOR_CHARS, room);
14
+ }
15
+ const ctxSize = ctx?.ctxSize;
16
+ return ctxSize ? Math.max(MAX_RESPONSE_CHARS, Math.floor(ctxSize / 4)) : MAX_RESPONSE_CHARS;
17
+ }
18
+ export function capResponseBody(body, ctx) {
19
+ const capped = truncateResponseBody(body, responseBudgetChars(ctx));
20
+ const budget = ctx?.runBudget;
21
+ if (budget?.responseRoomChars !== undefined) {
22
+ budget.responseRoomChars = Math.max(0, budget.responseRoomChars - capped.body.length);
23
+ }
24
+ return capped;
25
+ }
26
+ const NOT_JSON = Symbol('not-json');
27
+ export function truncateResponseBody(body, budget) {
28
+ if (body.length <= budget) {
29
+ return { body };
30
+ }
31
+ const parsed = parseJson(body);
32
+ if (parsed !== NOT_JSON) {
33
+ const compact = JSON.stringify(parsed);
34
+ if (compact.length <= budget) {
35
+ return { body: compact };
36
+ }
37
+ const kept = JSON.stringify(fit(parsed, budget));
38
+ return { body: kept, truncated: coverageOf(Math.min(kept.length, budget), compact.length) };
39
+ }
40
+ const kept = `${body.slice(0, budget)}${ELISION}`;
41
+ return { body: kept, truncated: coverageOf(budget, body.length) };
42
+ }
43
+ function coverageOf(keptChars, totalChars) {
44
+ const percent = Math.max(1, Math.floor((keptChars / totalChars) * 100));
45
+ return {
46
+ keptChars,
47
+ totalChars,
48
+ percent,
49
+ note: `Only the first ${percent}% of this response was read, to fit the context window. Tell the user that your answer covers that part only.`
50
+ };
7
51
  }
8
- function fitJson(body) {
9
- let parsed;
52
+ function parseJson(body) {
10
53
  try {
11
- parsed = JSON.parse(body);
54
+ return JSON.parse(body);
12
55
  }
13
56
  catch {
14
- return null;
57
+ return NOT_JSON;
15
58
  }
16
- return JSON.stringify(fit(parsed, MAX_RESPONSE_CHARS));
17
59
  }
18
60
  const MARKER_CHARS = 64;
19
61
  function shrinkable(value) {