@qvac/harness 1.0.1 → 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 (93) hide show
  1. package/CHANGELOG.md +137 -6
  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/files/list-dir.js +79 -32
  55. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  56. package/dist-lib/lib/tools/fs/walk.js +64 -30
  57. package/dist-lib/lib/tools/office.js +8 -5
  58. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  59. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  60. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  61. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  62. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  63. package/dist-lib/plugins/image/generate-image.js +9 -1
  64. package/dist-lib/plugins/image/index.js +6 -2
  65. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  66. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  67. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  68. package/dist-lib/plugins/knowledge/index.js +1 -0
  69. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  70. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  71. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  72. package/dist-lib/plugins/knowledge/store.js +44 -16
  73. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  74. package/dist-lib/plugins/lsp/rpc.js +81 -17
  75. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  76. package/dist-lib/plugins/music/generate-music.js +14 -1
  77. package/dist-lib/plugins/music/index.js +4 -1
  78. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  79. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  80. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  81. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  82. package/dist-lib/schema/harness.js +28 -2
  83. package/dist-lib/spec/bind.js +3 -0
  84. package/dist-lib/spec/calls.js +1 -0
  85. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  86. package/dist-lib/spec/hrpc/index.js +15 -3
  87. package/dist-lib/spec/hrpc/messages.js +87 -6
  88. package/dist-lib/spec/hyperschema/index.js +87 -6
  89. package/dist-lib/spec/hyperschema/schema.json +70 -2
  90. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  91. package/package.json +29 -28
  92. package/scripts/addon-externals.cjs +1 -0
  93. package/worker/harness-sidecar.mjs +12 -1
package/dist-lib/index.js CHANGED
@@ -1,1163 +1,32 @@
1
- import fs from 'fs';
2
- import { platform, totalmem } from 'os';
3
- import process from 'process';
4
- import ReadyResource from 'ready-resource';
5
- import { HarnessError } from './lib/errors.js';
6
- import { probeGpuStats } from './lib/hardware/gpu-probe.js';
7
- import { probeCapabilityProfile } from './lib/hardware/capability-probe.js';
8
- import { Lifecycle } from './lib/lifecycle/index.js';
9
- import { Policy } from './lib/policy/index.js';
10
- import { EFFECT_DRAIN_TIMEOUT_MS, didDrainTimeOut, raceDrain } from './lib/helpers/drain.js';
11
- import { CompletionEngine } from './lib/capabilities/completion-engine/index.js';
12
- import { imageSettingsFrom } from './lib/helpers/image-settings.js';
13
- import { detectLanguage } from './lib/capabilities/detect-language.js';
14
- import { invoke } from './lib/capabilities/invoke.js';
15
- import { previewModelSource } from './lib/capabilities/preview-model-source.js';
16
- import { expandImagePrompt } from './lib/capabilities/enhance.js';
17
- import { download } from './lib/capabilities/download.js';
18
- import { Embeddings } from './lib/embeddings/index.js';
19
- import { deleteAllKvCaches, deleteKvCacheKey } from './lib/capabilities/kv-cache.js';
20
- import { kvCacheDir, PrefixTemplate } from './lib/capabilities/prefix-template.js';
21
- import { pushQueue } from './lib/queue.js';
22
- import { AbortedError } from './lib/helpers/race-abort.js';
23
- import { RunLatency } from './lib/helpers/run-latency.js';
24
- import { audioGenDownloadMetadata, categoryDownloadMetadata, customProjectionMap, defaultProjectionMap, catalogModelName, defaultVoiceModel, diffusionDownloadMetadata, infraModelsFor, speculativeDraft, modelNameToCapabilityProfile, residentSrc, setCustomModels } from './lib/models/model-catalog.js';
25
- import { customModelRows, isModelSourceCached, mergeCustomRows, listModels } from './lib/models/model-list.js';
26
- import { createDownloadGate } from './lib/models/download-gate.js';
27
- import { deleteModelFiles, summarizeDelete } from './lib/models/model-delete.js';
28
- import { createLoadTracker, createVoicePool, evictIdle, evictIdleWhere, isResident, leaseResidentModel, loadedModels, releaseModel, progressState } from './lib/models/model-pool.js';
29
- import { openclCacheDir } from './lib/models/opencl-cache.js';
30
- import { isSdkModelWedgedError } from './lib/models/sdk-faults.js';
31
- import { createSdkLoader } from './lib/sdk-loader.js';
32
- import { installAbortControllerPolyfill } from './lib/helpers/abort-polyfill.js';
33
- import { Residency } from './lib/residency/index.js';
34
- import { toolCatalog } from './lib/tools/catalog.js';
35
- import { SkillsHost } from './lib/skills-host/index.js';
36
- import { errorMessage, isRecord } from './lib/guards.js';
37
- import { Wire } from './lib/wire.js';
38
- import { HarnessLog } from './lib/log.js';
39
- import { HarnessServer } from './lib/serve.js';
40
- import { installResolutionDetector, resolutionDetail } from './lib/resolution-detector.js';
41
- import { bareRuntime } from './lib/tools/exec/bare-runtime.js';
42
- import { runCommand } from './lib/tools/exec/runner.js';
43
- import { createLocalRoots } from './lib/tools/fs/local.js';
44
- import { createRemoteRoots } from './lib/tools/fs/remote.js';
45
1
  export { CompletionEngine, ToolSets } from './lib/capabilities/completion-engine/index.js';
46
- export { renderedTools } from './lib/capabilities/sdk-tool.js';
47
- export const CONTEXT_OVERFLOW_MESSAGE = HarnessError.CONTEXT_OVERFLOW_MESSAGE;
48
- export { imageSettingsFrom } from './lib/helpers/image-settings.js';
2
+ export * from './lib/capabilities/download.js';
3
+ export { CAPABILITIES, isCapability } from './lib/capabilities/invoke.js';
4
+ export { renderedTools, toSdkTool } from './lib/capabilities/sdk-tool.js';
49
5
  export { skillInContext, unreadySkillState } from './lib/capabilities/skill-entry.js';
50
- export { toSdkTool } from './lib/capabilities/sdk-tool.js';
51
6
  export { attachmentTurn, loadedSkillsFrom, skillLoadedTurn } from './lib/capabilities/tool-turns.js';
52
- export { CAPABILITIES, isCapability } from './lib/capabilities/invoke.js';
53
- export * from './lib/capabilities/download.js';
7
+ export { connectHarness, HARNESS_DIED, RemoteHarness } from './lib/connect.js';
8
+ export { imageSettingsFrom } from './lib/helpers/image-settings.js';
54
9
  export * from './lib/models/model-catalog.js';
55
10
  export * from './lib/models/model-list.js';
56
11
  export { harnessChild, spawnHarness } from './lib/spawn.js';
57
12
  export * from './lib/tools/skills/catalog.js';
58
- export { requiredSettings, settingEnvName } from './lib/tools/skills/skill-settings.js';
59
- export { TOOLSETS, toolsetEnabled } from './lib/tools/toolsets.js';
60
13
  export { markCredentialRejected, markCredentialValid, recordCredentialHealth, resetAllCredentialHealth, resetCredentialHealth } from './lib/tools/skills/credential-health.js';
61
14
  export { readSetup as normalizeSkillSetup } from './lib/tools/skills/manifest-parse.js';
15
+ export { requiredSettings, settingEnvName } from './lib/tools/skills/skill-settings.js';
62
16
  export { isAvailableState, SKILL_STATE } from './lib/tools/skills/skill-state.js';
63
- export { connectHarness, HARNESS_DIED, RemoteHarness } from './lib/connect.js';
17
+ export { toolsetEnabled, TOOLSETS } from './lib/tools/toolsets.js';
18
+ import { HarnessError } from './lib/errors.js';
19
+ import { HarnessLog } from './lib/log.js';
20
+ import { PluginRegistry } from './lib/plugins/index.js';
21
+ import { HarnessServer } from './lib/serve.js';
22
+ export { HarnessLog, HarnessLog as harnessLog };
23
+ export const CONTEXT_OVERFLOW_MESSAGE = HarnessError.CONTEXT_OVERFLOW_MESSAGE;
64
24
  export const serveHarness = HarnessServer.serve;
65
- export { HarnessLog };
66
- export const harnessLog = HarnessLog;
67
25
  export const hlog = HarnessLog.info;
68
26
  export const setHarnessLog = HarnessLog.enable;
69
27
  export const setHarnessLogLevel = HarnessLog.setLevel;
70
28
  export const setHarnessLogSink = HarnessLog.setSink;
71
- import { HookPipeline } from './lib/hooks/index.js';
72
- import { Agent } from './lib/agent/index.js';
73
- export { HookPipeline };
74
- export { Policy };
75
- import { createGuardedFetch } from './lib/guarded-fetch.js';
76
- import { PluginRegistry } from './lib/plugins/index.js';
77
- import { createExecTool } from './lib/tools/exec.js';
78
- import { canonicalDenyRoots, defaultRealpath, deniedRootsFor } from './lib/tools/fs/scope.js';
79
29
  export const PLUGIN_API_VERSION = PluginRegistry.API_VERSION;
80
- const SUSPEND_SETTLE_MS = 500;
81
- const SPEECH_PLUGIN_MISSING = 'speech needs the speech plugin';
82
- const KNOWLEDGE_PLUGIN_MISSING = 'knowledge needs the knowledge plugin';
83
- const OCR_PLUGIN_MISSING = 'ocr needs the ocr plugin';
84
- const MEDIA_ROUND_SERVICES = { image: 'image-rounds', music: 'music-rounds' };
85
- const UNLOAD_FAILED = 'Runtime unload failed; close the harness before loading models again';
86
- const HOST_SHELL = { name: 'host' };
87
- function execOptions(exec) {
88
- if (!exec)
89
- return null;
90
- return exec === true ? {} : exec;
91
- }
92
- export class Harness extends ReadyResource {
93
- _hostTools;
94
- _tools;
95
- _capabilities = [];
96
- _sdk;
97
- _loads = createLoadTracker();
98
- _downloads;
99
- _hold;
100
- _residency;
101
- _embeddings;
102
- _voicePools = new Map();
103
- _skills;
104
- _lifecycle;
105
- _closeRetryNeeded = false;
106
- _modelsDir;
107
- _skillsDir;
108
- _exec;
109
- _deniedRoots;
110
- _policy;
111
- _shell;
112
- _projectionModel;
113
- _customProjection = {};
114
- _speculative;
115
- _contextSize;
116
- _recentFits = new Map();
117
- _gpuStats;
118
- _capability = null;
119
- _capabilityInflight = null;
120
- _hostHooks;
121
- _hooks;
122
- _plugins;
123
- _prefix;
124
- _pluginMode;
125
- _pluginsStarted = null;
126
- constructor({ tools = [], sdkLoader, skillsDir, modelsDir, sdkHome, exec, projectionModel, llmDevice, llmGpuLayers, contextSize, kvCacheK, kvCacheV, llmLoad, slots, embedDevice, embedGpuLayers, embedBatchSize, transcriptionDevice, completionModelCap, credentialStore, platform, gpuStats, hooks, plugins = [], pluginMode = 'frozen', policy } = {}) {
127
- super();
128
- this._exec = execOptions(exec);
129
- if (this._exec && tools.some((tool) => tool.name === PluginRegistry.EXEC_TOOL)) {
130
- throw new Error(`tools has '${PluginRegistry.EXEC_TOOL}', which the harness builds when exec is set`);
131
- }
132
- this._deniedRoots = sdkHome === undefined ? undefined : deniedRootsFor(sdkHome);
133
- this._policy = policy;
134
- this._plugins = new PluginRegistry(plugins, {
135
- services: { models: this._modelHost(transcriptionDevice), embed: this._embedHost() },
136
- exec: this._exec !== null,
137
- deniedRoots: this._deniedRoots ?? []
138
- });
139
- this._pluginMode = pluginMode;
140
- installAbortControllerPolyfill();
141
- this._hostHooks = Object.freeze([...(hooks ?? HookPipeline.defaults())]);
142
- this._hooks = this._hostHooks;
143
- this._sdk = sdkLoader ?? createSdkLoader();
144
- this._prefix =
145
- sdkHome === undefined
146
- ? null
147
- : new PrefixTemplate({ cacheDir: kvCacheDir(sdkHome), sdk: () => this._sdk.load() });
148
- this._lifecycle = new Lifecycle({
149
- resource: this,
150
- sdk: { peek: () => this._sdk.peek() },
151
- loads: this._loads,
152
- releases: {
153
- pools: () => [
154
- this._residency.destroy(),
155
- this._embeddings.destroy(),
156
- ...[...this._voicePools.values()].map((entry) => entry.pool.destroy())
157
- ],
158
- runtimes: () => [],
159
- plugins: () => this._plugins.unload()
160
- },
161
- models: () => loadedModels(this._residency.pool).map((entry) => entry.model),
162
- recreate: () => {
163
- this._residency.recreate();
164
- this._embeddings.recreate();
165
- for (const entry of this._voicePools.values()) {
166
- entry.pool = this._createVoicePool(entry.spec);
167
- }
168
- },
169
- statusChanged: () => this._residency.invalidateStatus(),
170
- teardown: async () => {
171
- await this._prefix?.close();
172
- await this._skills.close();
173
- await this._teardownPlugins();
174
- }
175
- });
176
- this._gpuStats = gpuStats;
177
- this._hostTools = tools;
178
- this._tools = tools;
179
- this._projectionModel = projectionModel ?? defaultProjectionMap();
180
- this._speculative = llmLoad?.speculative === true;
181
- this._modelsDir = modelsDir;
182
- this._skillsDir = skillsDir;
183
- this._skills = new SkillsHost({
184
- skillsDir,
185
- platform,
186
- credentialStore,
187
- tools: () => this._tools,
188
- startPlugins: () => this._startPlugins()
189
- });
190
- this._downloads = createDownloadGate({
191
- isCached: (model, addon) => this._isModelCached(model, addon),
192
- onHeld: ({ model, addon }) => this._residency.notify({ status: 'held', model, addon }),
193
- onDropped: ({ model, addon }) => this._residency.notify({ status: 'error', model, addon, message: 'aborted' })
194
- });
195
- this._hold = (model, addon, signal) => this._downloads.hold(catalogModelName(model, addon), addon, signal);
196
- this._contextSize = contextSize;
197
- this._residency = new Residency({
198
- llmDevice,
199
- llmGpuLayers,
200
- contextSize,
201
- kvCacheK,
202
- kvCacheV,
203
- llmLoad,
204
- slots,
205
- completionModelCap,
206
- modelsDir: this._modelsDir,
207
- sdk: { load: () => this._sdk.load() },
208
- loads: this._loads,
209
- gate: this._lifecycle,
210
- hold: this._hold,
211
- capability: () => this.capability(),
212
- emit: (state) => this.emit('model', state),
213
- projectionFor: (model) => this._projectionFor(model),
214
- pools: () => [
215
- ...this._embeddings.pools(),
216
- ...[...this._voicePools.values()].map((entry) => entry.pool)
217
- ],
218
- poolFor: (addon, model) => {
219
- if (addon === 'embeddings') {
220
- return this._embeddings.target(model);
221
- }
222
- const entry = this._voicePools.get(addon);
223
- if (!entry) {
224
- throw new Error(SPEECH_PLUGIN_MISSING);
225
- }
226
- const key = residentSrc(model, addon);
227
- return {
228
- pool: entry.pool,
229
- key,
230
- modelType: entry.spec.modelType,
231
- needsRoom: entry.spec.needsRoom?.(key) ?? false,
232
- open: () => entry.pool.open(key, key)
233
- };
234
- },
235
- embedRoom: (model, target) => this._embeddings.makeRoom(model, target),
236
- evictIdle: () => [
237
- ...this._embeddings.evictIdle(),
238
- ...[...this._voicePools.values()].map((entry) => evictIdle(entry.pool))
239
- ],
240
- unloadIdlePlugins: () => this._plugins.unloadIdle(),
241
- tools: () => this._tools,
242
- skills: (agentId, model, trees) => this._skills.completionSkills(agentId, model, trees),
243
- platform: () => this._skills.platform
244
- });
245
- this._embeddings = new Embeddings({
246
- device: embedDevice,
247
- gpuLayers: embedGpuLayers,
248
- batchSize: embedBatchSize,
249
- sdk: { loadEmbed: () => this._sdk.loadEmbed() },
250
- loads: this._loads,
251
- gate: this._lifecycle,
252
- notify: (state) => this._residency.notify(state),
253
- settleFit: (query) => this._residency.fit.settle(query),
254
- evictIdleChat: () => this._residency.evictIdleChat(),
255
- beforeLoad: (load) => this._residency.beforeLoad(load),
256
- hold: this._hold
257
- });
258
- }
259
- async _open() {
260
- try {
261
- installResolutionDetector(import.meta);
262
- const core = PluginRegistry.loadAddons('the harness', this._sdk.addons);
263
- core.catch(noop);
264
- await this._startPlugins();
265
- await this._loadAddons(core);
266
- await this._skills.open();
267
- HarnessLog.info('open', { skills: this._skills.names.length, tools: this._tools.length });
268
- }
269
- catch (error) {
270
- await this._teardownPlugins();
271
- throw error;
272
- }
273
- }
274
- _startPlugins() {
275
- this._pluginsStarted ??= this._runPluginStart();
276
- return this._pluginsStarted;
277
- }
278
- async _runPluginStart() {
279
- const reserved = this._hostTools.map((tool) => tool.name);
280
- if (this._exec) {
281
- reserved.push(PluginRegistry.EXEC_TOOL);
282
- }
283
- const started = await this._plugins.start([...reserved, Agent.TRANSFER_TOOL_NAME, Agent.DELEGATE_TOOL_NAME], {
284
- fetch: (signal, mayConnect) => createGuardedFetch({ signal, mayConnect }),
285
- publish: (swapped) => this._publishPlugins(swapped)
286
- });
287
- this._publishPlugins(started);
288
- }
289
- _publishPlugins({ tools, capabilities, hooks, skills, exec }) {
290
- const pre = hooks.filter((hook) => hook.phase === 'preToolCall');
291
- const rest = hooks.filter((hook) => hook.phase !== 'preToolCall');
292
- this._tools = Object.freeze([...this._hostTools, ...this._execTools(exec), ...tools]);
293
- this._shell = exec.shell;
294
- this._capabilities = Object.freeze(capabilities);
295
- this._hooks = Object.freeze([...pre, ...this._hostHooks, ...rest]);
296
- this._skills.publish(skills);
297
- }
298
- _execTools(exec) {
299
- if (!this._exec) {
300
- return [];
301
- }
302
- return [
303
- createExecTool({
304
- ...this._exec,
305
- ...exec,
306
- deniedRoots: this._deniedRoots,
307
- skillsDir: this._skillsDir,
308
- skillSettings: (skill, agentId) => this._skills.skillSettings(skill, agentId),
309
- skillEnv: (skill) => this._skills.skillEnv(skill)
310
- })
311
- ];
312
- }
313
- async addPlugin(plugin) {
314
- await this._dynamicPlugins();
315
- await this._plugins.add(plugin);
316
- }
317
- async removePlugin(name) {
318
- await this._dynamicPlugins();
319
- await this._plugins.remove(name);
320
- }
321
- async reloadPlugin(name, plugin) {
322
- await this._dynamicPlugins();
323
- await this._plugins.reload(name, plugin);
324
- }
325
- async _dynamicPlugins() {
326
- if (this._pluginMode !== 'dynamic') {
327
- throw new Error("plugins are frozen: construct the harness with pluginMode 'dynamic'");
328
- }
329
- if (!this.opened)
330
- await this.ready();
331
- this._lifecycle.assertNotClosing();
332
- }
333
- _modelHost(transcriptionDevice) {
334
- const residency = () => this._residency;
335
- return {
336
- transcriptionDevice,
337
- sdk: () => this._sdk.load(),
338
- track: (load, sdk) => this._loads.track(load, sdk),
339
- makeRoom: (signal, busy, srcs) => this._residency.makeRoomForPlugin(signal, busy, srcs),
340
- hold: this._hold,
341
- isCached: (model, addon) => this._isModelCached(catalogModelName(model, addon), addon),
342
- get requests() {
343
- return residency().requests;
344
- },
345
- completionModel: (model, signal) => this._residency.borrow(model, signal),
346
- emit: (state) => this.emit('model', state),
347
- progressState,
348
- statusChanged: () => this._residency.statusChanged(),
349
- registerPool: (spec) => this._registerPool(spec),
350
- enterWork: () => {
351
- if (this._lifecycle.suspended) {
352
- throw new HarnessError('HARNESS_SUSPENDED');
353
- }
354
- return this._lifecycle.enterWork();
355
- }
356
- };
357
- }
358
- _registerPool(spec) {
359
- const entry = { spec, pool: this._createVoicePool(spec) };
360
- this._voicePools.set(spec.addon, entry);
361
- return {
362
- open: (model) => {
363
- const pool = entry.pool;
364
- const handle = pool.open(model, model);
365
- return {
366
- load: async () => {
367
- const { modelId } = await handle.load();
368
- this._lifecycle.assertNotClosing();
369
- return { modelId };
370
- },
371
- peek: () => handle.peek(),
372
- release: () => releaseModel(pool, model)
373
- };
374
- },
375
- resident: (model) => isResident(entry.pool, model),
376
- evictIdle: (wanted) => evictIdleWhere(entry.pool, wanted)
377
- };
378
- }
379
- _createVoicePool({ sdk, label, openclCache, ...spec }) {
380
- return createVoicePool(() => sdk(), (state) => this._residency.notify(label ? { ...state, model: label } : state), {
381
- ...spec,
382
- openclCacheDir: openclCache ? openclCacheDir : undefined,
383
- loads: this._loads,
384
- onUnloadFailure: (modelId, error) => this._lifecycle.recordModelUnloadFailure(modelId, error),
385
- beforeLoad: (load) => this._residency.beforeLoad(load),
386
- hold: this._hold
387
- });
388
- }
389
- _embedHost() {
390
- return {
391
- embed: (request) => this.embed(request),
392
- sdk: () => this._sdk.loadEmbed()
393
- };
394
- }
395
- async _loadAddons(core) {
396
- await Promise.all([
397
- core,
398
- ...this._tools.map((tool) => PluginRegistry.loadAddons(`tool '${tool.name}'`, tool.addons))
399
- ]);
400
- }
401
- _teardownPlugins() {
402
- return this._plugins.teardown((plugin, error) => HarnessLog.info('plugin teardown failed', { plugin, err: errorMessage(error) }));
403
- }
404
- get suspended() {
405
- return this._lifecycle.suspended;
406
- }
407
- get skillNames() {
408
- return this._skills.names;
409
- }
410
- setCredentials(entries) {
411
- this._skills.setCredentials(entries);
412
- }
413
- setSkillSettings(entries) {
414
- this._skills.setSkillSettings(entries);
415
- }
416
- skillSettings(skill, agentId) {
417
- return this._skills.skillSettings(skill, agentId);
418
- }
419
- listManagedSkills() {
420
- return this._skills.listManagedSkills();
421
- }
422
- readSkillFile(name) {
423
- return this._skills.readSkillFile(name);
424
- }
425
- writeSkillFile(name, content) {
426
- return this._skills.writeSkillFile(name, content);
427
- }
428
- copyBaseForEdit(name) {
429
- return this._skills.copyBaseForEdit(name);
430
- }
431
- deleteOverlaySkill(name) {
432
- return this._skills.deleteOverlaySkill(name);
433
- }
434
- resolveCredential(key, ctx) {
435
- return this._skills.resolveCredential(key, ctx);
436
- }
437
- async skills(agentId, modelName, options) {
438
- if (!this.opened)
439
- await this.ready();
440
- this._lifecycle.assertNotClosing();
441
- return this._skills.statuses(agentId, modelName, options);
442
- }
443
- async tools() {
444
- if (!this.opened)
445
- await this.ready();
446
- return toolCatalog(this._tools);
447
- }
448
- get toolNames() {
449
- return this._tools.map((tool) => tool.name);
450
- }
451
- get supportsImages() {
452
- if (!this._projectionModel)
453
- return false;
454
- if (typeof this._projectionModel === 'string')
455
- return true;
456
- return Object.keys(this._projectionModel).length > 0;
457
- }
458
- supportsImagesFor(model) {
459
- return Boolean(this._projectionFor(model));
460
- }
461
- _draftFor(model) {
462
- return this._speculative ? speculativeDraft(model)?.model?.src : undefined;
463
- }
464
- _projectionFor(model) {
465
- const custom = this._customProjection[model];
466
- if (custom) {
467
- return custom;
468
- }
469
- const projection = this._projectionModel;
470
- if (!projection) {
471
- return undefined;
472
- }
473
- return typeof projection === 'string' ? projection : projection[model];
474
- }
475
- setCustomModels(entries) {
476
- setCustomModels(entries);
477
- this._customProjection = customProjectionMap();
478
- }
479
- setModelIdleTimeout(ms) {
480
- this._residency.setIdleTimeout(ms);
481
- }
482
- async setModelMemoryCap(percent) {
483
- await this._residency.setMemoryCap(percent);
484
- }
485
- async memoryUsage() {
486
- return { usedBytes: this._residency.settledBytes() };
487
- }
488
- setDownloadsAllowed({ allowed }) {
489
- this._downloads.setAllowed(allowed);
490
- }
491
- async _isModelCached(model, addon) {
492
- const row = (await this.list({ type: addon })).find((entry) => entry.name === model);
493
- if (row) {
494
- return row.isCached;
495
- }
496
- const sdk = await this._sdk.load();
497
- return isModelSourceCached(sdk, { model, addon, modelsDir: this._modelsDir });
498
- }
499
- previewModelSource(context) {
500
- return previewModelSource(context, {
501
- assessFit: (query) => this._residency.fit.assess(query),
502
- contextSize: this._contextSize,
503
- recentFits: this._recentFits
504
- });
505
- }
506
- async describe() {
507
- if (!this.opened)
508
- await this.ready();
509
- return {
510
- toolNames: this.toolNames,
511
- skills: this._skills.names,
512
- supportsImages: this.supportsImages,
513
- supportsKvCacheDeletion: true
514
- };
515
- }
516
- diagnostics() {
517
- return {
518
- models: this.opened ? this._residency.loaded() : [],
519
- suspended: this.suspended,
520
- sdkLoaded: this._sdk.peek() !== null,
521
- toolNames: this.toolNames,
522
- skills: this._skills.names,
523
- device: this._residency.deviceConfig().device
524
- };
525
- }
526
- getEmbeddingDevice() {
527
- return this._embeddings.device;
528
- }
529
- setEmbeddingDevice(device) {
530
- return this._embeddings.setDevice(device);
531
- }
532
- async presuspend() {
533
- await this._lifecycle.send('PRESUSPEND', { open: false });
534
- }
535
- async suspend() {
536
- this._downloads.abandon();
537
- const result = await raceDrain(this._lifecycle.send('SUSPEND'), SUSPEND_SETTLE_MS);
538
- if (didDrainTimeOut(result)) {
539
- HarnessLog.info('suspend still waiting for active work to settle');
540
- }
541
- }
542
- async resume() {
543
- await this._lifecycle.send('RESUME');
544
- }
545
- async wakeup() {
546
- await this._lifecycle.send('WAKEUP');
547
- }
548
- ready() {
549
- if (this._lifecycle.closeRequested || this.closing || this.closed) {
550
- return Promise.reject(new HarnessError('HARNESS_CLOSING'));
551
- }
552
- return super.ready();
553
- }
554
- async _close() {
555
- HarnessLog.info('closing');
556
- this._residency.closeIdle();
557
- this._downloads.abandon();
558
- await this._lifecycle.close();
559
- }
560
- close() {
561
- this._lifecycle.requestClose();
562
- if (this._closeRetryNeeded) {
563
- this.closing = null;
564
- this._closeRetryNeeded = false;
565
- }
566
- const pending = !this.opened && this.opening !== null ? this._closeWhileOpening() : super.close();
567
- void pending.catch(() => {
568
- if (this.closing === pending) {
569
- this._closeRetryNeeded = true;
570
- }
571
- });
572
- const bounded = raceDrain(pending, EFFECT_DRAIN_TIMEOUT_MS).then((result) => {
573
- if (didDrainTimeOut(result)) {
574
- throw new Error('Harness close is still waiting for active work to settle');
575
- }
576
- });
577
- void bounded.catch(noop);
578
- return bounded;
579
- }
580
- _closeWhileOpening() {
581
- if (this.closing)
582
- return this.closing;
583
- const opening = this.opening;
584
- const pluginsClosing = this._teardownPlugins();
585
- const pending = (async () => {
586
- await opening?.catch(noop);
587
- await pluginsClosing;
588
- this._lifecycle.abortCompletions();
589
- this._loads.drain();
590
- await this._lifecycle.finishClose();
591
- this.closed = true;
592
- this.emit('close');
593
- })();
594
- this.closing = pending;
595
- return pending;
596
- }
597
- download(args) {
598
- this._lifecycle.assertNotClosing();
599
- let releaseWork = null;
600
- const llm = (args.addon ?? 'llm') === 'llm';
601
- const projection = llm ? this._projectionFor(args.model) : undefined;
602
- const draft = llm ? this._draftFor(args.model) : undefined;
603
- const multiFile = diffusionDownloadMetadata(args.model, args.addon) ??
604
- audioGenDownloadMetadata(args.model, args.addon) ??
605
- categoryDownloadMetadata(args.model, args.addon);
606
- return download(async () => {
607
- if (!this.opened)
608
- await this.ready();
609
- releaseWork = this._lifecycle.enterWork();
610
- try {
611
- const sdk = await this._sdk.load();
612
- this._lifecycle.assertNotClosing();
613
- return {
614
- ...sdk,
615
- downloadAsset: (opts) => this._loads.track(sdk.downloadAsset(opts), sdk)
616
- };
617
- }
618
- catch (error) {
619
- releaseWork?.();
620
- releaseWork = null;
621
- throw error;
622
- }
623
- }, {
624
- ...args,
625
- projection,
626
- companions: draft ? [...(multiFile?.companions ?? []), draft] : multiFile?.companions,
627
- assetSizes: multiFile?.assetSizes
628
- }, (event) => {
629
- this._residency.invalidateStatus();
630
- if (event.type === 'complete') {
631
- this._downloads.downloaded();
632
- }
633
- }, () => {
634
- releaseWork?.();
635
- releaseWork = null;
636
- });
637
- }
638
- embed(context) {
639
- return this._residency.busy(() => this._embeddings.embed(context));
640
- }
641
- async _speechService() {
642
- if (!this.opened)
643
- await this.ready();
644
- if (!this._plugins.ctx.speech) {
645
- throw new Error(SPEECH_PLUGIN_MISSING);
646
- }
647
- return this._plugins.ctx.speech;
648
- }
649
- async _knowledgeService() {
650
- if (!this.opened)
651
- await this.ready();
652
- if (!this._plugins.ctx.knowledge) {
653
- throw new Error(KNOWLEDGE_PLUGIN_MISSING);
654
- }
655
- return this._plugins.ctx.knowledge;
656
- }
657
- async knowledgeUpsert(artifact) {
658
- return (await this._knowledgeService()).upsert(artifact);
659
- }
660
- async knowledgeRemove(artifactId) {
661
- return (await this._knowledgeService()).remove(artifactId);
662
- }
663
- async knowledgeSearch(query) {
664
- return (await this._knowledgeService()).search(query);
665
- }
666
- async knowledgeStatus() {
667
- return (await this._knowledgeService()).status();
668
- }
669
- transcribe(context) {
670
- return this._residency.busy(() => this._transcribe(context));
671
- }
672
- async _transcribe({ model, audio, signal }) {
673
- const speech = await this._speechService();
674
- return speech.transcribe({
675
- model: model || defaultVoiceModel('transcription'),
676
- audio,
677
- signal
678
- });
679
- }
680
- ocrRead({ image, signal }) {
681
- return this._residency.busy(async () => (await this._ocrService()).read(image, signal));
682
- }
683
- async _ocrService() {
684
- if (!this.opened)
685
- await this.ready();
686
- if (!this._plugins.ctx.ocr) {
687
- throw new Error(OCR_PLUGIN_MISSING);
688
- }
689
- return this._plugins.ctx.ocr;
690
- }
691
- detectLanguage(context) {
692
- return detectLanguage(context);
693
- }
694
- speak(context) {
695
- return this._residency.busy(() => this._speak(context));
696
- }
697
- async _speak({ model, text, signal }) {
698
- const speech = await this._speechService();
699
- return speech.speak({ model: model || (await this._defaultTts(speech)), text, signal });
700
- }
701
- speakStream(context) {
702
- return this._residency.busyStream(() => this._speakStream(context));
703
- }
704
- async *_speakStream({ model, text, signal }) {
705
- const speech = await this._speechService();
706
- yield* speech.speakStream({ model: model || (await this._defaultTts(speech)), text, signal });
707
- }
708
- async _defaultTts(speech) {
709
- const profile = await this.capability().then((capability) => capability.capabilityProfile, () => null);
710
- return speech.defaultModel(profile);
711
- }
712
- async list(options = {}) {
713
- if (!this.opened)
714
- await this.ready();
715
- const releaseWork = this._lifecycle.enterWork();
716
- try {
717
- const sdk = await this._sdk.load();
718
- this._lifecycle.assertNotClosing();
719
- const rows = await listModels(sdk, options, {
720
- cache: this._residency.status,
721
- projectionFor: (name) => this._projectionFor(name),
722
- draftFor: (name) => this._draftFor(name)
723
- });
724
- const loaded = this._residency.settled();
725
- const loading = this._residency.loading();
726
- const custom = await customModelRows(options, { modelsDir: this._modelsDir, loaded });
727
- const merged = mergeCustomRows(rows, custom);
728
- const fits = await this._residency.rowFits(merged);
729
- const memory = this._residency.memoryByModel();
730
- return merged.map((row) => {
731
- const fit = row.isLoaded || loaded.has(row.name) ? undefined : fits.get(row.registryPath);
732
- return {
733
- ...row,
734
- isLoading: loading.has(row.name),
735
- memoryBytes: memory.get(row.name) ?? memory.get(residentSrc(row.name, row.type)),
736
- fit: fit?.verdict,
737
- fitBasis: fit?.basis,
738
- fitEvidence: fit?.evidence
739
- };
740
- });
741
- }
742
- finally {
743
- releaseWork();
744
- }
745
- }
746
- async deleteModel(name) {
747
- if (!this.opened)
748
- await this.ready();
749
- const releaseWork = this._lifecycle.enterWork();
750
- try {
751
- const sdk = await this._sdk.load();
752
- this._lifecycle.assertNotClosing();
753
- const result = await deleteModelFiles(sdk, name, { modelsDir: this._modelsDir });
754
- this._residency.invalidateStatus();
755
- return summarizeDelete(result);
756
- }
757
- finally {
758
- releaseWork();
759
- }
760
- }
761
- async clearKvCache() {
762
- if (!this.opened)
763
- await this.ready();
764
- const releaseWork = this._lifecycle.enterWork();
765
- try {
766
- return await deleteAllKvCaches(() => {
767
- this._lifecycle.assertNotClosing();
768
- return this._sdk.load();
769
- });
770
- }
771
- finally {
772
- releaseWork();
773
- }
774
- }
775
- async deleteKvCache(kvCacheKey) {
776
- if (!this.opened)
777
- await this.ready();
778
- const releaseWork = this._lifecycle.enterWork();
779
- try {
780
- return await deleteKvCacheKey(() => {
781
- this._lifecycle.assertNotClosing();
782
- return this._sdk.load();
783
- }, kvCacheKey);
784
- }
785
- finally {
786
- releaseWork();
787
- }
788
- }
789
- async infraModels(profile) {
790
- return infraModelsFor(profile);
791
- }
792
- async capability() {
793
- if (!this.opened)
794
- await this.ready();
795
- this._lifecycle.assertNotClosing();
796
- if (this._capability) {
797
- return this._capability;
798
- }
799
- if (this._capabilityInflight) {
800
- return this._capabilityInflight;
801
- }
802
- const reads = {
803
- totalmem,
804
- platform,
805
- readFile: async (path) => {
806
- try {
807
- return String(await fs.promises.readFile(path, 'utf8'));
808
- }
809
- catch {
810
- return null;
811
- }
812
- },
813
- run: async (command) => {
814
- try {
815
- const runtime = await bareRuntime();
816
- const result = await runCommand(command, { ...runtime, timeoutMs: 5_000 });
817
- return result.exitCode === 0 ? result.stdout : null;
818
- }
819
- catch {
820
- return null;
821
- }
822
- },
823
- readGpuStats: () => (this._gpuStats !== undefined ? this._gpuStats : probeGpuStats())
824
- };
825
- this._capabilityInflight = probeCapabilityProfile(reads)
826
- .then((capability) => {
827
- capability = { ...capability, hostRunLog: true, hostRunLogVersion: 1 };
828
- this._capability = capability;
829
- return capability;
830
- })
831
- .finally(() => {
832
- this._capabilityInflight = null;
833
- });
834
- return this._capabilityInflight;
835
- }
836
- warmModel(context) {
837
- return this._residency.busy(() => this._residency.warm(context));
838
- }
839
- loadModel(context) {
840
- return this._residency.busy(() => this._residency.load(context));
841
- }
842
- unloadModel(context) {
843
- return this._residency.busy(() => this._residency.unload(context));
844
- }
845
- invoke(context) {
846
- return this._residency.busyStream(() => this._invoke(context));
847
- }
848
- async *_invoke({ capability, args, enhance, agent, attach, fetchAttachment, progress, signal }) {
849
- if (!this.opened)
850
- await this.ready();
851
- if (this.suspended) {
852
- this._lifecycle.assertNotClosing();
853
- return yield { type: 'aborted' };
854
- }
855
- const releaseWork = this._lifecycle.enterWork();
856
- HarnessLog.info('invoke start', { capability, enhance });
857
- try {
858
- yield* invoke({
859
- capability,
860
- args,
861
- enhance,
862
- enhancer: this._residentEnhancer(),
863
- tools: [...this._tools, ...this._capabilities],
864
- ctx: {
865
- image: imageSettingsFrom(agent),
866
- attach,
867
- fetchAttachment,
868
- progress,
869
- signal
870
- }
871
- });
872
- }
873
- finally {
874
- HarnessLog.info('invoke end', { capability });
875
- releaseWork();
876
- }
877
- }
878
- completion(context) {
879
- if (!context.agents) {
880
- const { hopLog, ...run } = context;
881
- return this._completion({ ...run, ...hopLog?.({ index: 0, agent: run.agent?.id ?? '' }) });
882
- }
883
- if (context.boot || context.onStep) {
884
- throw new TypeError('A run that follows handoffs cannot take boot or onStep; give it a hopLog, or run it over the wire with a HostRunLog');
885
- }
886
- return Agent.follow({ completion: (hop) => this._completion(hop) }, { ...context, goal: undefined });
887
- }
888
- async serveModelRound(request, io) {
889
- if (!this.opened)
890
- await this.ready();
891
- this._lifecycle.assertNotClosing();
892
- if (this.suspended || this._lifecycle.draining) {
893
- throw new HarnessError('HARNESS_SUSPENDED');
894
- }
895
- if (this._lifecycle.unloadFailed) {
896
- throw new Error(UNLOAD_FAILED);
897
- }
898
- const { modelId } = request;
899
- const { key, acquireRound: acquire } = this._residency.servedRound(modelId, request.load);
900
- const acquireRound = this._seeding(acquire, modelId);
901
- let served;
902
- const round = this._lifecycle.trackCompletion((signal) => this._residency.busyStream(async function* () {
903
- served = await CompletionEngine.serveModelRound(request, { signal, emit: (event) => io.emit(event), retake: () => io.retake() }, { acquireRound });
904
- }), io.signal);
905
- const releasePrefix = this._prefix?.holdServed(request.runId);
906
- try {
907
- await round.next();
908
- }
909
- catch (err) {
910
- throw await this._servedRoundFailed(err, modelId, key);
911
- }
912
- finally {
913
- releasePrefix?.(Boolean(served?.final.toolCalls.length));
914
- }
915
- if (!served) {
916
- throw new Error('A served round ended without its result');
917
- }
918
- this._residency.clearFaults(modelId);
919
- return served;
920
- }
921
- async serveMediaRound(request, io) {
922
- if (!this.opened)
923
- await this.ready();
924
- this._lifecycle.assertNotClosing();
925
- if (this.suspended || this._lifecycle.draining) {
926
- throw new HarnessError('HARNESS_SUSPENDED');
927
- }
928
- const releasePlugins = await this._plugins.hold();
929
- try {
930
- const server = this._plugins.ctx[MEDIA_ROUND_SERVICES[request.kind]];
931
- if (!server) {
932
- throw new HarnessError('MEDIA_MODEL_MISSING', [
933
- request.kind,
934
- request.modelChoice ?? 'default'
935
- ]);
936
- }
937
- const leave = this._lifecycle.enterWork();
938
- try {
939
- return await server.serve(request, io);
940
- }
941
- finally {
942
- leave();
943
- }
944
- }
945
- finally {
946
- releasePlugins();
947
- }
948
- }
949
- async _servedRoundFailed(err, model, key) {
950
- const aborted = err instanceof AbortedError || this.suspended || this._lifecycle.draining;
951
- if (aborted || !isSdkModelWedgedError(err)) {
952
- return err;
953
- }
954
- const wedged = await this._residency.evictWedged(model, key);
955
- if (wedged.fatal) {
956
- setTimeout(() => process.exit(1), 0);
957
- }
958
- return new Error(wedged.message, { cause: err });
959
- }
960
- _completion(context) {
961
- this._lifecycle.assertNotClosing();
962
- if (this._lifecycle.draining) {
963
- throw new HarnessError('HARNESS_SUSPENDED');
964
- }
965
- if (this._lifecycle.unloadFailed) {
966
- throw new Error(UNLOAD_FAILED);
967
- }
968
- const own = context.latency ? undefined : RunLatency.start();
969
- const run = this._lifecycle.trackCompletion((signal) => this._residency.busyStream(() => this._runCompletion({ ...context, signal, latency: context.latency ?? own })), context.signal);
970
- return own ? own.logAfter(run) : run;
971
- }
972
- async *_runCompletion(request) {
973
- if (!this.opened)
974
- await this.ready();
975
- this._lifecycle.assertNotClosing();
976
- if (this.suspended || this._lifecycle.draining) {
977
- yield { type: 'aborted' };
978
- return;
979
- }
980
- const { boot, onStep, requestDigestKey, ...provided } = request;
981
- let modelId = request.model ?? '';
982
- let key = null;
983
- const releasePlugins = await this._plugins.hold(request.parentRunId !== undefined);
984
- const releasePrefix = this._prefix?.hold();
985
- request.latency?.mark('admittedMs');
986
- const detached = [];
987
- try {
988
- const runtime = async (run) => {
989
- modelId = run.model ?? run.modelId;
990
- const runContext = { ...run, model: run.model ?? run.modelId };
991
- const lease = await this._residency.completionRuntime(runContext);
992
- const access = await this._access(run, lease.args);
993
- request.latency?.mark('preparedMs');
994
- if (!key) {
995
- this._residency.reply(lease.key);
996
- }
997
- key = lease.key;
998
- const acquireRound = this._seeding(lease.args.acquireRound, modelId);
999
- const args = { ...lease.args, access, acquireRound };
1000
- return { ...lease, args, services: this._plugins.ctx };
1001
- };
1002
- const args = {
1003
- ...provided,
1004
- latency: request.latency,
1005
- lockOwner: this
1006
- };
1007
- for await (const event of CompletionEngine.run(runtime, args, {
1008
- hooks: this._hooks,
1009
- boot,
1010
- onStep,
1011
- requestDigestKey,
1012
- resumeRequest: provided,
1013
- onDetached: (pending, runId) => {
1014
- detached.push(pending);
1015
- this._lifecycle.trackDetachedRun(pending, runId);
1016
- }
1017
- })) {
1018
- yield event;
1019
- }
1020
- if (key) {
1021
- this._residency.clearFaults(modelId);
1022
- }
1023
- }
1024
- catch (error) {
1025
- yield* this._completionFailed(error, modelId, key);
1026
- }
1027
- finally {
1028
- if (key) {
1029
- HarnessLog.info('completion end', { model: modelId });
1030
- this._residency.replied(key);
1031
- void this._plugins.unloadIdle();
1032
- }
1033
- void Promise.allSettled(detached).then(releasePlugins);
1034
- releasePrefix?.();
1035
- }
1036
- }
1037
- _seeding(acquire, model) {
1038
- const prefix = this._prefix;
1039
- if (!prefix) {
1040
- return acquire;
1041
- }
1042
- return async (signal) => ({
1043
- ...(await acquire(signal)),
1044
- seed: (cacheKey, prime) => prefix.seed(cacheKey, prime, () => this._residentLease(model, prime.modelId))
1045
- });
1046
- }
1047
- async _residentLease(model, modelId) {
1048
- const lease = await leaseResidentModel(this._residency.pool, (name) => name === model);
1049
- if (lease?.modelId === modelId) {
1050
- return lease;
1051
- }
1052
- lease?.release();
1053
- return null;
1054
- }
1055
- async _access(run, roots) {
1056
- const layers = [this._policy, run.agent?.policy, run.policy];
1057
- return Policy.forRun(await Promise.all(layers.map(canonicalPolicy)), { ...roots, deny: await canonicalDenyRoots(this._deniedRoots, defaultRealpath) }, this._providers());
1058
- }
1059
- _providers() {
1060
- const providers = [];
1061
- if (this._exec) {
1062
- providers.push(this._shell ?? HOST_SHELL);
1063
- }
1064
- const ctx = this._plugins.ctx;
1065
- if ('sandbox' in ctx) {
1066
- providers.push(ctx.sandbox);
1067
- }
1068
- return providers;
1069
- }
1070
- async *_completionFailed(err, model, key) {
1071
- if (err instanceof AbortedError || this.suspended || this._lifecycle.draining) {
1072
- HarnessLog.info('completion aborted', {
1073
- model,
1074
- suspended: this.suspended || this._lifecycle.draining
1075
- });
1076
- yield { type: 'aborted' };
1077
- return;
1078
- }
1079
- const message = errorMessage(err);
1080
- const name = err instanceof Error ? err.name : undefined;
1081
- HarnessLog.error('completion failed', { model, ...resolutionDetail(err), err: message });
1082
- if (key && isSdkModelWedgedError(err)) {
1083
- const wedged = await this._residency.evictWedged(model, key);
1084
- yield completionErrorEvent(wedged.message, name, err);
1085
- if (wedged.fatal) {
1086
- process.exit(1);
1087
- }
1088
- }
1089
- else {
1090
- yield completionErrorEvent(message, name, err);
1091
- }
1092
- }
1093
- _residentEnhancer() {
1094
- return async (prompt, signal) => {
1095
- const lease = await leaseResidentModel(this._residency.pool, (model) => !this._residency.borrowed(model));
1096
- if (!lease) {
1097
- return null;
1098
- }
1099
- try {
1100
- const sdk = await this._sdk.load();
1101
- return await expandImagePrompt(sdk, prompt, {
1102
- modelId: lease.modelId,
1103
- model: lease.model,
1104
- signal
1105
- });
1106
- }
1107
- catch (err) {
1108
- HarnessLog.warn('enhance failed', { err: errorMessage(err) });
1109
- return null;
1110
- }
1111
- finally {
1112
- lease.release();
1113
- }
1114
- };
1115
- }
1116
- }
1117
- function completionErrorEvent(message, name, error) {
1118
- const event = { type: 'error', message, ...completionErrorDetails(error) };
1119
- if (name) {
1120
- event.name = name;
1121
- }
1122
- return event;
1123
- }
1124
- function completionErrorDetails(error) {
1125
- if (!isRecord(error))
1126
- return {};
1127
- if (error.code === 'PENDING_ARGS_REDACTED') {
1128
- return { code: 'PENDING_ARGS_REDACTED', ...Wire.redactedRecoveryFields(error) };
1129
- }
1130
- if (error.name !== 'RunIncompatible') {
1131
- return {};
1132
- }
1133
- const match = errorMessage(error).match(/^Incompatible run log: (machine|log|xstate) version (\d{1,10}(?:\.\d{1,10}){0,3}(?:-[A-Za-z0-9.-]{1,16})?) \(expected (\d{1,10}(?:\.\d{1,10}){0,3}(?:-[A-Za-z0-9.-]{1,16})?)\)/);
1134
- if (!match) {
1135
- return {};
1136
- }
1137
- const kind = match[1];
1138
- const found = match[2];
1139
- const expected = match[3];
1140
- if ((kind !== 'machine' && kind !== 'log' && kind !== 'xstate') || !found || !expected) {
1141
- return {};
1142
- }
1143
- return { kind, found, expected };
1144
- }
1145
- function noop() { }
1146
- async function canonicalPolicy(policy) {
1147
- if (!policy) {
1148
- return undefined;
1149
- }
1150
- const { files = {}, sockets } = policy;
1151
- return {
1152
- ...policy,
1153
- files: {
1154
- read: files.read === 'all' ? 'all' : await canonicalRoots(files.read),
1155
- write: await canonicalRoots(files.write),
1156
- deny: await canonicalRoots(files.deny)
1157
- },
1158
- sockets: await canonicalRoots(sockets)
1159
- };
1160
- }
1161
- async function canonicalRoots(roots) {
1162
- return roots && canonicalDenyRoots(roots, defaultRealpath);
1163
- }
30
+ export { HookPipeline } from './lib/hooks/index.js';
31
+ export { Policy } from './lib/policy/index.js';
32
+ export { Harness } from './lib/harness.js';