@qvac/harness 1.0.1 → 1.2.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.
- package/CHANGELOG.md +171 -6
- package/README.md +39 -0
- package/dist-lib/index.d.ts +32 -304
- package/dist-lib/index.js +16 -1147
- package/dist-lib/lib/agent/child-run.d.ts +33 -0
- package/dist-lib/lib/agent/child-run.js +58 -0
- package/dist-lib/lib/agent/delegate.d.ts +3 -19
- package/dist-lib/lib/agent/delegate.js +8 -31
- package/dist-lib/lib/agent/index.d.ts +7 -0
- package/dist-lib/lib/agent/index.js +5 -0
- package/dist-lib/lib/agent/read-parts.d.ts +47 -0
- package/dist-lib/lib/agent/read-parts.js +85 -0
- package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
- package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
- package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
- package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
- package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
- package/dist-lib/lib/client/index.js +1 -3
- package/dist-lib/lib/connect/decode.d.ts +3 -2
- package/dist-lib/lib/connect/decode.js +14 -0
- package/dist-lib/lib/connect.d.ts +1 -0
- package/dist-lib/lib/connect.js +11 -5
- package/dist-lib/lib/context-window.d.ts +2 -0
- package/dist-lib/lib/context-window.js +17 -14
- package/dist-lib/lib/contract/models.d.ts +13 -1
- package/dist-lib/lib/contract-types.d.ts +9 -0
- package/dist-lib/lib/harness.d.ts +269 -0
- package/dist-lib/lib/harness.js +1154 -0
- package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
- package/dist-lib/lib/models/custom-model-cache.js +21 -0
- package/dist-lib/lib/models/memory-cap.d.ts +6 -0
- package/dist-lib/lib/models/memory-cap.js +20 -0
- package/dist-lib/lib/models/model-catalog.d.ts +2 -0
- package/dist-lib/lib/models/model-catalog.js +8 -2
- package/dist-lib/lib/models/model-fit.d.ts +59 -10
- package/dist-lib/lib/models/model-fit.js +172 -35
- package/dist-lib/lib/models/model-handle.d.ts +2 -1
- package/dist-lib/lib/models/model-pool.d.ts +3 -2
- package/dist-lib/lib/models/model-pool.js +30 -13
- package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
- package/dist-lib/lib/models/tts-model-default.js +7 -6
- package/dist-lib/lib/residency/completion-runtime.d.ts +1 -1
- package/dist-lib/lib/residency/completion-runtime.js +1 -1
- package/dist-lib/lib/residency/index.d.ts +31 -9
- package/dist-lib/lib/residency/index.js +286 -88
- package/dist-lib/lib/run-log/boundary.d.ts +4 -1
- package/dist-lib/lib/run-log/boundary.js +2 -1
- package/dist-lib/lib/run-log/index.d.ts +2 -1
- package/dist-lib/lib/run-log/index.js +2 -1
- package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
- package/dist-lib/lib/run-log/persisted-actor.js +15 -0
- package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
- package/dist-lib/lib/run-log/run-journal.js +19 -8
- package/dist-lib/lib/serve/requests.d.ts +3 -0
- package/dist-lib/lib/serve.js +3 -0
- package/dist-lib/lib/spawn.d.ts +4 -1
- package/dist-lib/lib/tools/exec.d.ts +2 -0
- package/dist-lib/lib/tools/exec.js +29 -1
- package/dist-lib/lib/tools/files/list-dir.js +79 -32
- package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
- package/dist-lib/lib/tools/fs/walk.js +64 -30
- package/dist-lib/lib/tools/office.js +8 -5
- package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
- package/dist-lib/lib/tools/pdf/pages.js +3 -14
- package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
- package/dist-lib/lib/tools/pdf/recognize.js +45 -7
- package/dist-lib/plugins/image/generate-image.d.ts +2 -2
- package/dist-lib/plugins/image/generate-image.js +9 -1
- package/dist-lib/plugins/image/index.js +6 -2
- package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
- package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
- package/dist-lib/plugins/knowledge/index.d.ts +1 -0
- package/dist-lib/plugins/knowledge/index.js +1 -0
- package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
- package/dist-lib/plugins/knowledge/manifest.js +2 -9
- package/dist-lib/plugins/knowledge/store.d.ts +5 -1
- package/dist-lib/plugins/knowledge/store.js +44 -16
- package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
- package/dist-lib/plugins/lsp/rpc.js +81 -17
- package/dist-lib/plugins/music/generate-music.d.ts +2 -2
- package/dist-lib/plugins/music/generate-music.js +14 -1
- package/dist-lib/plugins/music/index.js +4 -1
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
- package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
- package/dist-lib/plugins/speech/speech-engine.js +28 -7
- package/dist-lib/schema/harness.js +28 -2
- package/dist-lib/spec/bind.js +3 -0
- package/dist-lib/spec/calls.js +1 -0
- package/dist-lib/spec/hrpc/hrpc.json +13 -0
- package/dist-lib/spec/hrpc/index.js +15 -3
- package/dist-lib/spec/hrpc/messages.js +87 -6
- package/dist-lib/spec/hyperschema/index.js +87 -6
- package/dist-lib/spec/hyperschema/schema.json +70 -2
- package/dist-lib/spec/hyperschema/types.d.ts +21 -1
- package/package.json +29 -28
- package/scripts/addon-externals.cjs +1 -0
- package/worker/harness-sidecar.mjs +12 -1
|
@@ -2,7 +2,7 @@ import { inspectRun, recordLog, renderRunLogHtml } from './inspect.js';
|
|
|
2
2
|
import { RunLogWatch } from './live.js';
|
|
3
3
|
import { createRunLogRedactor } from './redact.js';
|
|
4
4
|
import { parsePersistedSnapshot, replayRun } from './replay.js';
|
|
5
|
-
import { createPersistedActor } from './persisted-actor.js';
|
|
5
|
+
import { createPersistedActor, createTransientActor } from './persisted-actor.js';
|
|
6
6
|
import { boundaryBoot, openBoundaryJournal } from './boundary.js';
|
|
7
7
|
import { RUN_LOG_PROTOCOL_VERSION, RUN_LOG_VERSION, applyEngineStep, buildEngineBoot, contextFromBoot, createEngineBoot, requestFromBoot, validateEngineBoot } from './protocol.js';
|
|
8
8
|
import { XSTATE_VERSION, RunJournal, acquireRun, forkRepeatsSettledWrite, readRequests, readRunLog, recoveryAdvice, safeForkLength, unresolvedWriteIds, unsettledRedactedIds } from './run-journal.js';
|
|
@@ -33,6 +33,7 @@ export class RunLog extends RunJournal {
|
|
|
33
33
|
static openBoundary = openBoundaryJournal;
|
|
34
34
|
static boundaryBoot = boundaryBoot;
|
|
35
35
|
static createPersistedActor = createPersistedActor;
|
|
36
|
+
static createTransientActor = createTransientActor;
|
|
36
37
|
static acquireRun = acquireRun;
|
|
37
38
|
}
|
|
38
39
|
export { InvalidEngineStep } from './protocol.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CompletionMachine } from '../machine/index.ts';
|
|
1
2
|
import { type AnyStateMachine, type Actor } from 'xstate';
|
|
2
3
|
import { RunJournal } from './run-journal.ts';
|
|
3
4
|
import type { MachineLog } from './protocol-types.ts';
|
|
@@ -10,4 +11,13 @@ export interface PersistedActor<Machine extends AnyStateMachine> {
|
|
|
10
11
|
dispose(): Promise<void>;
|
|
11
12
|
};
|
|
12
13
|
}
|
|
14
|
+
export interface TransientActor<Machine extends AnyStateMachine> {
|
|
15
|
+
actor: Actor<Machine>;
|
|
16
|
+
persistence: {
|
|
17
|
+
checkpoint(): Promise<void>;
|
|
18
|
+
flush(): Promise<void>;
|
|
19
|
+
dispose(): Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export declare function createTransientActor(machine: ReturnType<typeof CompletionMachine.create>, journal: RunJournal, onFailure?: (error: Error) => void): TransientActor<ReturnType<typeof CompletionMachine.create>>;
|
|
13
23
|
export declare function createPersistedActor<Machine extends AnyStateMachine>(core: MachineLog | RunJournal, machine: Machine, onFailure?: (error: Error) => void, now?: () => number): Promise<PersistedActor<Machine>>;
|
|
@@ -6,6 +6,21 @@ import { brandCapturedRecord, isCapturedJson } from './protocol.js';
|
|
|
6
6
|
const CHECKPOINT_EVERY = 64;
|
|
7
7
|
const ROOT_ACTOR_ID = 'qvac-completion-machine';
|
|
8
8
|
const UNRECORDED = new Set(['OUTPUT', 'xstate.stop']);
|
|
9
|
+
export function createTransientActor(machine, journal, onFailure) {
|
|
10
|
+
const actor = createActor(machine, { id: ROOT_ACTOR_ID, input: undefined });
|
|
11
|
+
const noPersistence = () => Promise.resolve();
|
|
12
|
+
journal.onFailure = onFailure;
|
|
13
|
+
return {
|
|
14
|
+
actor,
|
|
15
|
+
persistence: {
|
|
16
|
+
checkpoint: noPersistence,
|
|
17
|
+
flush: () => journal.flush(),
|
|
18
|
+
async dispose() {
|
|
19
|
+
actor.stop();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
9
24
|
const noClock = () => 0;
|
|
10
25
|
export async function createPersistedActor(core, machine, onFailure, now = noClock) {
|
|
11
26
|
const journal = core instanceof RunJournal ? core : new RunJournal(core);
|
|
@@ -67,6 +67,7 @@ export declare class RunJournal {
|
|
|
67
67
|
sealed: boolean;
|
|
68
68
|
onFailure?: (error: Error) => void;
|
|
69
69
|
readonly core: MachineLog;
|
|
70
|
+
readonly transient: boolean;
|
|
70
71
|
restored: boolean;
|
|
71
72
|
private readonly redact;
|
|
72
73
|
private readonly redactShared;
|
|
@@ -97,6 +98,7 @@ export declare class RunJournal {
|
|
|
97
98
|
pendingArgumentsWereRedacted(snapshot: unknown): boolean | null;
|
|
98
99
|
append(record: RunRecord): Promise<void>;
|
|
99
100
|
private fail;
|
|
101
|
+
private storeReceipt;
|
|
100
102
|
hasPendingFlush(): boolean;
|
|
101
103
|
flush(): Promise<void>;
|
|
102
104
|
resolve(resolutions: readonly RecoveryResolution[]): Promise<void>;
|
|
@@ -109,6 +111,7 @@ interface RunJournalOptions {
|
|
|
109
111
|
redactOperationResult?: <Value>(operation: Operation, value: Value) => Value;
|
|
110
112
|
redactRecord?: (record: RunRecord) => RunRecord;
|
|
111
113
|
boot?: EngineBoot;
|
|
114
|
+
transient?: boolean;
|
|
112
115
|
}
|
|
113
116
|
export declare function acquireRun(owner: object, runId: string): () => void;
|
|
114
117
|
export declare class EventCodec {
|
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
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;
|
package/dist-lib/lib/serve.js
CHANGED
|
@@ -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']);
|
package/dist-lib/lib/spawn.d.ts
CHANGED
|
@@ -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 {
|
|
@@ -20,4 +20,6 @@ export interface ExecToolOptions {
|
|
|
20
20
|
}
|
|
21
21
|
export type SkillEnvFn = (skill: string) => Readonly<Record<string, string>> | undefined;
|
|
22
22
|
export declare function declaredEnv(declared: Readonly<Record<string, string>> | undefined, session: string | undefined): Record<string, string>;
|
|
23
|
+
export declare const WEB_REQUEST_ERROR = "exec does not make web requests. Call http_request with method \"GET\" instead; it attaches stored skill credentials itself.";
|
|
24
|
+
export declare function webRequestError(command: string, toolNames: readonly string[]): string | null;
|
|
23
25
|
export declare function createExecTool({ policyVersion, spawn, killProcess, shell: composedShell, languages, routes, skillSettings, skillEnv, realpath, deniedRoots, skillsDir }?: ExecToolOptions): ToolDefinition;
|
|
@@ -5,7 +5,8 @@ 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, tlsBypassError, videoToolError } from './exec/shell-guidance.js';
|
|
8
|
+
import { commandBin, LANGUAGE_UNAVAILABLE_ERROR, PYTHON_UNAVAILABLE_ERROR, savesDownload, SHELL_DOWNLOAD_NOTE, shellOnlyError, tlsBypassError, videoToolError } from './exec/shell-guidance.js';
|
|
9
|
+
import { isPrivateOrBlocked, stripIPv6Brackets } from './private-ip.js';
|
|
9
10
|
import { ShellLine } from './exec/shell-line.js';
|
|
10
11
|
import { bareRuntime } from './exec/bare-runtime.js';
|
|
11
12
|
import { canonicalDenyRoots, defaultRealpath, hostPath, resolveKey } from './fs/scope.js';
|
|
@@ -239,6 +240,29 @@ function execSchema(languages) {
|
|
|
239
240
|
}
|
|
240
241
|
};
|
|
241
242
|
}
|
|
243
|
+
export const WEB_REQUEST_ERROR = 'exec does not make web requests. Call http_request with method "GET" instead; it attaches stored skill credentials itself.';
|
|
244
|
+
export function webRequestError(command, toolNames) {
|
|
245
|
+
const bin = commandBin(command);
|
|
246
|
+
if ((bin !== 'curl' && bin !== 'wget') || !toolNames.includes('http_request')) {
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
if (savesDownload(command)) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
const argv = ShellLine.parse(command).commands[0]?.argv ?? [];
|
|
253
|
+
const target = argv.find((word) => /^https?:\/\//i.test(word));
|
|
254
|
+
if (!target) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
return isPrivateOrBlocked(stripIPv6Brackets(new URL(target).hostname))
|
|
259
|
+
? null
|
|
260
|
+
: WEB_REQUEST_ERROR;
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
242
266
|
export function createExecTool({ policyVersion, spawn, killProcess, shell: composedShell, languages = [], routes = [], skillSettings, skillEnv, realpath = defaultRealpath, deniedRoots, skillsDir } = {}) {
|
|
243
267
|
const shell = composedShell ??
|
|
244
268
|
createShellAdapter({
|
|
@@ -312,6 +336,10 @@ export function createExecTool({ policyVersion, spawn, killProcess, shell: compo
|
|
|
312
336
|
if (scopeError) {
|
|
313
337
|
return scopeError;
|
|
314
338
|
}
|
|
339
|
+
const webRequest = language ? null : webRequestError(command, ctx?.toolNames ?? []);
|
|
340
|
+
if (webRequest) {
|
|
341
|
+
return webRequest;
|
|
342
|
+
}
|
|
315
343
|
const workdirGiven = rawArgs.workdir !== undefined && rawArgs.workdir !== null;
|
|
316
344
|
if (workdirGiven && !language && (ctx?.fsRoots ?? []).length === 0) {
|
|
317
345
|
return WORKDIR_NO_ROOTS_ERROR;
|
|
@@ -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,
|
|
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
|
-
|
|
30
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
92
|
-
const
|
|
93
|
-
const
|
|
94
|
-
const folders =
|
|
95
|
-
for (const
|
|
96
|
-
if (isDeniedPath(
|
|
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
|
-
|
|
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
|
-
|
|
106
|
-
|
|
147
|
+
if (Date.now() > expand.deadline) {
|
|
148
|
+
return { name, entry, visible: false, truncated: true };
|
|
107
149
|
}
|
|
108
|
-
|
|
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.#
|
|
112
|
+
const children = await listChildren(this.#root, dir, this.#deadline);
|
|
81
113
|
if (children === null) {
|
|
82
114
|
return false;
|
|
83
115
|
}
|
|
84
|
-
const rules =
|
|
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;
|
|
@@ -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
|
-
|
|
679
|
-
|
|
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,
|
|
12
|
+
export declare function pdfPages(bytes: Uint8Array, options?: PdfPagesOptions): Promise<PdfPage[]>;
|
|
@@ -1,29 +1,18 @@
|
|
|
1
1
|
import { HarnessError } from '../../errors.js';
|
|
2
|
-
import {
|
|
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,
|
|
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
|
-
|
|
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();
|