@diffra-ai/durable 0.0.0-stage → 0.2.3
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 +442 -0
- package/README.md +1153 -2
- package/dist/codemode/codemode.d.ts +174 -0
- package/dist/codemode/codemode.d.ts.map +1 -0
- package/dist/codemode/codemode.js +884 -0
- package/dist/codemode/codemode.js.map +1 -0
- package/dist/codemode/describe.d.ts +38 -0
- package/dist/codemode/describe.d.ts.map +1 -0
- package/dist/codemode/describe.js +127 -0
- package/dist/codemode/describe.js.map +1 -0
- package/dist/codemode/index.d.ts +3 -0
- package/dist/codemode/index.d.ts.map +1 -0
- package/dist/codemode/index.js +3 -0
- package/dist/codemode/index.js.map +1 -0
- package/dist/codemode/models.d.ts +29 -0
- package/dist/codemode/models.d.ts.map +1 -0
- package/dist/codemode/models.js +242 -0
- package/dist/codemode/models.js.map +1 -0
- package/dist/codemode/output.d.ts +43 -0
- package/dist/codemode/output.d.ts.map +1 -0
- package/dist/codemode/output.js +168 -0
- package/dist/codemode/output.js.map +1 -0
- package/dist/documents.d.ts +66 -0
- package/dist/documents.d.ts.map +1 -0
- package/dist/documents.js +98 -0
- package/dist/documents.js.map +1 -0
- package/dist/entries.d.ts +31 -0
- package/dist/entries.d.ts.map +1 -0
- package/dist/entries.js +31 -0
- package/dist/entries.js.map +1 -0
- package/dist/env/decode.d.ts +16 -0
- package/dist/env/decode.d.ts.map +1 -0
- package/dist/env/decode.js +28 -0
- package/dist/env/decode.js.map +1 -0
- package/dist/env/index.d.ts +308 -0
- package/dist/env/index.d.ts.map +1 -0
- package/dist/env/index.js +49 -0
- package/dist/env/index.js.map +1 -0
- package/dist/env/line-scan.d.ts +13 -0
- package/dist/env/line-scan.d.ts.map +1 -0
- package/dist/env/line-scan.js +147 -0
- package/dist/env/line-scan.js.map +1 -0
- package/dist/env/node-watch.d.ts +29 -0
- package/dist/env/node-watch.d.ts.map +1 -0
- package/dist/env/node-watch.js +487 -0
- package/dist/env/node-watch.js.map +1 -0
- package/dist/env/node.d.ts +56 -0
- package/dist/env/node.d.ts.map +1 -0
- package/dist/env/node.js +1185 -0
- package/dist/env/node.js.map +1 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +76 -0
- package/dist/errors.js.map +1 -0
- package/dist/harness/agent.d.ts +46 -0
- package/dist/harness/agent.d.ts.map +1 -0
- package/dist/harness/agent.js +334 -0
- package/dist/harness/agent.js.map +1 -0
- package/dist/harness/compaction.d.ts +68 -0
- package/dist/harness/compaction.d.ts.map +1 -0
- package/dist/harness/compaction.js +431 -0
- package/dist/harness/compaction.js.map +1 -0
- package/dist/harness/context.d.ts +84 -0
- package/dist/harness/context.d.ts.map +1 -0
- package/dist/harness/context.js +301 -0
- package/dist/harness/context.js.map +1 -0
- package/dist/harness/define.d.ts +25 -0
- package/dist/harness/define.d.ts.map +1 -0
- package/dist/harness/define.js +32 -0
- package/dist/harness/define.js.map +1 -0
- package/dist/harness/generation.d.ts +117 -0
- package/dist/harness/generation.d.ts.map +1 -0
- package/dist/harness/generation.js +1098 -0
- package/dist/harness/generation.js.map +1 -0
- package/dist/harness/harness.d.ts +22 -0
- package/dist/harness/harness.d.ts.map +1 -0
- package/dist/harness/harness.js +438 -0
- package/dist/harness/harness.js.map +1 -0
- package/dist/harness/inbox.d.ts +84 -0
- package/dist/harness/inbox.d.ts.map +1 -0
- package/dist/harness/inbox.js +135 -0
- package/dist/harness/inbox.js.map +1 -0
- package/dist/harness/json.d.ts +26 -0
- package/dist/harness/json.d.ts.map +1 -0
- package/dist/harness/json.js +51 -0
- package/dist/harness/json.js.map +1 -0
- package/dist/harness/live.d.ts +285 -0
- package/dist/harness/live.d.ts.map +1 -0
- package/dist/harness/live.js +257 -0
- package/dist/harness/live.js.map +1 -0
- package/dist/harness/parks.d.ts +23 -0
- package/dist/harness/parks.d.ts.map +1 -0
- package/dist/harness/parks.js +52 -0
- package/dist/harness/parks.js.map +1 -0
- package/dist/harness/partial-changes.d.ts +54 -0
- package/dist/harness/partial-changes.d.ts.map +1 -0
- package/dist/harness/partial-changes.js +163 -0
- package/dist/harness/partial-changes.js.map +1 -0
- package/dist/harness/prompt.d.ts +27 -0
- package/dist/harness/prompt.d.ts.map +1 -0
- package/dist/harness/prompt.js +131 -0
- package/dist/harness/prompt.js.map +1 -0
- package/dist/harness/provider.d.ts +16 -0
- package/dist/harness/provider.d.ts.map +1 -0
- package/dist/harness/provider.js +33 -0
- package/dist/harness/provider.js.map +1 -0
- package/dist/harness/registry-reader.d.ts +11 -0
- package/dist/harness/registry-reader.d.ts.map +1 -0
- package/dist/harness/registry-reader.js +25 -0
- package/dist/harness/registry-reader.js.map +1 -0
- package/dist/harness/registry.d.ts +6 -0
- package/dist/harness/registry.d.ts.map +1 -0
- package/dist/harness/registry.js +101 -0
- package/dist/harness/registry.js.map +1 -0
- package/dist/harness/scheduler.d.ts +195 -0
- package/dist/harness/scheduler.d.ts.map +1 -0
- package/dist/harness/scheduler.js +3073 -0
- package/dist/harness/scheduler.js.map +1 -0
- package/dist/harness/submissions.d.ts +44 -0
- package/dist/harness/submissions.d.ts.map +1 -0
- package/dist/harness/submissions.js +265 -0
- package/dist/harness/submissions.js.map +1 -0
- package/dist/harness/task-graph.d.ts +75 -0
- package/dist/harness/task-graph.d.ts.map +1 -0
- package/dist/harness/task-graph.js +224 -0
- package/dist/harness/task-graph.js.map +1 -0
- package/dist/harness/telemetry.d.ts +307 -0
- package/dist/harness/telemetry.d.ts.map +1 -0
- package/dist/harness/telemetry.js +140 -0
- package/dist/harness/telemetry.js.map +1 -0
- package/dist/harness/tool.d.ts +106 -0
- package/dist/harness/tool.d.ts.map +1 -0
- package/dist/harness/tool.js +1182 -0
- package/dist/harness/tool.js.map +1 -0
- package/dist/harness/transcript.d.ts +72 -0
- package/dist/harness/transcript.d.ts.map +1 -0
- package/dist/harness/transcript.js +264 -0
- package/dist/harness/transcript.js.map +1 -0
- package/dist/harness/types.d.ts +1146 -0
- package/dist/harness/types.d.ts.map +1 -0
- package/dist/harness/types.js +2 -0
- package/dist/harness/types.js.map +1 -0
- package/dist/harness/usage.d.ts +19 -0
- package/dist/harness/usage.d.ts.map +1 -0
- package/dist/harness/usage.js +57 -0
- package/dist/harness/usage.js.map +1 -0
- package/dist/harness/util.d.ts +25 -0
- package/dist/harness/util.d.ts.map +1 -0
- package/dist/harness/util.js +76 -0
- package/dist/harness/util.js.map +1 -0
- package/dist/harness/view.d.ts +69 -0
- package/dist/harness/view.d.ts.map +1 -0
- package/dist/harness/view.js +265 -0
- package/dist/harness/view.js.map +1 -0
- package/dist/ids.d.ts +6 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +9 -0
- package/dist/ids.js.map +1 -0
- package/dist/images/cloudflare.d.ts +4 -0
- package/dist/images/cloudflare.d.ts.map +1 -0
- package/dist/images/cloudflare.js +9 -0
- package/dist/images/cloudflare.js.map +1 -0
- package/dist/images/exif.d.ts +3 -0
- package/dist/images/exif.d.ts.map +1 -0
- package/dist/images/exif.js +71 -0
- package/dist/images/exif.js.map +1 -0
- package/dist/images/fit.d.ts +41 -0
- package/dist/images/fit.d.ts.map +1 -0
- package/dist/images/fit.js +108 -0
- package/dist/images/fit.js.map +1 -0
- package/dist/images/index.d.ts +18 -0
- package/dist/images/index.d.ts.map +1 -0
- package/dist/images/index.js +125 -0
- package/dist/images/index.js.map +1 -0
- package/dist/images/node-worker.d.ts +19 -0
- package/dist/images/node-worker.d.ts.map +1 -0
- package/dist/images/node-worker.js +17 -0
- package/dist/images/node-worker.js.map +1 -0
- package/dist/images/node.d.ts +21 -0
- package/dist/images/node.d.ts.map +1 -0
- package/dist/images/node.js +121 -0
- package/dist/images/node.js.map +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/search.d.ts +29 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +148 -0
- package/dist/search.js.map +1 -0
- package/dist/session/cached-storage.d.ts +72 -0
- package/dist/session/cached-storage.d.ts.map +1 -0
- package/dist/session/cached-storage.js +269 -0
- package/dist/session/cached-storage.js.map +1 -0
- package/dist/session/conversation-tails.d.ts +33 -0
- package/dist/session/conversation-tails.d.ts.map +1 -0
- package/dist/session/conversation-tails.js +101 -0
- package/dist/session/conversation-tails.js.map +1 -0
- package/dist/session/forks.d.ts +10 -0
- package/dist/session/forks.d.ts.map +1 -0
- package/dist/session/forks.js +42 -0
- package/dist/session/forks.js.map +1 -0
- package/dist/session/keys.d.ts +69 -0
- package/dist/session/keys.d.ts.map +1 -0
- package/dist/session/keys.js +161 -0
- package/dist/session/keys.js.map +1 -0
- package/dist/session/session.d.ts +287 -0
- package/dist/session/session.d.ts.map +1 -0
- package/dist/session/session.js +1701 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/transaction.d.ts +205 -0
- package/dist/session/transaction.d.ts.map +1 -0
- package/dist/session/transaction.js +1059 -0
- package/dist/session/transaction.js.map +1 -0
- package/dist/session/writer.d.ts +74 -0
- package/dist/session/writer.d.ts.map +1 -0
- package/dist/session/writer.js +294 -0
- package/dist/session/writer.js.map +1 -0
- package/dist/signals.d.ts +180 -0
- package/dist/signals.d.ts.map +1 -0
- package/dist/signals.js +236 -0
- package/dist/signals.js.map +1 -0
- package/dist/storage/indexeddb.d.ts +69 -0
- package/dist/storage/indexeddb.d.ts.map +1 -0
- package/dist/storage/indexeddb.js +883 -0
- package/dist/storage/indexeddb.js.map +1 -0
- package/dist/storage/jsonl/index.d.ts +2 -0
- package/dist/storage/jsonl/index.d.ts.map +1 -0
- package/dist/storage/jsonl/index.js +2 -0
- package/dist/storage/jsonl/index.js.map +1 -0
- package/dist/storage/jsonl/node.d.ts +6 -0
- package/dist/storage/jsonl/node.d.ts.map +1 -0
- package/dist/storage/jsonl/node.js +8 -0
- package/dist/storage/jsonl/node.js.map +1 -0
- package/dist/storage/jsonl/storage.d.ts +206 -0
- package/dist/storage/jsonl/storage.d.ts.map +1 -0
- package/dist/storage/jsonl/storage.js +799 -0
- package/dist/storage/jsonl/storage.js.map +1 -0
- package/dist/storage/memory.d.ts +68 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/memory.js +761 -0
- package/dist/storage/memory.js.map +1 -0
- package/dist/storage/scan.d.ts +18 -0
- package/dist/storage/scan.d.ts.map +1 -0
- package/dist/storage/scan.js +29 -0
- package/dist/storage/scan.js.map +1 -0
- package/dist/storage/sqlite/cloudflare.d.ts +9 -0
- package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
- package/dist/storage/sqlite/cloudflare.js +11 -0
- package/dist/storage/sqlite/cloudflare.js.map +1 -0
- package/dist/storage/sqlite/commit.d.ts +52 -0
- package/dist/storage/sqlite/commit.d.ts.map +1 -0
- package/dist/storage/sqlite/commit.js +371 -0
- package/dist/storage/sqlite/commit.js.map +1 -0
- package/dist/storage/sqlite/database.d.ts +2 -0
- package/dist/storage/sqlite/database.d.ts.map +1 -0
- package/dist/storage/sqlite/database.js +2 -0
- package/dist/storage/sqlite/database.js.map +1 -0
- package/dist/storage/sqlite/index.d.ts +4 -0
- package/dist/storage/sqlite/index.d.ts.map +1 -0
- package/dist/storage/sqlite/index.js +3 -0
- package/dist/storage/sqlite/index.js.map +1 -0
- package/dist/storage/sqlite/migrations.d.ts +12 -0
- package/dist/storage/sqlite/migrations.d.ts.map +1 -0
- package/dist/storage/sqlite/migrations.js +121 -0
- package/dist/storage/sqlite/migrations.js.map +1 -0
- package/dist/storage/sqlite/node.d.ts +8 -0
- package/dist/storage/sqlite/node.d.ts.map +1 -0
- package/dist/storage/sqlite/node.js +12 -0
- package/dist/storage/sqlite/node.js.map +1 -0
- package/dist/storage/sqlite/rows.d.ts +33 -0
- package/dist/storage/sqlite/rows.d.ts.map +1 -0
- package/dist/storage/sqlite/rows.js +53 -0
- package/dist/storage/sqlite/rows.js.map +1 -0
- package/dist/storage/sqlite/schema.d.ts +45 -0
- package/dist/storage/sqlite/schema.d.ts.map +1 -0
- package/dist/storage/sqlite/schema.js +50 -0
- package/dist/storage/sqlite/schema.js.map +1 -0
- package/dist/storage/sqlite/statements.d.ts +13 -0
- package/dist/storage/sqlite/statements.d.ts.map +1 -0
- package/dist/storage/sqlite/statements.js +88 -0
- package/dist/storage/sqlite/statements.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +86 -0
- package/dist/storage/sqlite/storage.d.ts.map +1 -0
- package/dist/storage/sqlite/storage.js +534 -0
- package/dist/storage/sqlite/storage.js.map +1 -0
- package/dist/storage/store/commit.d.ts +33 -0
- package/dist/storage/store/commit.d.ts.map +1 -0
- package/dist/storage/store/commit.js +286 -0
- package/dist/storage/store/commit.js.map +1 -0
- package/dist/storage/store/documents.d.ts +43 -0
- package/dist/storage/store/documents.d.ts.map +1 -0
- package/dist/storage/store/documents.js +102 -0
- package/dist/storage/store/documents.js.map +1 -0
- package/dist/storage/store/index.d.ts +2 -0
- package/dist/storage/store/index.d.ts.map +1 -0
- package/dist/storage/store/index.js +2 -0
- package/dist/storage/store/index.js.map +1 -0
- package/dist/storage/store/queries.d.ts +49 -0
- package/dist/storage/store/queries.d.ts.map +1 -0
- package/dist/storage/store/queries.js +93 -0
- package/dist/storage/store/queries.js.map +1 -0
- package/dist/storage/store/storage.d.ts +60 -0
- package/dist/storage/store/storage.d.ts.map +1 -0
- package/dist/storage/store/storage.js +438 -0
- package/dist/storage/store/storage.js.map +1 -0
- package/dist/storage/store/tables.d.ts +54 -0
- package/dist/storage/store/tables.d.ts.map +1 -0
- package/dist/storage/store/tables.js +108 -0
- package/dist/storage/store/tables.js.map +1 -0
- package/dist/tasks.d.ts +6 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +5 -0
- package/dist/tasks.js.map +1 -0
- package/dist/testing/assertions.d.ts +5 -0
- package/dist/testing/assertions.d.ts.map +1 -0
- package/dist/testing/assertions.js +25 -0
- package/dist/testing/assertions.js.map +1 -0
- package/dist/testing/commit-writes.d.ts +5 -0
- package/dist/testing/commit-writes.d.ts.map +1 -0
- package/dist/testing/commit-writes.js +12 -0
- package/dist/testing/commit-writes.js.map +1 -0
- package/dist/testing/env-conformance.d.ts +7 -0
- package/dist/testing/env-conformance.d.ts.map +1 -0
- package/dist/testing/env-conformance.js +531 -0
- package/dist/testing/env-conformance.js.map +1 -0
- package/dist/testing/index.d.ts +8 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/runner.d.ts +12 -0
- package/dist/testing/runner.d.ts.map +1 -0
- package/dist/testing/runner.js +23 -0
- package/dist/testing/runner.js.map +1 -0
- package/dist/testing/storage-benchmark.d.ts +41 -0
- package/dist/testing/storage-benchmark.d.ts.map +1 -0
- package/dist/testing/storage-benchmark.js +351 -0
- package/dist/testing/storage-benchmark.js.map +1 -0
- package/dist/testing/storage-conformance.d.ts +4 -0
- package/dist/testing/storage-conformance.d.ts.map +1 -0
- package/dist/testing/storage-conformance.js +1554 -0
- package/dist/testing/storage-conformance.js.map +1 -0
- package/dist/testing/types.d.ts +39 -0
- package/dist/testing/types.d.ts.map +1 -0
- package/dist/testing/types.js +2 -0
- package/dist/testing/types.js.map +1 -0
- package/dist/timers.d.ts +21 -0
- package/dist/timers.d.ts.map +1 -0
- package/dist/timers.js +72 -0
- package/dist/timers.js.map +1 -0
- package/dist/tool-search/index.d.ts +2 -0
- package/dist/tool-search/index.d.ts.map +1 -0
- package/dist/tool-search/index.js +2 -0
- package/dist/tool-search/index.js.map +1 -0
- package/dist/tool-search/tool-search.d.ts +17 -0
- package/dist/tool-search/tool-search.d.ts.map +1 -0
- package/dist/tool-search/tool-search.js +96 -0
- package/dist/tool-search/tool-search.js.map +1 -0
- package/dist/tools/bash.d.ts +55 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +139 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit-diff.d.ts +89 -0
- package/dist/tools/edit-diff.d.ts.map +1 -0
- package/dist/tools/edit-diff.js +386 -0
- package/dist/tools/edit-diff.js.map +1 -0
- package/dist/tools/edit.d.ts +18 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +117 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/env.d.ts +5 -0
- package/dist/tools/env.d.ts.map +1 -0
- package/dist/tools/env.js +7 -0
- package/dist/tools/env.js.map +1 -0
- package/dist/tools/file-mutation-queue.d.ts +9 -0
- package/dist/tools/file-mutation-queue.d.ts.map +1 -0
- package/dist/tools/file-mutation-queue.js +52 -0
- package/dist/tools/file-mutation-queue.js.map +1 -0
- package/dist/tools/image-processor.d.ts +57 -0
- package/dist/tools/image-processor.d.ts.map +1 -0
- package/dist/tools/image-processor.js +49 -0
- package/dist/tools/image-processor.js.map +1 -0
- package/dist/tools/image.d.ts +20 -0
- package/dist/tools/image.d.ts.map +1 -0
- package/dist/tools/image.js +178 -0
- package/dist/tools/image.js.map +1 -0
- package/dist/tools/index.d.ts +46 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +23 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/path-utils.d.ts +5 -0
- package/dist/tools/path-utils.d.ts.map +1 -0
- package/dist/tools/path-utils.js +26 -0
- package/dist/tools/path-utils.js.map +1 -0
- package/dist/tools/read.d.ts +30 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +239 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +31 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/truncate.d.ts +65 -0
- package/dist/truncate.d.ts.map +1 -0
- package/dist/truncate.js +124 -0
- package/dist/truncate.js.map +1 -0
- package/dist/types.d.ts +1244 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +179 -5
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { characterEnd } from "@diffra-ai/chord/output";
|
|
2
|
+
import { lit, num, obj, opt, str, union } from "@diffra-ai/schema";
|
|
3
|
+
import { getOrThrow, rangeDecoder, startsWithBom, } from "../env/index.js";
|
|
4
|
+
import { defineTool } from "../harness/define.js";
|
|
5
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHeadOf, utf8ByteLength, } from "../truncate.js";
|
|
6
|
+
import { requireEnv } from "./env.js";
|
|
7
|
+
import { detectSupportedImageMimeTypeOf, imageDimensions } from "./image.js";
|
|
8
|
+
import { base64Length, INLINE_IMAGE_TYPES, imageLimits, preparedNotes, toBase64, } from "./image-processor.js";
|
|
9
|
+
import { resolveReadToolPath } from "./path-utils.js";
|
|
10
|
+
const readSchema = obj({
|
|
11
|
+
path: str({ description: "Path to the file to read (relative or absolute)" }),
|
|
12
|
+
offset: opt(num({ description: "Line number to start reading from (1-indexed)" })),
|
|
13
|
+
limit: opt(num({ description: "Maximum number of lines to read" })),
|
|
14
|
+
}, { open: true });
|
|
15
|
+
/**
|
|
16
|
+
* What programs such as code mode scripts get: the text of a text file, or the image block of an image, which code
|
|
17
|
+
* mode's `image()` shows.
|
|
18
|
+
*/
|
|
19
|
+
const readStructuredOutputSchema = union([
|
|
20
|
+
str(),
|
|
21
|
+
obj({ type: lit("image"), data: str(), mimeType: str() }, { open: true }),
|
|
22
|
+
]);
|
|
23
|
+
const READ_CHUNK = 64 * 1024;
|
|
24
|
+
/** `Array.prototype.slice`'s conversion of an index: NaN is 0, other values truncate toward zero. */
|
|
25
|
+
function sliceIndex(value) {
|
|
26
|
+
return Number.isNaN(value) ? 0 : Math.trunc(value);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The decoded start of bytes `[start, end)` of the file, decoded as part of the whole file: all of it, or enough for
|
|
30
|
+
* `truncateHeadOf` (more than `DEFAULT_MAX_BYTES + 1` bytes, or `DEFAULT_MAX_LINES` newlines).
|
|
31
|
+
*/
|
|
32
|
+
async function readHead(reader, start, end, skipBom, context) {
|
|
33
|
+
const decoder = rangeDecoder();
|
|
34
|
+
let text = "";
|
|
35
|
+
let newlines = 0;
|
|
36
|
+
for (let position = skipBom && start === 0 ? 3 : start; position < end;) {
|
|
37
|
+
const bytes = getOrThrow(await reader.read(position, Math.min(READ_CHUNK, end - position), context));
|
|
38
|
+
if (bytes.length === 0)
|
|
39
|
+
break;
|
|
40
|
+
position += bytes.length;
|
|
41
|
+
const decoded = decoder.decode(bytes, { stream: true });
|
|
42
|
+
text += decoded;
|
|
43
|
+
for (let index = decoded.indexOf("\n"); index !== -1; index = decoded.indexOf("\n", index + 1))
|
|
44
|
+
newlines++;
|
|
45
|
+
if (newlines >= DEFAULT_MAX_LINES || utf8ByteLength(text) > DEFAULT_MAX_BYTES + 1)
|
|
46
|
+
return text;
|
|
47
|
+
}
|
|
48
|
+
return text + decoder.decode();
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Reads text files and images. Remarks about truncation, continuation, and image processing are diagnostics; the content
|
|
52
|
+
* is only file text, or one image. Programs get the text, or the image's `ImageContent`.
|
|
53
|
+
*/
|
|
54
|
+
export function createReadTool(options = {}) {
|
|
55
|
+
const formats = options.images === undefined ? "jpg, png, gif, webp" : "jpg, png, gif, webp, bmp";
|
|
56
|
+
return defineTool({
|
|
57
|
+
name: "read",
|
|
58
|
+
description: `Read the contents of a file. Supports text files and images (${formats}). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,
|
|
59
|
+
parameters: readSchema,
|
|
60
|
+
structuredOutputSchema: readStructuredOutputSchema,
|
|
61
|
+
async execute(args, api, context) {
|
|
62
|
+
const { path, offset, limit } = args;
|
|
63
|
+
const env = requireEnv(api);
|
|
64
|
+
const absolutePath = await resolveReadToolPath(env, path, context);
|
|
65
|
+
const reader = getOrThrow(await env.openBinaryReader(absolutePath, undefined, context));
|
|
66
|
+
try {
|
|
67
|
+
// A concurrent writer can change the file between the scan and the reads. Appending (a growing log) leaves
|
|
68
|
+
// the scanned text as it was; an image must be whole. Otherwise the file is read again once.
|
|
69
|
+
for (let attempt = 0;; attempt++) {
|
|
70
|
+
const before = getOrThrow(await reader.info(context));
|
|
71
|
+
const mimeType = await detectSupportedImageMimeTypeOf({
|
|
72
|
+
size: before.size,
|
|
73
|
+
read: async (position, length) => getOrThrow(await reader.read(position, length, context)),
|
|
74
|
+
});
|
|
75
|
+
const result = mimeType === undefined
|
|
76
|
+
? await readText(reader, path, offset, limit, context)
|
|
77
|
+
: await readImage(reader, before, path, mimeType, options.images, await imageModel(api, context), context);
|
|
78
|
+
const after = getOrThrow(await reader.info(context));
|
|
79
|
+
const unchanged = after.size === before.size && after.mtimeMs === before.mtimeMs;
|
|
80
|
+
if (unchanged || (mimeType === undefined && after.size > before.size))
|
|
81
|
+
return result;
|
|
82
|
+
if (attempt === 1)
|
|
83
|
+
throw new Error(`${path} changed while it was read`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await reader.close(context);
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* One image block, prepared by `processor` or, without one, as it is when its format is inline and it fits the limits
|
|
94
|
+
* (its size is checked before reading it, its dimensions from its header); otherwise an error result saying why. What happened to the image is an `info` diagnostic, so programs get the
|
|
95
|
+
* bare `ImageContent`. A model without image input sees diffra-ai's placeholder instead, decided per request; `details`
|
|
96
|
+
* names it for UIs.
|
|
97
|
+
*/
|
|
98
|
+
async function readImage(reader, info, path, mimeType, processor, { limits, imageUnsupportedByModel }, context) {
|
|
99
|
+
let image;
|
|
100
|
+
const notes = [];
|
|
101
|
+
if (processor !== undefined) {
|
|
102
|
+
const bytes = getOrThrow(await reader.read(0, info.size, context));
|
|
103
|
+
const prepared = await processor.prepare(bytes, mimeType, limits);
|
|
104
|
+
if (prepared === undefined)
|
|
105
|
+
return imageError(`${path} is an image (${mimeType}) that cannot be prepared for the model`);
|
|
106
|
+
image = prepared;
|
|
107
|
+
notes.push(...preparedNotes(prepared));
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
if (!INLINE_IMAGE_TYPES.has(mimeType)) {
|
|
111
|
+
return imageError(`${path} is an image (${mimeType}) that needs converting, and no image processor is configured`);
|
|
112
|
+
}
|
|
113
|
+
const unshrinkable = "and no image processor is configured to shrink it";
|
|
114
|
+
if (base64Length(info.size) > limits.maxBytes) {
|
|
115
|
+
return imageError(`${path} is an image (${mimeType}) of ${formatSize(info.size)}, too large to send, ${unshrinkable}`);
|
|
116
|
+
}
|
|
117
|
+
const bytes = getOrThrow(await reader.read(0, info.size, context));
|
|
118
|
+
const size = imageDimensions(bytes, mimeType);
|
|
119
|
+
if (size === undefined)
|
|
120
|
+
return imageError(`${path} is an image (${mimeType}) whose size cannot be read`);
|
|
121
|
+
if (size.width > limits.maxWidth || size.height > limits.maxHeight) {
|
|
122
|
+
return imageError(`${path} is an image (${mimeType}) of ${size.width}x${size.height}, larger than ${limits.maxWidth}x${limits.maxHeight}, ${unshrinkable}`);
|
|
123
|
+
}
|
|
124
|
+
image = { data: toBase64(bytes), mimeType };
|
|
125
|
+
}
|
|
126
|
+
const diagnostics = [
|
|
127
|
+
{ severity: "info", code: "image", message: [`Read image file [${image.mimeType}].`, ...notes].join(" ") },
|
|
128
|
+
];
|
|
129
|
+
const block = { type: "image", data: image.data, mimeType: image.mimeType };
|
|
130
|
+
return {
|
|
131
|
+
output: [block],
|
|
132
|
+
structuredOutput: block,
|
|
133
|
+
...(imageUnsupportedByModel === undefined ? {} : { details: { imageUnsupportedByModel } }),
|
|
134
|
+
diagnostics,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The conversation model's image limits (`imageLimits`), and its id if it has no image input. Without a resolvable
|
|
139
|
+
* model, the defaults and no id.
|
|
140
|
+
*/
|
|
141
|
+
async function imageModel(api, context) {
|
|
142
|
+
const ref = (await api.agent(context)).model;
|
|
143
|
+
const model = ref === undefined ? undefined : api.models.getModel(ref.provider, ref.modelId);
|
|
144
|
+
return {
|
|
145
|
+
...(model === undefined || model.input.includes("image") ? {} : { imageUnsupportedByModel: model.id }),
|
|
146
|
+
limits: imageLimits(model),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function imageError(message) {
|
|
150
|
+
return { output: [], isError: true, diagnostics: [{ severity: "error", code: "unsupported_image", message }] };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The read result for the opened file. It equals decoding the whole file with `TextDecoder`, splitting it on `\n`,
|
|
154
|
+
* and bounding the selected lines with `truncateHead`, while reading only one scan's worth of the file plus the head.
|
|
155
|
+
*/
|
|
156
|
+
async function readText(reader, path, offset, limit, context) {
|
|
157
|
+
const startLine = offset ? Math.max(0, offset - 1) : 0;
|
|
158
|
+
const startLineDisplay = startLine + 1;
|
|
159
|
+
// Lines are selected like `allLines.slice(startLine, endLine)`, which truncates fractional indices.
|
|
160
|
+
const sliceStart = sliceIndex(startLine);
|
|
161
|
+
// One pass finds the line count and the selection; a selection past the last line ends with it, as `slice` does,
|
|
162
|
+
// and an empty one (a zero or negative limit) is scanned as one line and then ignored.
|
|
163
|
+
// A start beyond any file is scanned from 0 only to count lines; the offset check below then fails as before.
|
|
164
|
+
const scanStart = Number.isSafeInteger(sliceStart) ? sliceStart : 0;
|
|
165
|
+
const requestedEnd = limit === undefined ? undefined : Math.max(scanStart + 1, sliceIndex(startLine + limit));
|
|
166
|
+
const scanEnd = requestedEnd !== undefined && Number.isSafeInteger(requestedEnd) ? requestedEnd : undefined;
|
|
167
|
+
const scanOf = async (endLine) => getOrThrow(await reader.scanLines({ startLine: scanStart, ...(endLine === undefined ? {} : { endLine }) }, context));
|
|
168
|
+
let scan = await scanOf(scanEnd);
|
|
169
|
+
const totalFileLines = scan.newlines + 1;
|
|
170
|
+
if (startLine >= totalFileLines) {
|
|
171
|
+
throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
|
|
172
|
+
}
|
|
173
|
+
let userLimitedLines;
|
|
174
|
+
let selectedLineCount = totalFileLines - sliceStart;
|
|
175
|
+
if (limit !== undefined) {
|
|
176
|
+
const endLine = Math.min(startLine + limit, totalFileLines);
|
|
177
|
+
userLimitedLines = endLine - startLine;
|
|
178
|
+
// `slice` counts a negative end from the end of the lines, which only the line count tells; scan again for it.
|
|
179
|
+
const relativeEnd = sliceIndex(endLine);
|
|
180
|
+
const sliceEnd = relativeEnd < 0 ? Math.max(totalFileLines + relativeEnd, 0) : relativeEnd;
|
|
181
|
+
selectedLineCount = Math.max(0, sliceEnd - sliceStart);
|
|
182
|
+
if (selectedLineCount > 0 && relativeEnd < 0)
|
|
183
|
+
scan = await scanOf(sliceEnd);
|
|
184
|
+
}
|
|
185
|
+
const empty = selectedLineCount === 0;
|
|
186
|
+
// Counted like `truncateHead`: a trailing newline adds no line, and empty text has none.
|
|
187
|
+
const endsWithNewline = !empty && scan.lastLineStart === scan.end && scan.lastLineStart > scan.start;
|
|
188
|
+
const totals = {
|
|
189
|
+
lines: empty || scan.selectedBytes === 0 ? 0 : selectedLineCount - (endsWithNewline ? 1 : 0),
|
|
190
|
+
bytes: empty ? 0 : scan.selectedBytes,
|
|
191
|
+
};
|
|
192
|
+
const firstBytes = getOrThrow(await reader.read(0, 3, context));
|
|
193
|
+
const head = empty ? "" : await readHead(reader, scan.start, scan.end, startsWithBom(firstBytes), context);
|
|
194
|
+
const { content: headText, ...truncation } = truncateHeadOf(head, totals);
|
|
195
|
+
const diagnostics = [];
|
|
196
|
+
let outputText = headText;
|
|
197
|
+
let details;
|
|
198
|
+
if (truncation.firstLineExceedsLimit) {
|
|
199
|
+
// Show the start of the line, cut at the byte limit on a character boundary. Like `allLines[startLine]`, a
|
|
200
|
+
// fractional start line names no line.
|
|
201
|
+
const integral = Number.isInteger(startLine);
|
|
202
|
+
const lineBytes = new TextEncoder().encode(integral ? (head.split("\n")[0] ?? "") : "");
|
|
203
|
+
const lineSize = integral ? scan.firstLineBytes : 0;
|
|
204
|
+
const end = characterEnd(lineBytes, DEFAULT_MAX_BYTES);
|
|
205
|
+
outputText = new TextDecoder().decode(lineBytes.subarray(0, end));
|
|
206
|
+
diagnostics.push({
|
|
207
|
+
severity: "warn",
|
|
208
|
+
code: "truncated",
|
|
209
|
+
message: `Line ${startLineDisplay} is ${formatSize(lineSize)}, exceeds the ${formatSize(DEFAULT_MAX_BYTES)} limit; showing its first ${formatSize(end)}. Use bash: sed -n '${startLineDisplay}p' ${path} | tail -c +${end + 1}`,
|
|
210
|
+
});
|
|
211
|
+
details = { truncation: { ...truncation, outputBytes: end, outputLines: 1 } };
|
|
212
|
+
}
|
|
213
|
+
else if (truncation.truncated) {
|
|
214
|
+
const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
|
|
215
|
+
const nextOffset = endLineDisplay + 1;
|
|
216
|
+
const limitText = truncation.truncatedBy === "lines" ? "" : ` (${formatSize(DEFAULT_MAX_BYTES)} limit)`;
|
|
217
|
+
diagnostics.push({
|
|
218
|
+
severity: "info",
|
|
219
|
+
code: "truncated",
|
|
220
|
+
message: `Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}${limitText}. Use offset=${nextOffset} to continue.`,
|
|
221
|
+
});
|
|
222
|
+
details = { truncation };
|
|
223
|
+
}
|
|
224
|
+
else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {
|
|
225
|
+
const remaining = totalFileLines - (startLine + userLimitedLines);
|
|
226
|
+
const nextOffset = startLine + userLimitedLines + 1;
|
|
227
|
+
diagnostics.push({
|
|
228
|
+
severity: "info",
|
|
229
|
+
message: `${remaining} more lines in file. Use offset=${nextOffset} to continue.`,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
output: outputText === "" ? [] : [{ type: "text", text: outputText }],
|
|
234
|
+
structuredOutput: outputText,
|
|
235
|
+
...(details === undefined ? {} : { details }),
|
|
236
|
+
diagnostics,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
//# sourceMappingURL=read.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAe,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAChF,OAAO,EAGN,UAAU,EAEV,YAAY,EACZ,aAAa,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAEV,cAAc,EACd,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,8BAA8B,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7E,OAAO,EACN,YAAY,EAGZ,kBAAkB,EAClB,WAAW,EACX,aAAa,EACb,QAAQ,GACR,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD,MAAM,UAAU,GAAG,GAAG,CACrB;IACC,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IAC7E,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC,CAAC;IAClF,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,WAAW,EAAE,iCAAiC,EAAE,CAAC,CAAC;CACnE,EACD,EAAE,IAA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C,CAAC,EAAE,OAAO,EAAE,CAAC;QAC7C,WAAW;KACX,CAAC;AACH,CAAC","sourcesContent":["import type { Context } from \"@diffra-ai/chord/context\";\nimport { characterEnd } from \"@diffra-ai/chord/output\";\nimport { lit, num, obj, opt, type Static, str, union } from \"@diffra-ai/schema\";\nimport {\n\ttype BinaryReader,\n\ttype FileInfo,\n\tgetOrThrow,\n\ttype LineScan,\n\trangeDecoder,\n\tstartsWithBom,\n} from \"../env/index.ts\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolDiagnostic, ToolExecutionApi, ToolExecutionResult, ToolRegistration } from \"../harness/types.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n\ttruncateHeadOf,\n\tutf8ByteLength,\n} from \"../truncate.ts\";\nimport { requireEnv } from \"./env.ts\";\nimport { detectSupportedImageMimeTypeOf, imageDimensions } from \"./image.ts\";\nimport {\n\tbase64Length,\n\ttype ImageLimits,\n\ttype ImageProcessor,\n\tINLINE_IMAGE_TYPES,\n\timageLimits,\n\tpreparedNotes,\n\ttoBase64,\n} from \"./image-processor.ts\";\nimport { resolveReadToolPath } from \"./path-utils.ts\";\n\nconst readSchema = obj(\n\t{\n\t\tpath: str({ description: \"Path to the file to read (relative or absolute)\" }),\n\t\toffset: opt(num({ description: \"Line number to start reading from (1-indexed)\" })),\n\t\tlimit: opt(num({ description: \"Maximum number of lines to read\" })),\n\t},\n\t{ open: true },\n);\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\n/**\n * What programs such as code mode scripts get: the text of a text file, or the image block of an image, which code\n * mode's `image()` shows.\n */\nconst readStructuredOutputSchema = union([\n\tstr(),\n\tobj({ type: lit(\"image\"), data: str(), mimeType: str() }, { open: true }),\n]);\n\nexport type ReadToolDetails = {\n\t/** How the shown text was cut; the text itself is the result content. */\n\ttruncation?: Omit<TruncationResult, \"content\">;\n\t/**\n\t * Id of the conversation's model when the image was read, if it has no image input. For UIs only: the model gets\n\t * diffra-ai's placeholder per request, so the stored result stays right after a switch to a vision model.\n\t */\n\timageUnsupportedByModel?: string;\n};\n\nconst READ_CHUNK = 64 * 1024;\n\n/** `Array.prototype.slice`'s conversion of an index: NaN is 0, other values truncate toward zero. */\nfunction sliceIndex(value: number): number {\n\treturn Number.isNaN(value) ? 0 : Math.trunc(value);\n}\n\n/**\n * The decoded start of bytes `[start, end)` of the file, decoded as part of the whole file: all of it, or enough for\n * `truncateHeadOf` (more than `DEFAULT_MAX_BYTES + 1` bytes, or `DEFAULT_MAX_LINES` newlines).\n */\nasync function readHead(\n\treader: BinaryReader,\n\tstart: number,\n\tend: number,\n\tskipBom: boolean,\n\tcontext: Context,\n): Promise<string> {\n\tconst decoder = rangeDecoder();\n\tlet text = \"\";\n\tlet newlines = 0;\n\tfor (let position = skipBom && start === 0 ? 3 : start; position < end; ) {\n\t\tconst bytes = getOrThrow(await reader.read(position, Math.min(READ_CHUNK, end - position), context));\n\t\tif (bytes.length === 0) break;\n\t\tposition += bytes.length;\n\t\tconst decoded = decoder.decode(bytes, { stream: true });\n\t\ttext += decoded;\n\t\tfor (let index = decoded.indexOf(\"\\n\"); index !== -1; index = decoded.indexOf(\"\\n\", index + 1)) newlines++;\n\t\tif (newlines >= DEFAULT_MAX_LINES || utf8ByteLength(text) > DEFAULT_MAX_BYTES + 1) return text;\n\t}\n\treturn text + decoder.decode();\n}\n\nexport type ReadToolOptions = {\n\t/** Resizes and converts images; without one, images within `DEFAULT_IMAGE_LIMITS.maxBytes` pass through as they are. */\n\treadonly images?: ImageProcessor;\n};\n\n/**\n * Reads text files and images. Remarks about truncation, continuation, and image processing are diagnostics; the content\n * is only file text, or one image. Programs get the text, or the image's `ImageContent`.\n */\nexport function createReadTool(options: ReadToolOptions = {}): ToolRegistration<typeof readSchema, ReadToolDetails> {\n\tconst formats = options.images === undefined ? \"jpg, png, gif, webp\" : \"jpg, png, gif, webp, bmp\";\n\treturn defineTool({\n\t\tname: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (${formats}). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tparameters: readSchema,\n\t\tstructuredOutputSchema: readStructuredOutputSchema,\n\t\tasync execute(args, api, context) {\n\t\t\tconst { path, offset, limit } = args;\n\t\t\tconst env = requireEnv(api);\n\t\t\tconst absolutePath = await resolveReadToolPath(env, path, context);\n\t\t\tconst reader = getOrThrow(await env.openBinaryReader(absolutePath, undefined, context));\n\t\t\ttry {\n\t\t\t\t// A concurrent writer can change the file between the scan and the reads. Appending (a growing log) leaves\n\t\t\t\t// the scanned text as it was; an image must be whole. Otherwise the file is read again once.\n\t\t\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\t\t\tconst before = getOrThrow(await reader.info(context));\n\t\t\t\t\tconst mimeType = await detectSupportedImageMimeTypeOf({\n\t\t\t\t\t\tsize: before.size,\n\t\t\t\t\t\tread: async (position, length) => getOrThrow(await reader.read(position, length, context)),\n\t\t\t\t\t});\n\t\t\t\t\tconst result =\n\t\t\t\t\t\tmimeType === undefined\n\t\t\t\t\t\t\t? await readText(reader, path, offset, limit, context)\n\t\t\t\t\t\t\t: await readImage(\n\t\t\t\t\t\t\t\t\treader,\n\t\t\t\t\t\t\t\t\tbefore,\n\t\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t\tmimeType,\n\t\t\t\t\t\t\t\t\toptions.images,\n\t\t\t\t\t\t\t\t\tawait imageModel(api, context),\n\t\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\tconst after = getOrThrow(await reader.info(context));\n\t\t\t\t\tconst unchanged = after.size === before.size && after.mtimeMs === before.mtimeMs;\n\t\t\t\t\tif (unchanged || (mimeType === undefined && after.size > before.size)) return result;\n\t\t\t\t\tif (attempt === 1) throw new Error(`${path} changed while it was read`);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader.close(context);\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * One image block, prepared by `processor` or, without one, as it is when its format is inline and it fits the limits\n * (its size is checked before reading it, its dimensions from its header); otherwise an error result saying why. What happened to the image is an `info` diagnostic, so programs get the\n * bare `ImageContent`. A model without image input sees diffra-ai's placeholder instead, decided per request; `details`\n * names it for UIs.\n */\nasync function readImage(\n\treader: BinaryReader,\n\tinfo: FileInfo,\n\tpath: string,\n\tmimeType: string,\n\tprocessor: ImageProcessor | undefined,\n\t{ limits, imageUnsupportedByModel }: ImageModel,\n\tcontext: Context,\n): Promise<ToolExecutionResult<ReadToolDetails>> {\n\tlet image: { readonly data: string; readonly mimeType: string };\n\tconst notes: string[] = [];\n\tif (processor !== undefined) {\n\t\tconst bytes = getOrThrow(await reader.read(0, info.size, context));\n\t\tconst prepared = await processor.prepare(bytes, mimeType, limits);\n\t\tif (prepared === undefined)\n\t\t\treturn imageError(`${path} is an image (${mimeType}) that cannot be prepared for the model`);\n\t\timage = prepared;\n\t\tnotes.push(...preparedNotes(prepared));\n\t} else {\n\t\tif (!INLINE_IMAGE_TYPES.has(mimeType)) {\n\t\t\treturn imageError(\n\t\t\t\t`${path} is an image (${mimeType}) that needs converting, and no image processor is configured`,\n\t\t\t);\n\t\t}\n\t\tconst unshrinkable = \"and no image processor is configured to shrink it\";\n\t\tif (base64Length(info.size) > limits.maxBytes) {\n\t\t\treturn imageError(\n\t\t\t\t`${path} is an image (${mimeType}) of ${formatSize(info.size)}, too large to send, ${unshrinkable}`,\n\t\t\t);\n\t\t}\n\t\tconst bytes = getOrThrow(await reader.read(0, info.size, context));\n\t\tconst size = imageDimensions(bytes, mimeType);\n\t\tif (size === undefined) return imageError(`${path} is an image (${mimeType}) whose size cannot be read`);\n\t\tif (size.width > limits.maxWidth || size.height > limits.maxHeight) {\n\t\t\treturn imageError(\n\t\t\t\t`${path} is an image (${mimeType}) of ${size.width}x${size.height}, larger than ${limits.maxWidth}x${limits.maxHeight}, ${unshrinkable}`,\n\t\t\t);\n\t\t}\n\t\timage = { data: toBase64(bytes), mimeType };\n\t}\n\tconst diagnostics: ToolDiagnostic[] = [\n\t\t{ severity: \"info\", code: \"image\", message: [`Read image file [${image.mimeType}].`, ...notes].join(\" \") },\n\t];\n\tconst block = { type: \"image\" as const, data: image.data, mimeType: image.mimeType };\n\treturn {\n\t\toutput: [block],\n\t\tstructuredOutput: block,\n\t\t...(imageUnsupportedByModel === undefined ? {} : { details: { imageUnsupportedByModel } }),\n\t\tdiagnostics,\n\t};\n}\n\n/** The conversation's model as images see it: its limits, and its id if it has no image input. */\ntype ImageModel = { readonly limits: ImageLimits; readonly imageUnsupportedByModel?: string };\n\n/**\n * The conversation model's image limits (`imageLimits`), and its id if it has no image input. Without a resolvable\n * model, the defaults and no id.\n */\nasync function imageModel(api: ToolExecutionApi, context: Context): Promise<ImageModel> {\n\tconst ref = (await api.agent(context)).model;\n\tconst model = ref === undefined ? undefined : api.models.getModel(ref.provider, ref.modelId);\n\treturn {\n\t\t...(model === undefined || model.input.includes(\"image\") ? {} : { imageUnsupportedByModel: model.id }),\n\t\tlimits: imageLimits(model),\n\t};\n}\n\nfunction imageError(message: string): ToolExecutionResult<ReadToolDetails> {\n\treturn { output: [], isError: true, diagnostics: [{ severity: \"error\", code: \"unsupported_image\", message }] };\n}\n\n/**\n * The read result for the opened file. It equals decoding the whole file with `TextDecoder`, splitting it on `\\n`,\n * and bounding the selected lines with `truncateHead`, while reading only one scan's worth of the file plus the head.\n */\nasync function readText(\n\treader: BinaryReader,\n\tpath: string,\n\toffset: number | undefined,\n\tlimit: number | undefined,\n\tcontext: Context,\n) {\n\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\tconst startLineDisplay = startLine + 1;\n\t// Lines are selected like `allLines.slice(startLine, endLine)`, which truncates fractional indices.\n\tconst sliceStart = sliceIndex(startLine);\n\t// One pass finds the line count and the selection; a selection past the last line ends with it, as `slice` does,\n\t// and an empty one (a zero or negative limit) is scanned as one line and then ignored.\n\t// A start beyond any file is scanned from 0 only to count lines; the offset check below then fails as before.\n\tconst scanStart = Number.isSafeInteger(sliceStart) ? sliceStart : 0;\n\tconst requestedEnd = limit === undefined ? undefined : Math.max(scanStart + 1, sliceIndex(startLine + limit));\n\tconst scanEnd = requestedEnd !== undefined && Number.isSafeInteger(requestedEnd) ? requestedEnd : undefined;\n\tconst scanOf = async (endLine: number | undefined): Promise<LineScan> =>\n\t\tgetOrThrow(\n\t\t\tawait reader.scanLines({ startLine: scanStart, ...(endLine === undefined ? {} : { endLine }) }, context),\n\t\t);\n\tlet scan = await scanOf(scanEnd);\n\tconst totalFileLines = scan.newlines + 1;\n\tif (startLine >= totalFileLines) {\n\t\tthrow new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n\t}\n\n\tlet userLimitedLines: number | undefined;\n\tlet selectedLineCount = totalFileLines - sliceStart;\n\tif (limit !== undefined) {\n\t\tconst endLine = Math.min(startLine + limit, totalFileLines);\n\t\tuserLimitedLines = endLine - startLine;\n\t\t// `slice` counts a negative end from the end of the lines, which only the line count tells; scan again for it.\n\t\tconst relativeEnd = sliceIndex(endLine);\n\t\tconst sliceEnd = relativeEnd < 0 ? Math.max(totalFileLines + relativeEnd, 0) : relativeEnd;\n\t\tselectedLineCount = Math.max(0, sliceEnd - sliceStart);\n\t\tif (selectedLineCount > 0 && relativeEnd < 0) scan = await scanOf(sliceEnd);\n\t}\n\tconst empty = selectedLineCount === 0;\n\t// Counted like `truncateHead`: a trailing newline adds no line, and empty text has none.\n\tconst endsWithNewline = !empty && scan.lastLineStart === scan.end && scan.lastLineStart > scan.start;\n\tconst totals = {\n\t\tlines: empty || scan.selectedBytes === 0 ? 0 : selectedLineCount - (endsWithNewline ? 1 : 0),\n\t\tbytes: empty ? 0 : scan.selectedBytes,\n\t};\n\tconst firstBytes = getOrThrow(await reader.read(0, 3, context));\n\tconst head = empty ? \"\" : await readHead(reader, scan.start, scan.end, startsWithBom(firstBytes), context);\n\n\tconst { content: headText, ...truncation } = truncateHeadOf(head, totals);\n\tconst diagnostics: ToolDiagnostic[] = [];\n\tlet outputText = headText;\n\tlet details: ReadToolDetails | undefined;\n\tif (truncation.firstLineExceedsLimit) {\n\t\t// Show the start of the line, cut at the byte limit on a character boundary. Like `allLines[startLine]`, a\n\t\t// fractional start line names no line.\n\t\tconst integral = Number.isInteger(startLine);\n\t\tconst lineBytes = new TextEncoder().encode(integral ? (head.split(\"\\n\")[0] ?? \"\") : \"\");\n\t\tconst lineSize = integral ? scan.firstLineBytes : 0;\n\t\tconst end = characterEnd(lineBytes, DEFAULT_MAX_BYTES);\n\t\toutputText = new TextDecoder().decode(lineBytes.subarray(0, end));\n\t\tdiagnostics.push({\n\t\t\tseverity: \"warn\",\n\t\t\tcode: \"truncated\",\n\t\t\tmessage: `Line ${startLineDisplay} is ${formatSize(lineSize)}, exceeds the ${formatSize(DEFAULT_MAX_BYTES)} limit; showing its first ${formatSize(end)}. Use bash: sed -n '${startLineDisplay}p' ${path} | tail -c +${end + 1}`,\n\t\t});\n\t\tdetails = { truncation: { ...truncation, outputBytes: end, outputLines: 1 } };\n\t} else if (truncation.truncated) {\n\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\tconst nextOffset = endLineDisplay + 1;\n\t\tconst limitText = truncation.truncatedBy === \"lines\" ? \"\" : ` (${formatSize(DEFAULT_MAX_BYTES)} limit)`;\n\t\tdiagnostics.push({\n\t\t\tseverity: \"info\",\n\t\t\tcode: \"truncated\",\n\t\t\tmessage: `Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}${limitText}. Use offset=${nextOffset} to continue.`,\n\t\t});\n\t\tdetails = { truncation };\n\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {\n\t\tconst remaining = totalFileLines - (startLine + userLimitedLines);\n\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\tdiagnostics.push({\n\t\t\tseverity: \"info\",\n\t\t\tmessage: `${remaining} more lines in file. Use offset=${nextOffset} to continue.`,\n\t\t});\n\t}\n\n\treturn {\n\t\toutput: outputText === \"\" ? [] : [{ type: \"text\" as const, text: outputText }],\n\t\tstructuredOutput: outputText,\n\t\t...(details === undefined ? {} : { details }),\n\t\tdiagnostics,\n\t};\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Static } from "@diffra-ai/schema";
|
|
2
|
+
import type { ToolRegistration } from "../harness/types.ts";
|
|
3
|
+
declare const writeSchema: import("@diffra-ai/schema").Schema<{
|
|
4
|
+
path: string;
|
|
5
|
+
content: string;
|
|
6
|
+
}>;
|
|
7
|
+
export type WriteToolInput = Static<typeof writeSchema>;
|
|
8
|
+
export declare function createWriteTool(): ToolRegistration<typeof writeSchema>;
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=write.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../src/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAO,KAAK,MAAM,EAAO,MAAM,mBAAmB,CAAC;AAG1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAK5D,QAAA,MAAM,WAAW;;;EAMhB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD,wBAAgB,eAAe,IAAI,gBAAgB,CAAC,OAAO,WAAW,CAAC,CAuBtE"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { obj, str } from "@diffra-ai/schema";
|
|
2
|
+
import { getOrThrow } from "../env/index.js";
|
|
3
|
+
import { defineTool } from "../harness/define.js";
|
|
4
|
+
import { requireEnv } from "./env.js";
|
|
5
|
+
import { withFileMutationQueue } from "./file-mutation-queue.js";
|
|
6
|
+
import { resolveToolPath } from "./path-utils.js";
|
|
7
|
+
const writeSchema = obj({
|
|
8
|
+
path: str({ description: "Path to the file to write (relative or absolute)" }),
|
|
9
|
+
content: str({ description: "Content to write to the file" }),
|
|
10
|
+
}, { open: true });
|
|
11
|
+
export function createWriteTool() {
|
|
12
|
+
return defineTool({
|
|
13
|
+
name: "write",
|
|
14
|
+
description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
|
|
15
|
+
parameters: writeSchema,
|
|
16
|
+
async execute(args, api, context) {
|
|
17
|
+
const { path, content } = args;
|
|
18
|
+
const env = requireEnv(api);
|
|
19
|
+
const absolutePath = await resolveToolPath(env, path, context);
|
|
20
|
+
return withFileMutationQueue(env, absolutePath, async () => {
|
|
21
|
+
if (context.abortSignal?.aborted)
|
|
22
|
+
throw new Error("Operation aborted");
|
|
23
|
+
getOrThrow(await env.writeFile(absolutePath, content, context));
|
|
24
|
+
if (context.abortSignal?.aborted)
|
|
25
|
+
throw new Error("Operation aborted");
|
|
26
|
+
return { output: [{ type: "text", text: `Successfully wrote to ${path}` }] };
|
|
27
|
+
}, context);
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=write.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"write.js","sourceRoot":"","sources":["../../src/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAe,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,MAAM,WAAW,GAAG,GAAG,CACtB;IACC,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,kDAAkD,EAAE,CAAC;IAC9E,OAAO,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,8BAA8B,EAAE,CAAC;CAC7D,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACd,CAAC;AAIF,MAAM,UAAU,eAAe;IAC9B,OAAO,UAAU,CAAC;QACjB,IAAI,EAAE,OAAO;QACb,WAAW,EACV,iIAAiI;QAClI,UAAU,EAAE,WAAW;QACvB,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO;YAC/B,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;YAC/B,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;YAC5B,MAAM,YAAY,GAAG,MAAM,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;YAC/D,OAAO,qBAAqB,CAC3B,GAAG,EACH,YAAY,EACZ,KAAK,IAAI,EAAE;gBACV,IAAI,OAAO,CAAC,WAAW,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBACvE,UAAU,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;gBAChE,IAAI,OAAO,CAAC,WAAW,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBACvE,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;YAC9E,CAAC,EACD,OAAO,CACP,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { obj, type Static, str } from \"@diffra-ai/schema\";\nimport { getOrThrow } from \"../env/index.ts\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\nimport { requireEnv } from \"./env.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\n\nconst writeSchema = obj(\n\t{\n\t\tpath: str({ description: \"Path to the file to write (relative or absolute)\" }),\n\t\tcontent: str({ description: \"Content to write to the file\" }),\n\t},\n\t{ open: true },\n);\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport function createWriteTool(): ToolRegistration<typeof writeSchema> {\n\treturn defineTool({\n\t\tname: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tparameters: writeSchema,\n\t\tasync execute(args, api, context) {\n\t\t\tconst { path, content } = args;\n\t\t\tconst env = requireEnv(api);\n\t\t\tconst absolutePath = await resolveToolPath(env, path, context);\n\t\t\treturn withFileMutationQueue(\n\t\t\t\tenv,\n\t\t\t\tabsolutePath,\n\t\t\t\tasync () => {\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t\tgetOrThrow(await env.writeFile(absolutePath, content, context));\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t\treturn { output: [{ type: \"text\", text: `Successfully wrote to ${path}` }] };\n\t\t\t\t},\n\t\t\t\tcontext,\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { utf8ByteLength } from "@diffra-ai/chord/output";
|
|
2
|
+
/**
|
|
3
|
+
* Shared truncation utilities for tool outputs.
|
|
4
|
+
*
|
|
5
|
+
* Truncation is based on two independent limits - whichever is hit first wins:
|
|
6
|
+
* - Line limit (default: 2000 lines)
|
|
7
|
+
* - Byte limit (default: 50KB)
|
|
8
|
+
*
|
|
9
|
+
* Never returns partial lines. Tool output streams are bounded by `OutputBuffer` from `@diffra-ai/chord/output` instead.
|
|
10
|
+
*/
|
|
11
|
+
export declare const DEFAULT_MAX_LINES = 2000;
|
|
12
|
+
export declare const DEFAULT_MAX_BYTES: number;
|
|
13
|
+
export interface TruncationResult {
|
|
14
|
+
/** The truncated content */
|
|
15
|
+
content: string;
|
|
16
|
+
/** Whether truncation occurred */
|
|
17
|
+
truncated: boolean;
|
|
18
|
+
/** Which limit was hit: "lines", "bytes", or null if not truncated */
|
|
19
|
+
truncatedBy: "lines" | "bytes" | null;
|
|
20
|
+
/** Total number of lines in the original content */
|
|
21
|
+
totalLines: number;
|
|
22
|
+
/** Total number of bytes in the original content */
|
|
23
|
+
totalBytes: number;
|
|
24
|
+
/** Number of complete lines in the truncated output */
|
|
25
|
+
outputLines: number;
|
|
26
|
+
/** Number of bytes in the truncated output */
|
|
27
|
+
outputBytes: number;
|
|
28
|
+
/** Whether the last line was partially truncated (only for tail truncation edge case) */
|
|
29
|
+
lastLinePartial: boolean;
|
|
30
|
+
/** Whether the first line exceeded the byte limit (for head truncation) */
|
|
31
|
+
firstLineExceedsLimit: boolean;
|
|
32
|
+
/** The max lines limit that was applied */
|
|
33
|
+
maxLines: number;
|
|
34
|
+
/** The max bytes limit that was applied */
|
|
35
|
+
maxBytes: number;
|
|
36
|
+
}
|
|
37
|
+
export interface TruncationOptions {
|
|
38
|
+
/** Maximum number of lines (default: 2000) */
|
|
39
|
+
maxLines?: number;
|
|
40
|
+
/** Maximum number of bytes (default: 50KB) */
|
|
41
|
+
maxBytes?: number;
|
|
42
|
+
}
|
|
43
|
+
export { utf8ByteLength };
|
|
44
|
+
/**
|
|
45
|
+
* Format bytes as human-readable size.
|
|
46
|
+
*/
|
|
47
|
+
export declare function formatSize(bytes: number): string;
|
|
48
|
+
/**
|
|
49
|
+
* Truncate content from the head (keep first N lines/bytes).
|
|
50
|
+
* Suitable for file reads where you want to see the beginning.
|
|
51
|
+
*
|
|
52
|
+
* Never returns partial lines. If first line exceeds byte limit,
|
|
53
|
+
* returns empty content with firstLineExceedsLimit=true.
|
|
54
|
+
*/
|
|
55
|
+
export declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult;
|
|
56
|
+
/**
|
|
57
|
+
* `truncateHead` of a text known by a prefix and its totals (`lines` counted like `truncateHead`, ignoring a trailing
|
|
58
|
+
* newline). The prefix must be the whole text, or longer than `maxBytes + 1` UTF-8 bytes, or hold at least `maxLines`
|
|
59
|
+
* newlines; then the result equals `truncateHead` of the whole text.
|
|
60
|
+
*/
|
|
61
|
+
export declare function truncateHeadOf(prefix: string, totals: {
|
|
62
|
+
readonly lines: number;
|
|
63
|
+
readonly bytes: number;
|
|
64
|
+
}, options?: TruncationOptions): TruncationResult;
|
|
65
|
+
//# sourceMappingURL=truncate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"truncate.d.ts","sourceRoot":"","sources":["../src/truncate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD;;;;;;;;GAQG;AAEH,eAAO,MAAM,iBAAiB,OAAO,CAAC;AACtC,eAAO,MAAM,iBAAiB,QAAY,CAAC;AAE3C,MAAM,WAAW,gBAAgB;IAChC,4BAA4B;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,SAAS,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,WAAW,EAAE,OAAO,GAAG,OAAO,GAAG,IAAI,CAAC;IACtC,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,uDAAuD;IACvD,WAAW,EAAE,MAAM,CAAC;IACpB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,yFAAyF;IACzF,eAAe,EAAE,OAAO,CAAC;IACzB,2EAA2E;IAC3E,qBAAqB,EAAE,OAAO,CAAC;IAC/B,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IACjC,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,OAAO,EAAE,cAAc,EAAE,CAAC;AAS1B;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAQhD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAM/F;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC7B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAC1D,OAAO,GAAE,iBAAsB,GAC7B,gBAAgB,CAgFlB"}
|
package/dist/truncate.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { utf8ByteLength } from "@diffra-ai/chord/output";
|
|
2
|
+
/**
|
|
3
|
+
* Shared truncation utilities for tool outputs.
|
|
4
|
+
*
|
|
5
|
+
* Truncation is based on two independent limits - whichever is hit first wins:
|
|
6
|
+
* - Line limit (default: 2000 lines)
|
|
7
|
+
* - Byte limit (default: 50KB)
|
|
8
|
+
*
|
|
9
|
+
* Never returns partial lines. Tool output streams are bounded by `OutputBuffer` from `@diffra-ai/chord/output` instead.
|
|
10
|
+
*/
|
|
11
|
+
export const DEFAULT_MAX_LINES = 2000;
|
|
12
|
+
export const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB
|
|
13
|
+
// One implementation, shared with the output buffer.
|
|
14
|
+
export { utf8ByteLength };
|
|
15
|
+
function splitLinesForCounting(content) {
|
|
16
|
+
if (content.length === 0)
|
|
17
|
+
return [];
|
|
18
|
+
const lines = content.split("\n");
|
|
19
|
+
if (content.endsWith("\n"))
|
|
20
|
+
lines.pop();
|
|
21
|
+
return lines;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Format bytes as human-readable size.
|
|
25
|
+
*/
|
|
26
|
+
export function formatSize(bytes) {
|
|
27
|
+
if (bytes < 1024) {
|
|
28
|
+
return `${bytes}B`;
|
|
29
|
+
}
|
|
30
|
+
else if (bytes < 1024 * 1024) {
|
|
31
|
+
return `${(bytes / 1024).toFixed(1)}KB`;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Truncate content from the head (keep first N lines/bytes).
|
|
39
|
+
* Suitable for file reads where you want to see the beginning.
|
|
40
|
+
*
|
|
41
|
+
* Never returns partial lines. If first line exceeds byte limit,
|
|
42
|
+
* returns empty content with firstLineExceedsLimit=true.
|
|
43
|
+
*/
|
|
44
|
+
export function truncateHead(content, options = {}) {
|
|
45
|
+
return truncateHeadOf(content, { lines: splitLinesForCounting(content).length, bytes: utf8ByteLength(content) }, options);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* `truncateHead` of a text known by a prefix and its totals (`lines` counted like `truncateHead`, ignoring a trailing
|
|
49
|
+
* newline). The prefix must be the whole text, or longer than `maxBytes + 1` UTF-8 bytes, or hold at least `maxLines`
|
|
50
|
+
* newlines; then the result equals `truncateHead` of the whole text.
|
|
51
|
+
*/
|
|
52
|
+
export function truncateHeadOf(prefix, totals, options = {}) {
|
|
53
|
+
const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
|
|
54
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
55
|
+
const totalBytes = totals.bytes;
|
|
56
|
+
const lines = splitLinesForCounting(prefix);
|
|
57
|
+
const totalLines = totals.lines;
|
|
58
|
+
// Check if no truncation needed
|
|
59
|
+
if (totalLines <= maxLines && totalBytes <= maxBytes) {
|
|
60
|
+
return {
|
|
61
|
+
content: prefix,
|
|
62
|
+
truncated: false,
|
|
63
|
+
truncatedBy: null,
|
|
64
|
+
totalLines,
|
|
65
|
+
totalBytes,
|
|
66
|
+
outputLines: totalLines,
|
|
67
|
+
outputBytes: totalBytes,
|
|
68
|
+
lastLinePartial: false,
|
|
69
|
+
firstLineExceedsLimit: false,
|
|
70
|
+
maxLines,
|
|
71
|
+
maxBytes,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
// Check if first line alone exceeds byte limit
|
|
75
|
+
const firstLineBytes = utf8ByteLength(lines[0]);
|
|
76
|
+
if (firstLineBytes > maxBytes) {
|
|
77
|
+
return {
|
|
78
|
+
content: "",
|
|
79
|
+
truncated: true,
|
|
80
|
+
truncatedBy: "bytes",
|
|
81
|
+
totalLines,
|
|
82
|
+
totalBytes,
|
|
83
|
+
outputLines: 0,
|
|
84
|
+
outputBytes: 0,
|
|
85
|
+
lastLinePartial: false,
|
|
86
|
+
firstLineExceedsLimit: true,
|
|
87
|
+
maxLines,
|
|
88
|
+
maxBytes,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
// Collect complete lines that fit
|
|
92
|
+
const outputLinesArr = [];
|
|
93
|
+
let outputBytesCount = 0;
|
|
94
|
+
let truncatedBy = "lines";
|
|
95
|
+
for (let i = 0; i < lines.length && i < maxLines; i++) {
|
|
96
|
+
const line = lines[i];
|
|
97
|
+
const lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0); // +1 for newline
|
|
98
|
+
if (outputBytesCount + lineBytes > maxBytes) {
|
|
99
|
+
truncatedBy = "bytes";
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
outputLinesArr.push(line);
|
|
103
|
+
outputBytesCount += lineBytes;
|
|
104
|
+
}
|
|
105
|
+
// Without a byte break, only omitted lines prove the line limit was reached; otherwise a trailing newline exceeded bytes.
|
|
106
|
+
if (truncatedBy !== "bytes")
|
|
107
|
+
truncatedBy = outputLinesArr.length < totalLines ? "lines" : "bytes";
|
|
108
|
+
const outputContent = outputLinesArr.join("\n");
|
|
109
|
+
const finalOutputBytes = utf8ByteLength(outputContent);
|
|
110
|
+
return {
|
|
111
|
+
content: outputContent,
|
|
112
|
+
truncated: true,
|
|
113
|
+
truncatedBy,
|
|
114
|
+
totalLines,
|
|
115
|
+
totalBytes,
|
|
116
|
+
outputLines: outputLinesArr.length,
|
|
117
|
+
outputBytes: finalOutputBytes,
|
|
118
|
+
lastLinePartial: false,
|
|
119
|
+
firstLineExceedsLimit: false,
|
|
120
|
+
maxLines,
|
|
121
|
+
maxBytes,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=truncate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"truncate.js","sourceRoot":"","sources":["../src/truncate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO;AAkCnD,qDAAqD;AACrD,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B,SAAS,qBAAqB,CAAC,OAAe;IAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACpC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClC,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,KAAK,CAAC,GAAG,EAAE,CAAC;IACxC,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa;IACvC,IAAI,KAAK,GAAG,IAAI,EAAE,CAAC;QAClB,OAAO,GAAG,KAAK,GAAG,CAAC;IACpB,CAAC;SAAM,IAAI,KAAK,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;QAChC,OAAO,GAAG,CAAC,KAAK,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G,cAAc,CAAC,aAAa,CAAC,CAAC;IAEvD,OAAO;QACN,OAAO,EAAE,aAAa;QACtB,SAAS,EAAE,IAAI;QACf,WAAW;QACX,UAAU;QACV,UAAU;QACV,WAAW,EAAE,cAAc,CAAC,MAAM;QAClC,WAAW,EAAE,gBAAgB;QAC7B,eAAe,EAAE,KAAK;QACtB,qBAAqB,EAAE,KAAK;QAC5B,QAAQ;QACR,QAAQ;KACR,CAAC;AACH,CAAC","sourcesContent":["import { utf8ByteLength } from \"@diffra-ai/chord/output\";\n/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines. Tool output streams are bounded by `OutputBuffer` from `@diffra-ai/chord/output` instead.\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\n// One implementation, shared with the output buffer.\nexport { utf8ByteLength };\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) return [];\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) lines.pop();\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\treturn truncateHeadOf(\n\t\tcontent,\n\t\t{ lines: splitLinesForCounting(content).length, bytes: utf8ByteLength(content) },\n\t\toptions,\n\t);\n}\n\n/**\n * `truncateHead` of a text known by a prefix and its totals (`lines` counted like `truncateHead`, ignoring a trailing\n * newline). The prefix must be the whole text, or longer than `maxBytes + 1` UTF-8 bytes, or hold at least `maxLines`\n * newlines; then the result equals `truncateHead` of the whole text.\n */\nexport function truncateHeadOf(\n\tprefix: string,\n\ttotals: { readonly lines: number; readonly bytes: number },\n\toptions: TruncationOptions = {},\n): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = totals.bytes;\n\tconst lines = splitLinesForCounting(prefix);\n\tconst totalLines = totals.lines;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent: prefix,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = utf8ByteLength(lines[0]);\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// Without a byte break, only omitted lines prove the line limit was reached; otherwise a trailing newline exceeded bytes.\n\tif (truncatedBy !== \"bytes\") truncatedBy = outputLinesArr.length < totalLines ? \"lines\" : \"bytes\";\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = utf8ByteLength(outputContent);\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n"]}
|