@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,265 @@
|
|
|
1
|
+
import { withoutAbortSignal } from "@diffra-ai/chord/context";
|
|
2
|
+
import { applyImmutable } from "@diffra-ai/chord/delta";
|
|
3
|
+
import { Watch } from "@diffra-ai/chord/watch";
|
|
4
|
+
import { idFromNumber } from "../ids.js";
|
|
5
|
+
import { closeEndOf, closeEnds, contained, guardObserver, observation, } from "../session/session.js";
|
|
6
|
+
import { AgentDoc } from "./agent.js";
|
|
7
|
+
import { InboxDoc } from "./inbox.js";
|
|
8
|
+
import { LiveDoc } from "./live.js";
|
|
9
|
+
import { ProviderDoc } from "./provider.js";
|
|
10
|
+
import { UsageDoc } from "./usage.js";
|
|
11
|
+
import { closedError } from "./util.js";
|
|
12
|
+
/** Default `ConversationWindow.min`. */
|
|
13
|
+
const DEFAULT_WINDOW_MIN = 50;
|
|
14
|
+
const MOUNTED = [
|
|
15
|
+
AgentDoc,
|
|
16
|
+
LiveDoc,
|
|
17
|
+
InboxDoc,
|
|
18
|
+
ProviderDoc,
|
|
19
|
+
UsageDoc,
|
|
20
|
+
];
|
|
21
|
+
const MOUNTED_KINDS = new Set(MOUNTED.map((token) => token.definition.kind));
|
|
22
|
+
const SCAN_PAGE_SIZE = 256;
|
|
23
|
+
const VIEWS = new WeakMap();
|
|
24
|
+
/** The view mounts of a Harness, for adapters built on them. */
|
|
25
|
+
export function conversationViews(harness) {
|
|
26
|
+
const views = VIEWS.get(harness);
|
|
27
|
+
if (views === undefined)
|
|
28
|
+
throw new Error("Not a Harness");
|
|
29
|
+
return views;
|
|
30
|
+
}
|
|
31
|
+
/** `window` with its defaults; throws a `RangeError` for bounds that are not integers or `max` below `min`. */
|
|
32
|
+
function resolveWindow(window) {
|
|
33
|
+
const min = window?.min ?? DEFAULT_WINDOW_MIN;
|
|
34
|
+
if (!Number.isSafeInteger(min) || min < 1)
|
|
35
|
+
throw new RangeError(`Window min must be an integer >= 1, got ${min}`);
|
|
36
|
+
const max = window?.max ?? 2 * min;
|
|
37
|
+
if (!Number.isSafeInteger(max) || max < min) {
|
|
38
|
+
throw new RangeError(`Window max must be an integer >= min (${min}), got ${max}`);
|
|
39
|
+
}
|
|
40
|
+
const from = window?.from;
|
|
41
|
+
if (from !== undefined && !Number.isSafeInteger(from)) {
|
|
42
|
+
throw new RangeError(`Window from must be an entry ID, got ${from}`);
|
|
43
|
+
}
|
|
44
|
+
return { from, min, max };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The Harness's conversation view mounts: at most one per conversation, built on the Session line by its first
|
|
48
|
+
* observer and dropped with its last. Each mount advances from the Session's commits as memory adopts them, deferred ones
|
|
49
|
+
* (`CommitPersistence`) before they are stored, and hands each observer the next revision of its own window.
|
|
50
|
+
*/
|
|
51
|
+
export class ConversationViews {
|
|
52
|
+
#session;
|
|
53
|
+
#mounts = new Map();
|
|
54
|
+
#closed = false;
|
|
55
|
+
constructor(session) {
|
|
56
|
+
this.#session = session;
|
|
57
|
+
VIEWS.set(session, this);
|
|
58
|
+
session.followCommits((publication, context) => {
|
|
59
|
+
for (const [id, mount] of this.#mounts)
|
|
60
|
+
advance(id, mount, publication, context, (error) => this.report(error));
|
|
61
|
+
});
|
|
62
|
+
session.subscribeClose(() => {
|
|
63
|
+
this.#closed = true;
|
|
64
|
+
const ends = closeEnds(this.#session.failure);
|
|
65
|
+
for (const mount of this.#mounts.values())
|
|
66
|
+
for (const windowed of [...mount.observers]) {
|
|
67
|
+
contained(() => windowed.observer.end(closeEndOf(windowed.observer, ends)), (error) => this.report(error));
|
|
68
|
+
}
|
|
69
|
+
this.#mounts.clear();
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Report an observer's listener error through the Harness. */
|
|
73
|
+
report(error) {
|
|
74
|
+
this.#session.report(error);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Attach a synchronous observer of the view (`Harness.observeConversation()`), behind `guardObserver()`; `context`
|
|
78
|
+
* governs only the attachment.
|
|
79
|
+
*/
|
|
80
|
+
async observe(id, observer, context, window) {
|
|
81
|
+
let value;
|
|
82
|
+
const attached = await this.attach(id, window, (current, release) => {
|
|
83
|
+
value = current;
|
|
84
|
+
return guardObserver(observer, release, (error) => this.report(error));
|
|
85
|
+
}, context);
|
|
86
|
+
const signal = context.abortSignal;
|
|
87
|
+
if (signal?.aborted) {
|
|
88
|
+
attached.detach();
|
|
89
|
+
throw signal.reason;
|
|
90
|
+
}
|
|
91
|
+
return observation(value, attached.observer);
|
|
92
|
+
}
|
|
93
|
+
/** A serialized watch of the view, an observer of its mount; aborting `context` ends it `aborted`. */
|
|
94
|
+
async watch(id, context, window) {
|
|
95
|
+
const { observer } = await this.attach(id, window, (value, release) => new Watch(value, release, (error) => this.#session.report(error)), context);
|
|
96
|
+
const signal = context.abortSignal;
|
|
97
|
+
if (signal?.aborted) {
|
|
98
|
+
observer.abort();
|
|
99
|
+
throw signal.reason;
|
|
100
|
+
}
|
|
101
|
+
if (signal !== undefined)
|
|
102
|
+
observer.observeAbort(signal);
|
|
103
|
+
return observer;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Register an observer created from its window's first revision, atomically on the Session line: it sees every later
|
|
107
|
+
* publication and nothing earlier. `release` drops it, and the mount with its last observer.
|
|
108
|
+
*/
|
|
109
|
+
async attach(id, window, create, context) {
|
|
110
|
+
const bounds = resolveWindow(window);
|
|
111
|
+
return this.#session.readOnLine(async (storage) => {
|
|
112
|
+
const mount = this.#mounts.get(id) ?? (await this.#build(storage, id, context));
|
|
113
|
+
const { entries, before } = await loadWindow(storage, id, bounds, context);
|
|
114
|
+
const value = view(mount.conversation, entries, before, mount.docs);
|
|
115
|
+
let windowed;
|
|
116
|
+
const detach = () => {
|
|
117
|
+
if (windowed !== undefined)
|
|
118
|
+
mount.observers.delete(windowed);
|
|
119
|
+
if (mount.observers.size === 0 && this.#mounts.get(id) === mount)
|
|
120
|
+
this.#mounts.delete(id);
|
|
121
|
+
};
|
|
122
|
+
const observer = create(value, detach);
|
|
123
|
+
// Close or cancellation may begin while the mount hydrates; register nothing then.
|
|
124
|
+
if (this.#closed)
|
|
125
|
+
throw closedError(this.#session);
|
|
126
|
+
context.abortSignal?.throwIfAborted();
|
|
127
|
+
windowed = { min: bounds.min, max: bounds.max, value, observer };
|
|
128
|
+
this.#mounts.set(id, mount);
|
|
129
|
+
mount.observers.add(windowed);
|
|
130
|
+
return { observer, detach };
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/** Hydrate a mount on the line, through the line's `storage`. */
|
|
134
|
+
async #build(storage, id, context) {
|
|
135
|
+
const conversation = await storage.conversation(id, context);
|
|
136
|
+
if (conversation === undefined)
|
|
137
|
+
throw new Error(`Conversation ${id} does not exist`);
|
|
138
|
+
const docs = {};
|
|
139
|
+
const incarnations = new Map();
|
|
140
|
+
for (const token of MOUNTED) {
|
|
141
|
+
const loaded = await this.#session.conversationDocumentOnLine(token, id, context);
|
|
142
|
+
if (loaded === undefined)
|
|
143
|
+
continue;
|
|
144
|
+
docs[token.definition.kind] = loaded.value;
|
|
145
|
+
incarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });
|
|
146
|
+
}
|
|
147
|
+
return { conversation, docs, incarnations, observers: new Set() };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** A view revision; `before` is a key only when set. */
|
|
151
|
+
function view(conversation, entries, before, docs) {
|
|
152
|
+
return before === undefined ? { conversation, entries, docs } : { conversation, entries, before, docs };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* A new observer's window, read on the Session line with bounded scans: the entries from `from` when at most `max` are
|
|
156
|
+
* at or after it, otherwise the newest `min`, and the entry before them.
|
|
157
|
+
*/
|
|
158
|
+
async function loadWindow(storage, conversationId, bounds, context) {
|
|
159
|
+
const { from, min, max } = bounds;
|
|
160
|
+
if (from !== undefined) {
|
|
161
|
+
const since = await scanUpTo(storage, { conversationId, minEntryId: from, order: "ascending" }, max + 1, context);
|
|
162
|
+
if (since.length <= max) {
|
|
163
|
+
const query = { conversationId, maxEntryId: idFromNumber(from - 1) };
|
|
164
|
+
const previous = (await storage.scanEntries(query, 1, undefined, context)).items[0];
|
|
165
|
+
return { entries: since, before: previous?.id };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const newest = await scanUpTo(storage, { conversationId }, min + 1, context);
|
|
169
|
+
const before = newest.length > min ? newest.pop().id : undefined;
|
|
170
|
+
return { entries: newest.reverse(), before };
|
|
171
|
+
}
|
|
172
|
+
/** Up to `limit` entries of `query`, following cursors past short pages. */
|
|
173
|
+
async function scanUpTo(storage, query, limit, context) {
|
|
174
|
+
const entries = [];
|
|
175
|
+
let cursor;
|
|
176
|
+
do {
|
|
177
|
+
const page = await storage.scanEntries(query, Math.min(SCAN_PAGE_SIZE, limit - entries.length), cursor, context);
|
|
178
|
+
entries.push(...page.items);
|
|
179
|
+
cursor = page.next;
|
|
180
|
+
} while (cursor !== undefined && entries.length < limit);
|
|
181
|
+
return entries;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Derive the mount's operations from one publication and hand each observer the next revision of its window; one that
|
|
185
|
+
* throws is reported through `report`, and the others still get theirs. Documents are applied once and shared; each
|
|
186
|
+
* window takes the appended entries and, past its `max`, drops its oldest down to its `min` in one splice.
|
|
187
|
+
*/
|
|
188
|
+
function advance(id, mount, publication, context, report) {
|
|
189
|
+
const docOps = [];
|
|
190
|
+
// Entry writes are published in ID order.
|
|
191
|
+
const appended = [];
|
|
192
|
+
for (const change of publication.changes) {
|
|
193
|
+
if (change.type === "entry" && change.value.conversationId === id) {
|
|
194
|
+
appended.push(change.value);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (change.type !== "document" || change.conversationId !== id)
|
|
198
|
+
continue;
|
|
199
|
+
const kind = change.record.kind;
|
|
200
|
+
if (!MOUNTED_KINDS.has(kind) || change.record.key !== undefined)
|
|
201
|
+
continue;
|
|
202
|
+
const path = ["docs", kind];
|
|
203
|
+
const mounted = mount.incarnations.get(kind);
|
|
204
|
+
if (change.kind === "retire") {
|
|
205
|
+
if (mounted?.id !== change.record.id)
|
|
206
|
+
continue;
|
|
207
|
+
mount.incarnations.delete(kind);
|
|
208
|
+
docOps.push(["d", path]);
|
|
209
|
+
}
|
|
210
|
+
else if (mounted?.id === change.record.id && mounted.version === change.version) {
|
|
211
|
+
for (const op of change.ops)
|
|
212
|
+
docOps.push(prefixed(op, path));
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
mount.incarnations.set(kind, { id: change.record.id, version: change.version });
|
|
216
|
+
docOps.push(["s", path, change.value]);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (docOps.length === 0 && appended.length === 0)
|
|
220
|
+
return;
|
|
221
|
+
if (docOps.length > 0)
|
|
222
|
+
mount.docs = applyImmutable({ docs: mount.docs }, docOps).docs;
|
|
223
|
+
const frameContext = withoutAbortSignal(context);
|
|
224
|
+
const inserted = appended;
|
|
225
|
+
for (const windowed of [...mount.observers]) {
|
|
226
|
+
const previous = windowed.value;
|
|
227
|
+
let entries = previous.entries;
|
|
228
|
+
let before = previous.before;
|
|
229
|
+
let ops = docOps;
|
|
230
|
+
if (appended.length > 0) {
|
|
231
|
+
ops = [...docOps, ["p", ["entries"], entries.length, 0, inserted]];
|
|
232
|
+
entries = entries.concat(appended);
|
|
233
|
+
if (entries.length > windowed.max) {
|
|
234
|
+
const drop = entries.length - windowed.min;
|
|
235
|
+
before = entries[drop - 1].id;
|
|
236
|
+
entries = entries.slice(drop);
|
|
237
|
+
ops.push(["p", ["entries"], 0, drop, []], ["s", ["before"], before]);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
windowed.value = view(mount.conversation, entries, before, mount.docs);
|
|
241
|
+
const call = { kind: "value", value: windowed.value, ops, retired: false };
|
|
242
|
+
contained(() => windowed.observer.advance(call, frameContext), report);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** `op` moved under `prefix`; a root replacement becomes a set of the prefix. */
|
|
246
|
+
function prefixed(op, prefix) {
|
|
247
|
+
const at = (path) => [...prefix, ...path];
|
|
248
|
+
switch (op[0]) {
|
|
249
|
+
case "r":
|
|
250
|
+
return ["s", prefix, op[1]];
|
|
251
|
+
case "p":
|
|
252
|
+
return ["p", at(op[1]), op[2], op[3], op[4]];
|
|
253
|
+
case "m":
|
|
254
|
+
return ["m", at(op[1]), op[2]];
|
|
255
|
+
case "s":
|
|
256
|
+
return ["s", at(op[1]), op[2]];
|
|
257
|
+
case "d":
|
|
258
|
+
return ["d", at(op[1])];
|
|
259
|
+
case "a":
|
|
260
|
+
return ["a", at(op[1]), op[2]];
|
|
261
|
+
case "t":
|
|
262
|
+
return ["t", at(op[1]), op[2]];
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=view.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"view.js","sourceRoot":"","sources":["../../src/harness/view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAyC,MAAM,wBAAwB,CAAC;AAE/F,OAAO,EAAE,KAAK,EAAmD,MAAM,wBAAwB,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,aAAa,EAEb,WAAW,GAEX,MAAM,uBAAuB,CAAC;AAe/B,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAk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AC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9C,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzB,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,CAAC;AACF,CAAC","sourcesContent":["import { type Context, withoutAbortSignal } from \"@diffra-ai/chord/context\";\nimport { applyImmutable, type NonEmptyPath, type Op, type Path } from \"@diffra-ai/chord/delta\";\nimport type { JsonValue } from \"@diffra-ai/chord/json\";\nimport { Watch, type WatchCall, type WatchEnd, type WatchHandle } from \"@diffra-ai/chord/watch\";\nimport { idFromNumber } from \"../ids.ts\";\nimport {\n\tcloseEndOf,\n\tcloseEnds,\n\tcontained,\n\tguardObserver,\n\ttype ObservedCommit,\n\tobservation,\n\ttype SessionImpl,\n} from \"../session/session.ts\";\nimport type {\n\tConversationDocToken,\n\tConversationId,\n\tConversationRecord,\n\tCursor,\n\tDocumentId,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tObservation,\n\tObserver,\n\tStorage,\n} from \"../types.ts\";\nimport { AgentDoc } from \"./agent.ts\";\nimport { InboxDoc } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { UsageDoc } from \"./usage.ts\";\nimport { closedError } from \"./util.ts\";\n\n/** Structural view of one conversation: a window over its transcript and its built-in documents (spec §9.3). */\nexport type ConversationView = {\n\treadonly conversation: ConversationRecord;\n\t/**\n\t * A window over the transcript, its fork-aware history (`Conversation.entries()`), in entry ID order. Head markers\n\t * such as compaction summaries sit where they were written; their `head` tells where the entries they summarize end.\n\t */\n\treadonly entries: readonly EntryRecord[];\n\t/** ID of the entry just before the window; absent when the window starts the transcript. */\n\treadonly before?: EntryId;\n\t/** Built-in conversation documents keyed by kind; absent documents are absent. */\n\treadonly docs: Readonly<Record<string, JsonObject>>;\n};\n\n/**\n * Which entries a view's window holds (spec §9.3). The window holds between `min` and `max` entries: it starts with\n * the newest `min` entries, takes appends, and once it would hold more than `max`, drops its oldest in one splice down\n * to `min`. With `from`, it starts at `from` instead when at most `max` entries are at or after it.\n */\nexport type ConversationWindow = {\n\t/**\n\t * Where the first value's window starts, inclusive, such as right after the newest entry a client has\n\t * (`ConversationTranscript.resume`). It selects only that first value: every entry committed after the attachment is\n\t * appended, whatever its ID. A `from` past the newest entry starts the window empty, with `before` the newest entry.\n\t */\n\treadonly from?: EntryId;\n\t/** Default 50; an integer, at least 1. */\n\treadonly min?: number;\n\t/** Default `2 * min`; an integer, at least `min`. */\n\treadonly max?: number;\n};\n\n/** Default `ConversationWindow.min`. */\nconst DEFAULT_WINDOW_MIN = 50;\n\n/** Receives each next revision of one observer's window, and the Session's close. */\nexport type ViewObserver = {\n\tadvance(call: WatchCall<ConversationView>, context: Context): void;\n\t/** The Session closed (`ended`), or failed (`failed`). */\n\tend(end: WatchEnd): void;\n};\n\nconst MOUNTED = [\n\tAgentDoc,\n\tLiveDoc,\n\tInboxDoc,\n\tProviderDoc,\n\tUsageDoc,\n] as unknown as readonly ConversationDocToken<JsonObject>[];\nconst MOUNTED_KINDS: ReadonlySet<string> = new Set(MOUNTED.map((token) => token.definition.kind));\nconst SCAN_PAGE_SIZE = 256;\n\n/** One observer of a mount and its window: the bounds and the revision it was last given. */\ntype Windowed = {\n\treadonly min: number;\n\treadonly max: number;\n\tvalue: ConversationView;\n\treadonly observer: ViewObserver;\n};\n\n/**\n * One conversation's mount: the documents it shows, shared by every observer, and the observers, each with its own\n * window over the entries.\n */\ntype Mount = {\n\treadonly conversation: ConversationRecord;\n\tdocs: Readonly<Record<string, JsonObject>>;\n\t/** Mounted incarnation and definition version per kind; another incarnation or version is set whole. */\n\treadonly incarnations: Map<string, { id: DocumentId; version: number }>;\n\treadonly observers: Set<Windowed>;\n};\n\nconst VIEWS = new WeakMap<object, ConversationViews>();\n\n/** The view mounts of a Harness, for adapters built on them. */\nexport function conversationViews(harness: object): ConversationViews {\n\tconst views = VIEWS.get(harness);\n\tif (views === undefined) throw new Error(\"Not a Harness\");\n\treturn views;\n}\n\n/** A window with its defaults applied. */\ntype WindowBounds = { readonly from: EntryId | undefined; readonly min: number; readonly max: number };\n\n/** `window` with its defaults; throws a `RangeError` for bounds that are not integers or `max` below `min`. */\nfunction resolveWindow(window: ConversationWindow | undefined): WindowBounds {\n\tconst min = window?.min ?? DEFAULT_WINDOW_MIN;\n\tif (!Number.isSafeInteger(min) || min < 1) throw new RangeError(`Window min must be an integer >= 1, got ${min}`);\n\tconst max = window?.max ?? 2 * min;\n\tif (!Number.isSafeInteger(max) || max < min) {\n\t\tthrow new RangeError(`Window max must be an integer >= min (${min}), got ${max}`);\n\t}\n\tconst from = window?.from;\n\tif (from !== undefined && !Number.isSafeInteger(from)) {\n\t\tthrow new RangeError(`Window from must be an entry ID, got ${from}`);\n\t}\n\treturn { from, min, max };\n}\n\n/**\n * The Harness's conversation view mounts: at most one per conversation, built on the Session line by its first\n * observer and dropped with its last. Each mount advances from the Session's commits as memory adopts them, deferred ones\n * (`CommitPersistence`) before they are stored, and hands each observer the next revision of its own window.\n */\nexport class ConversationViews {\n\treadonly #session: SessionImpl;\n\treadonly #mounts = new Map<ConversationId, Mount>();\n\t#closed = false;\n\n\tconstructor(session: SessionImpl) {\n\t\tthis.#session = session;\n\t\tVIEWS.set(session, this);\n\t\tsession.followCommits((publication, context) => {\n\t\t\tfor (const [id, mount] of this.#mounts)\n\t\t\t\tadvance(id, mount, publication, context, (error) => this.report(error));\n\t\t});\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tconst ends = closeEnds(this.#session.failure);\n\t\t\tfor (const mount of this.#mounts.values())\n\t\t\t\tfor (const windowed of [...mount.observers]) {\n\t\t\t\t\tcontained(\n\t\t\t\t\t\t() => windowed.observer.end(closeEndOf(windowed.observer, ends)),\n\t\t\t\t\t\t(error) => this.report(error),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\tthis.#mounts.clear();\n\t\t});\n\t}\n\n\t/** Report an observer's listener error through the Harness. */\n\treport(error: unknown): void {\n\t\tthis.#session.report(error);\n\t}\n\n\t/**\n\t * Attach a synchronous observer of the view (`Harness.observeConversation()`), behind `guardObserver()`; `context`\n\t * governs only the attachment.\n\t */\n\tasync observe(\n\t\tid: ConversationId,\n\t\tobserver: Observer<ConversationView>,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<Observation<ConversationView>> {\n\t\tlet value!: ConversationView;\n\t\tconst attached = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(current, release) => {\n\t\t\t\tvalue = current;\n\t\t\t\treturn guardObserver(observer, release, (error) => this.report(error));\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tattached.detach();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\treturn observation(value, attached.observer);\n\t}\n\n\t/** A serialized watch of the view, an observer of its mount; aborting `context` ends it `aborted`. */\n\tasync watch(\n\t\tid: ConversationId,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<WatchHandle<ConversationView>> {\n\t\tconst { observer } = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(value, release) => new Watch<ConversationView>(value, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.abort();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeAbort(signal);\n\t\treturn observer;\n\t}\n\n\t/**\n\t * Register an observer created from its window's first revision, atomically on the Session line: it sees every later\n\t * publication and nothing earlier. `release` drops it, and the mount with its last observer.\n\t */\n\tasync attach<O extends ViewObserver>(\n\t\tid: ConversationId,\n\t\twindow: ConversationWindow | undefined,\n\t\tcreate: (value: ConversationView, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void }> {\n\t\tconst bounds = resolveWindow(window);\n\t\treturn this.#session.readOnLine(async (storage) => {\n\t\t\tconst mount = this.#mounts.get(id) ?? (await this.#build(storage, id, context));\n\t\t\tconst { entries, before } = await loadWindow(storage, id, bounds, context);\n\t\t\tconst value = view(mount.conversation, entries, before, mount.docs);\n\t\t\tlet windowed: Windowed | undefined;\n\t\t\tconst detach = (): void => {\n\t\t\t\tif (windowed !== undefined) mount.observers.delete(windowed);\n\t\t\t\tif (mount.observers.size === 0 && this.#mounts.get(id) === mount) this.#mounts.delete(id);\n\t\t\t};\n\t\t\tconst observer = create(value, detach);\n\t\t\t// Close or cancellation may begin while the mount hydrates; register nothing then.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\twindowed = { min: bounds.min, max: bounds.max, value, observer };\n\t\t\tthis.#mounts.set(id, mount);\n\t\t\tmount.observers.add(windowed);\n\t\t\treturn { observer, detach };\n\t\t});\n\t}\n\n\t/** Hydrate a mount on the line, through the line's `storage`. */\n\tasync #build(storage: Storage, id: ConversationId, context: Context): Promise<Mount> {\n\t\tconst conversation = await storage.conversation(id, context);\n\t\tif (conversation === undefined) throw new Error(`Conversation ${id} does not exist`);\n\t\tconst docs: Record<string, JsonObject> = {};\n\t\tconst incarnations = new Map<string, { id: DocumentId; version: number }>();\n\t\tfor (const token of MOUNTED) {\n\t\t\tconst loaded = await this.#session.conversationDocumentOnLine(token, id, context);\n\t\t\tif (loaded === undefined) continue;\n\t\t\tdocs[token.definition.kind] = loaded.value;\n\t\t\tincarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });\n\t\t}\n\t\treturn { conversation, docs, incarnations, observers: new Set() };\n\t}\n}\n\n/** A view revision; `before` is a key only when set. */\nfunction view(\n\tconversation: ConversationRecord,\n\tentries: readonly EntryRecord[],\n\tbefore: EntryId | undefined,\n\tdocs: Readonly<Record<string, JsonObject>>,\n): ConversationView {\n\treturn before === undefined ? { conversation, entries, docs } : { conversation, entries, before, docs };\n}\n\n/**\n * A new observer's window, read on the Session line with bounded scans: the entries from `from` when at most `max` are\n * at or after it, otherwise the newest `min`, and the entry before them.\n */\nasync function loadWindow(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: WindowBounds,\n\tcontext: Context,\n): Promise<{ entries: readonly EntryRecord[]; before: EntryId | undefined }> {\n\tconst { from, min, max } = bounds;\n\tif (from !== undefined) {\n\t\tconst since = await scanUpTo(storage, { conversationId, minEntryId: from, order: \"ascending\" }, max + 1, context);\n\t\tif (since.length <= max) {\n\t\t\tconst query = { conversationId, maxEntryId: idFromNumber<EntryId>(from - 1) };\n\t\t\tconst previous = (await storage.scanEntries(query, 1, undefined, context)).items[0];\n\t\t\treturn { entries: since, before: previous?.id };\n\t\t}\n\t}\n\tconst newest = await scanUpTo(storage, { conversationId }, min + 1, context);\n\tconst before = newest.length > min ? newest.pop()!.id : undefined;\n\treturn { entries: newest.reverse(), before };\n}\n\n/** Up to `limit` entries of `query`, following cursors past short pages. */\nasync function scanUpTo(storage: Storage, query: EntryQuery, limit: number, context: Context): Promise<EntryRecord[]> {\n\tconst entries: EntryRecord[] = [];\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await storage.scanEntries(query, Math.min(SCAN_PAGE_SIZE, limit - entries.length), cursor, context);\n\t\tentries.push(...page.items);\n\t\tcursor = page.next;\n\t} while (cursor !== undefined && entries.length < limit);\n\treturn entries;\n}\n\n/**\n * Derive the mount's operations from one publication and hand each observer the next revision of its window; one that\n * throws is reported through `report`, and the others still get theirs. Documents are applied once and shared; each\n * window takes the appended entries and, past its `max`, drops its oldest down to its `min` in one splice.\n */\nfunction advance(\n\tid: ConversationId,\n\tmount: Mount,\n\tpublication: ObservedCommit,\n\tcontext: Context,\n\treport: (error: unknown) => void,\n): void {\n\tconst docOps: Op[] = [];\n\t// Entry writes are published in ID order.\n\tconst appended: EntryRecord[] = [];\n\tfor (const change of publication.changes) {\n\t\tif (change.type === \"entry\" && change.value.conversationId === id) {\n\t\t\tappended.push(change.value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (change.type !== \"document\" || change.conversationId !== id) continue;\n\t\tconst kind = change.record.kind;\n\t\tif (!MOUNTED_KINDS.has(kind) || change.record.key !== undefined) continue;\n\t\tconst path: NonEmptyPath = [\"docs\", kind];\n\t\tconst mounted = mount.incarnations.get(kind);\n\t\tif (change.kind === \"retire\") {\n\t\t\tif (mounted?.id !== change.record.id) continue;\n\t\t\tmount.incarnations.delete(kind);\n\t\t\tdocOps.push([\"d\", path]);\n\t\t} else if (mounted?.id === change.record.id && mounted.version === change.version) {\n\t\t\tfor (const op of change.ops) docOps.push(prefixed(op, path));\n\t\t} else {\n\t\t\tmount.incarnations.set(kind, { id: change.record.id, version: change.version });\n\t\t\tdocOps.push([\"s\", path, change.value]);\n\t\t}\n\t}\n\tif (docOps.length === 0 && appended.length === 0) return;\n\tif (docOps.length > 0) mount.docs = applyImmutable({ docs: mount.docs }, docOps).docs;\n\tconst frameContext = withoutAbortSignal(context);\n\tconst inserted = appended as unknown as JsonValue[];\n\tfor (const windowed of [...mount.observers]) {\n\t\tconst previous = windowed.value;\n\t\tlet entries = previous.entries;\n\t\tlet before = previous.before;\n\t\tlet ops: Op[] = docOps;\n\t\tif (appended.length > 0) {\n\t\t\tops = [...docOps, [\"p\", [\"entries\"], entries.length, 0, inserted]];\n\t\t\tentries = entries.concat(appended);\n\t\t\tif (entries.length > windowed.max) {\n\t\t\t\tconst drop = entries.length - windowed.min;\n\t\t\t\tbefore = entries[drop - 1]!.id;\n\t\t\t\tentries = entries.slice(drop);\n\t\t\t\tops.push([\"p\", [\"entries\"], 0, drop, []], [\"s\", [\"before\"], before]);\n\t\t\t}\n\t\t}\n\t\twindowed.value = view(mount.conversation, entries, before, mount.docs);\n\t\tconst call: WatchCall<ConversationView> = { kind: \"value\", value: windowed.value, ops, retired: false };\n\t\tcontained(() => windowed.observer.advance(call, frameContext), report);\n\t}\n}\n\n/** `op` moved under `prefix`; a root replacement becomes a set of the prefix. */\nfunction prefixed(op: Op, prefix: NonEmptyPath): Op {\n\tconst at = (path: Path): NonEmptyPath => [...prefix, ...path] as unknown as NonEmptyPath;\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\treturn [\"s\", prefix, op[1]];\n\t\tcase \"p\":\n\t\t\treturn [\"p\", at(op[1]), op[2], op[3], op[4]];\n\t\tcase \"m\":\n\t\t\treturn [\"m\", at(op[1]), op[2]];\n\t\tcase \"s\":\n\t\t\treturn [\"s\", at(op[1]), op[2]];\n\t\tcase \"d\":\n\t\t\treturn [\"d\", at(op[1])];\n\t\tcase \"a\":\n\t\t\treturn [\"a\", at(op[1]), op[2]];\n\t\tcase \"t\":\n\t\t\treturn [\"t\", at(op[1]), op[2]];\n\t}\n}\n"]}
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Id, Seq } from "./types.ts";
|
|
2
|
+
/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */
|
|
3
|
+
export declare function idFromNumber<I extends Id<string>>(value: number): I;
|
|
4
|
+
/** Apply the erased commit-sequence brand at a trusted storage boundary. */
|
|
5
|
+
export declare function seqFromNumber(value: number): Seq;
|
|
6
|
+
//# sourceMappingURL=ids.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAE1C,qFAAqF;AACrF,wBAAgB,YAAY,CAAC,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAEnE;AAED,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAEhD"}
|
package/dist/ids.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */
|
|
2
|
+
export function idFromNumber(value) {
|
|
3
|
+
return value;
|
|
4
|
+
}
|
|
5
|
+
/** Apply the erased commit-sequence brand at a trusted storage boundary. */
|
|
6
|
+
export function seqFromNumber(value) {
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=ids.js.map
|
package/dist/ids.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ids.js","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAEA,qFAAqF;AACrF,MAAM,UAAU,YAAY,CAAuB,KAAa;IAC/D,OAAO,KAAU,CAAC;AACnB,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,aAAa,CAAC,KAAa;IAC1C,OAAO,KAAY,CAAC;AACrB,CAAC","sourcesContent":["import type { Id, Seq } from \"./types.ts\";\n\n/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */\nexport function idFromNumber<I extends Id<string>>(value: number): I {\n\treturn value as I;\n}\n\n/** Apply the erased commit-sequence brand at a trusted storage boundary. */\nexport function seqFromNumber(value: number): Seq {\n\treturn value as Seq;\n}\n"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ImageProcessor } from "../tools/image-processor.ts";
|
|
2
|
+
/** `createPhotonImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. */
|
|
3
|
+
export declare function createCloudflarePhotonImages(): ImageProcessor;
|
|
4
|
+
//# sourceMappingURL=cloudflare.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../../src/images/cloudflare.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAGlE,8FAA8F;AAC9F,wBAAgB,4BAA4B,IAAI,cAAc,CAE7D"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Wrangler's default `CompiledWasm` rule turns this import into a `WebAssembly.Module`; Workers cannot compile
|
|
2
|
+
// WebAssembly from bytes at runtime. Other bundlers do not support it: use `createPhotonImages()` there.
|
|
3
|
+
import photonWasm from "@silvia-odwyer/photon/photon_rs_bg.wasm";
|
|
4
|
+
import { createPhotonImages } from "./index.js";
|
|
5
|
+
/** `createPhotonImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. */
|
|
6
|
+
export function createCloudflarePhotonImages() {
|
|
7
|
+
return createPhotonImages(photonWasm);
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=cloudflare.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare.js","sourceRoot":"","sources":["../../src/images/cloudflare.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAC/G,yGAAyG;AACzG,OAAO,UAAU,MAAM,yCAAyC,CAAC;AAEjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEhD,8FAA8F;AAC9F,MAAM,UAAU,4BAA4B;IAC3C,OAAO,kBAAkB,CAAC,UAAU,CAAC,CAAC;AACvC,CAAC","sourcesContent":["// Wrangler's default `CompiledWasm` rule turns this import into a `WebAssembly.Module`; Workers cannot compile\n// WebAssembly from bytes at runtime. Other bundlers do not support it: use `createPhotonImages()` there.\nimport photonWasm from \"@silvia-odwyer/photon/photon_rs_bg.wasm\";\nimport type { ImageProcessor } from \"../tools/image-processor.ts\";\nimport { createPhotonImages } from \"./index.ts\";\n\n/** `createPhotonImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. */\nexport function createCloudflarePhotonImages(): ImageProcessor {\n\treturn createPhotonImages(photonWasm);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exif.d.ts","sourceRoot":"","sources":["../../src/images/exif.ts"],"names":[],"mappings":"AAEA,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAuBzD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// EXIF orientation of JPEG and WebP files, read from the bytes without decoding the image.
|
|
2
|
+
/** The EXIF orientation of a JPEG or WebP, 1 to 8; 1 when absent or unreadable. */
|
|
3
|
+
export function exifOrientation(bytes) {
|
|
4
|
+
const tiff = tiffStart(bytes);
|
|
5
|
+
if (tiff < 0 || tiff + 8 > bytes.length)
|
|
6
|
+
return 1;
|
|
7
|
+
const little = bytes[tiff] === 0x49 && bytes[tiff + 1] === 0x49;
|
|
8
|
+
const u16 = (at) => little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1];
|
|
9
|
+
const u32 = (at) => little
|
|
10
|
+
? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16) | (bytes[at + 3] << 24)) >>> 0
|
|
11
|
+
: ((bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) >>> 0;
|
|
12
|
+
const directory = tiff + u32(tiff + 4);
|
|
13
|
+
if (directory + 2 > bytes.length)
|
|
14
|
+
return 1;
|
|
15
|
+
const entries = u16(directory);
|
|
16
|
+
for (let index = 0; index < entries; index++) {
|
|
17
|
+
const entry = directory + 2 + index * 12;
|
|
18
|
+
if (entry + 12 > bytes.length)
|
|
19
|
+
return 1;
|
|
20
|
+
// Tag 0x0112 is Orientation, a SHORT whose value sits in the entry.
|
|
21
|
+
if (u16(entry) === 0x0112) {
|
|
22
|
+
const value = u16(entry + 8);
|
|
23
|
+
return value >= 1 && value <= 8 ? value : 1;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
/** Where the TIFF header of a JPEG's APP1 or a WebP's EXIF chunk starts; -1 when there is none. */
|
|
29
|
+
function tiffStart(bytes) {
|
|
30
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
31
|
+
for (let offset = 2; offset + 4 <= bytes.length;) {
|
|
32
|
+
if (bytes[offset] !== 0xff)
|
|
33
|
+
return -1;
|
|
34
|
+
const marker = bytes[offset + 1];
|
|
35
|
+
if (marker === 0xff) {
|
|
36
|
+
offset++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (marker === 0xe1 && isExifHeader(bytes, offset + 4))
|
|
40
|
+
return offset + 10;
|
|
41
|
+
offset += 2 + ((bytes[offset + 2] << 8) | bytes[offset + 3]);
|
|
42
|
+
}
|
|
43
|
+
return -1;
|
|
44
|
+
}
|
|
45
|
+
if (ascii(bytes, 0, "RIFF") && ascii(bytes, 8, "WEBP")) {
|
|
46
|
+
for (let offset = 12; offset + 8 <= bytes.length;) {
|
|
47
|
+
const size = (bytes[offset + 4] |
|
|
48
|
+
(bytes[offset + 5] << 8) |
|
|
49
|
+
(bytes[offset + 6] << 16) |
|
|
50
|
+
(bytes[offset + 7] << 24)) >>>
|
|
51
|
+
0;
|
|
52
|
+
// Some WebP files prefix the TIFF header with "Exif\0\0".
|
|
53
|
+
if (ascii(bytes, offset, "EXIF"))
|
|
54
|
+
return isExifHeader(bytes, offset + 8) ? offset + 14 : offset + 8;
|
|
55
|
+
// RIFF chunks are padded to an even size.
|
|
56
|
+
offset += 8 + size + (size % 2);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return -1;
|
|
60
|
+
}
|
|
61
|
+
function isExifHeader(bytes, offset) {
|
|
62
|
+
return ascii(bytes, offset, "Exif") && bytes[offset + 4] === 0 && bytes[offset + 5] === 0;
|
|
63
|
+
}
|
|
64
|
+
function ascii(bytes, offset, text) {
|
|
65
|
+
for (let index = 0; index < text.length; index++) {
|
|
66
|
+
if (bytes[offset + index] !== text.charCodeAt(index))
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=exif.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exif.js","sourceRoot":"","sources":["../../src/images/exif.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAE3F,mFAAmF;AACnF,MAAM,UAAU,eAAe,CAAC,KAAiB;IAChD,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,KAAK,CAAC,MAAM;QAAE,OAAO,CAAC,CAAC;IAClD,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC;IAChE,MAAM,GAAG,GAAG,CAAC,EAAU,EAAU,EAAE,CAClC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAE,GAAG,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAE,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,GAAG,CAAC,CAAE,C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AC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAE,IAAI,CAAC,CAAC;gBACzB,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAE,IAAI,EAAE,CAAC;gBAC1B,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAE,IAAI,EAAE,CAAC,CAAC;gBAC5B,CAAC,CAAC;YACH,0DAA0D;YAC1D,IAAI,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;gBAAE,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;YACpG,0CAA0C;YAC1C,MAAM,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QACjC,CAAC;IACF,CAAC;IACD,OAAO,CAAC,CAAC,CAAC;AACX,CAAC;AAED,SAAS,YAAY,CAAC,KAAiB,EAAE,MAAc;IACtD,OAAO,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;AAC3F,CAAC;AAED,SAAS,KAAK,CAAC,KAAiB,EAAE,MAAc,EAAE,IAAY;IAC7D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAClD,IAAI,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;IACpE,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["// EXIF orientation of JPEG and WebP files, read from the bytes without decoding the image.\n\n/** The EXIF orientation of a JPEG or WebP, 1 to 8; 1 when absent or unreadable. */\nexport function exifOrientation(bytes: Uint8Array): number {\n\tconst tiff = tiffStart(bytes);\n\tif (tiff < 0 || tiff + 8 > bytes.length) return 1;\n\tconst little = bytes[tiff] === 0x49 && bytes[tiff + 1] === 0x49;\n\tconst u16 = (at: number): number =>\n\t\tlittle ? bytes[at]! | (bytes[at + 1]! << 8) : (bytes[at]! << 8) | bytes[at + 1]!;\n\tconst u32 = (at: number): number =>\n\t\tlittle\n\t\t\t? (bytes[at]! | (bytes[at + 1]! << 8) | (bytes[at + 2]! << 16) | (bytes[at + 3]! << 24)) >>> 0\n\t\t\t: ((bytes[at]! << 24) | (bytes[at + 1]! << 16) | (bytes[at + 2]! << 8) | bytes[at + 3]!) >>> 0;\n\tconst directory = tiff + u32(tiff + 4);\n\tif (directory + 2 > bytes.length) return 1;\n\tconst entries = u16(directory);\n\tfor (let index = 0; index < entries; index++) {\n\t\tconst entry = directory + 2 + index * 12;\n\t\tif (entry + 12 > bytes.length) return 1;\n\t\t// Tag 0x0112 is Orientation, a SHORT whose value sits in the entry.\n\t\tif (u16(entry) === 0x0112) {\n\t\t\tconst value = u16(entry + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\treturn 1;\n}\n\n/** Where the TIFF header of a JPEG's APP1 or a WebP's EXIF chunk starts; -1 when there is none. */\nfunction tiffStart(bytes: Uint8Array): number {\n\tif (bytes[0] === 0xff && bytes[1] === 0xd8) {\n\t\tfor (let offset = 2; offset + 4 <= bytes.length; ) {\n\t\t\tif (bytes[offset] !== 0xff) return -1;\n\t\t\tconst marker = bytes[offset + 1]!;\n\t\t\tif (marker === 0xff) {\n\t\t\t\toffset++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (marker === 0xe1 && isExifHeader(bytes, offset + 4)) return offset + 10;\n\t\t\toffset += 2 + ((bytes[offset + 2]! << 8) | bytes[offset + 3]!);\n\t\t}\n\t\treturn -1;\n\t}\n\tif (ascii(bytes, 0, \"RIFF\") && ascii(bytes, 8, \"WEBP\")) {\n\t\tfor (let offset = 12; offset + 8 <= bytes.length; ) {\n\t\t\tconst size =\n\t\t\t\t(bytes[offset + 4]! |\n\t\t\t\t\t(bytes[offset + 5]! << 8) |\n\t\t\t\t\t(bytes[offset + 6]! << 16) |\n\t\t\t\t\t(bytes[offset + 7]! << 24)) >>>\n\t\t\t\t0;\n\t\t\t// Some WebP files prefix the TIFF header with \"Exif\\0\\0\".\n\t\t\tif (ascii(bytes, offset, \"EXIF\")) return isExifHeader(bytes, offset + 8) ? offset + 14 : offset + 8;\n\t\t\t// RIFF chunks are padded to an even size.\n\t\t\toffset += 8 + size + (size % 2);\n\t\t}\n\t}\n\treturn -1;\n}\n\nfunction isExifHeader(bytes: Uint8Array, offset: number): boolean {\n\treturn ascii(bytes, offset, \"Exif\") && bytes[offset + 4] === 0 && bytes[offset + 5] === 0;\n}\n\nfunction ascii(bytes: Uint8Array, offset: number, text: string): boolean {\n\tfor (let index = 0; index < text.length; index++) {\n\t\tif (bytes[offset + index] !== text.charCodeAt(index)) return false;\n\t}\n\treturn true;\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ImageContent, TextContent } from "@diffra-ai/ai";
|
|
2
|
+
import type { Extension } from "../harness/types.ts";
|
|
3
|
+
import { type ImageLimits, type ImageProcessor } from "../tools/image-processor.ts";
|
|
4
|
+
/** One image fitted by `fitImage`, with notes for the model saying what changed; or why it was left out. */
|
|
5
|
+
export type FittedImage = {
|
|
6
|
+
readonly kind: "fitted";
|
|
7
|
+
readonly image: ImageContent;
|
|
8
|
+
readonly notes: readonly string[];
|
|
9
|
+
} | {
|
|
10
|
+
readonly kind: "omitted";
|
|
11
|
+
readonly note: string;
|
|
12
|
+
};
|
|
13
|
+
/** What `fitImages` did: nothing, or the content with its images fitted and notes for the model. */
|
|
14
|
+
export type FittedImages = {
|
|
15
|
+
readonly kind: "unchanged";
|
|
16
|
+
} | {
|
|
17
|
+
readonly kind: "fitted";
|
|
18
|
+
readonly content: (TextContent | ImageContent)[];
|
|
19
|
+
readonly notes: readonly string[];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The image in `bytes`, declared as `mimeType`, prepared by `processor` to fit `limits`. Every image is decoded, as the
|
|
23
|
+
* coding agent's are: one the provider would reject (damaged, or too large) never reaches the transcript, where it would
|
|
24
|
+
* fail every later request. Its type is read from its bytes, since providers reject a declared type that differs. An
|
|
25
|
+
* image the processor cannot prepare, or fails on, is left out with a note.
|
|
26
|
+
*/
|
|
27
|
+
export declare function fitImage(bytes: Uint8Array, mimeType: string, limits: ImageLimits, processor: ImageProcessor): Promise<FittedImage>;
|
|
28
|
+
/**
|
|
29
|
+
* `content` with each image fitted by `fitImage` (malformed base64 is left out as an image that cannot be prepared);
|
|
30
|
+
* text stays where it is. `unchanged` when every image came back as it was.
|
|
31
|
+
*/
|
|
32
|
+
export declare function fitImages(content: readonly (TextContent | ImageContent)[], limits: ImageLimits, processor: ImageProcessor): Promise<FittedImages>;
|
|
33
|
+
/**
|
|
34
|
+
* The `fit-images` extension: an `afterTool` hook that fits the images of every result the model gets to the
|
|
35
|
+
* conversation model's current limits (`fitImages`) before it is committed, whichever tool made them (an MCP tool, code
|
|
36
|
+
* mode's `image()`), and says what changed in an `info` diagnostic (code `image`). Hooks of extensions installed before
|
|
37
|
+
* it see the images unfitted. Nested calls' results are left as they are: the program that made the call gets them, not
|
|
38
|
+
* the model.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createFitImagesExtension(processor: ImageProcessor): Extension;
|
|
41
|
+
//# sourceMappingURL=fit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fit.d.ts","sourceRoot":"","sources":["../../src/images/fit.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAM/D,OAAO,KAAK,EAAE,SAAS,EAA8C,MAAM,qBAAqB,CAAC;AAEjG,OAAO,EAEN,KAAK,WAAW,EAChB,KAAK,cAAc,EAInB,MAAM,6BAA6B,CAAC;AAErC,4GAA4G;AAC5G,MAAM,MAAM,WAAW,GACpB;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAC5F;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvD,oGAAoG;AACpG,MAAM,MAAM,YAAY,GACrB;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GAC9B;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAEpH;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC7B,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,EACnB,SAAS,EAAE,cAAc,GACvB,OAAO,CAAC,WAAW,CAAC,CAYtB;AASD;;;GAGG;AACH,wBAAsB,SAAS,CAC9B,OAAO,EAAE,SAAS,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,MAAM,EAAE,WAAW,EACnB,SAAS,EAAE,cAAc,GACvB,OAAO,CAAC,YAAY,CAAC,CAsBvB;AAaD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,cAAc,GAAG,SAAS,CAS7E"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// `@diffra-ai/durable/images/fit`: images entering a conversation, fitted to its model's limits by any
|
|
2
|
+
// `ImageProcessor` before they are stored, so the transcript (and the provider's prompt cache) never changes later: a
|
|
3
|
+
// host's input before it is submitted (`fitImage`, `fitImages`), and the results of the model's tool calls
|
|
4
|
+
// (`createFitImagesExtension`). Photon is not loaded from here; pass a processor.
|
|
5
|
+
import { errorMessage } from "../errors.js";
|
|
6
|
+
import { AgentDoc } from "../harness/agent.js";
|
|
7
|
+
import { defineExtension, hook } from "../harness/define.js";
|
|
8
|
+
import { ToolTask } from "../harness/tool.js";
|
|
9
|
+
import { detectSupportedImageMimeType } from "../tools/image.js";
|
|
10
|
+
import { fromBase64, imageLimits, preparedNotes, } from "../tools/image-processor.js";
|
|
11
|
+
/**
|
|
12
|
+
* The image in `bytes`, declared as `mimeType`, prepared by `processor` to fit `limits`. Every image is decoded, as the
|
|
13
|
+
* coding agent's are: one the provider would reject (damaged, or too large) never reaches the transcript, where it would
|
|
14
|
+
* fail every later request. Its type is read from its bytes, since providers reject a declared type that differs. An
|
|
15
|
+
* image the processor cannot prepare, or fails on, is left out with a note.
|
|
16
|
+
*/
|
|
17
|
+
export async function fitImage(bytes, mimeType, limits, processor) {
|
|
18
|
+
let prepared;
|
|
19
|
+
try {
|
|
20
|
+
prepared = await processor.prepare(bytes, detectSupportedImageMimeType(bytes) ?? mimeType, limits);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
// The image is known to need preparing: keeping it would commit what the provider rejects. The note carries the
|
|
24
|
+
// failure into the transcript.
|
|
25
|
+
return omitted(mimeType, `: ${errorMessage(error)}`);
|
|
26
|
+
}
|
|
27
|
+
if (prepared === undefined)
|
|
28
|
+
return omitted(mimeType, "");
|
|
29
|
+
const image = { type: "image", data: prepared.data, mimeType: prepared.mimeType };
|
|
30
|
+
return { kind: "fitted", image, notes: preparedNotes(prepared) };
|
|
31
|
+
}
|
|
32
|
+
function omitted(mimeType, reason) {
|
|
33
|
+
return {
|
|
34
|
+
kind: "omitted",
|
|
35
|
+
note: `An image (${mimeType}) cannot be prepared for the model and was left out${reason}.`,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* `content` with each image fitted by `fitImage` (malformed base64 is left out as an image that cannot be prepared);
|
|
40
|
+
* text stays where it is. `unchanged` when every image came back as it was.
|
|
41
|
+
*/
|
|
42
|
+
export async function fitImages(content, limits, processor) {
|
|
43
|
+
const fitted = [];
|
|
44
|
+
const notes = [];
|
|
45
|
+
let changed = false;
|
|
46
|
+
for (const item of content) {
|
|
47
|
+
if (item.type !== "image") {
|
|
48
|
+
fitted.push(item);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const result = await fitBase64(item, limits, processor);
|
|
52
|
+
if (result.kind === "omitted") {
|
|
53
|
+
changed = true;
|
|
54
|
+
notes.push(result.note);
|
|
55
|
+
}
|
|
56
|
+
else if (result.image.data === item.data && result.image.mimeType === item.mimeType) {
|
|
57
|
+
fitted.push(item);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
changed = true;
|
|
61
|
+
fitted.push(result.image);
|
|
62
|
+
notes.push(...result.notes);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return changed ? { kind: "fitted", content: fitted, notes } : { kind: "unchanged" };
|
|
66
|
+
}
|
|
67
|
+
async function fitBase64(image, limits, processor) {
|
|
68
|
+
let bytes;
|
|
69
|
+
try {
|
|
70
|
+
bytes = fromBase64(image.data);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// Wire input: a tool's base64 may be malformed.
|
|
74
|
+
return omitted(image.mimeType, `: ${errorMessage(error)}`);
|
|
75
|
+
}
|
|
76
|
+
return fitImage(bytes, image.mimeType, limits, processor);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The `fit-images` extension: an `afterTool` hook that fits the images of every result the model gets to the
|
|
80
|
+
* conversation model's current limits (`fitImages`) before it is committed, whichever tool made them (an MCP tool, code
|
|
81
|
+
* mode's `image()`), and says what changed in an `info` diagnostic (code `image`). Hooks of extensions installed before
|
|
82
|
+
* it see the images unfitted. Nested calls' results are left as they are: the program that made the call gets them, not
|
|
83
|
+
* the model.
|
|
84
|
+
*/
|
|
85
|
+
export function createFitImagesExtension(processor) {
|
|
86
|
+
return defineExtension({
|
|
87
|
+
name: "fit-images",
|
|
88
|
+
hooks: [
|
|
89
|
+
hook(ToolTask, {
|
|
90
|
+
afterTool: (call, result, api, context) => fitResult(call, result, processor, api, context),
|
|
91
|
+
}),
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async function fitResult(call, result, processor, api, context) {
|
|
96
|
+
if (call.parent !== undefined || !result.output?.some((item) => item.type === "image"))
|
|
97
|
+
return undefined;
|
|
98
|
+
const ref = (await api.snapshot(AgentDoc, api.conversationId, context))?.model;
|
|
99
|
+
const model = ref === undefined ? undefined : api.models.getModel(ref.provider, ref.modelId);
|
|
100
|
+
const fitted = await fitImages(result.output, imageLimits(model), processor);
|
|
101
|
+
if (fitted.kind === "unchanged")
|
|
102
|
+
return undefined;
|
|
103
|
+
if (fitted.notes.length === 0)
|
|
104
|
+
return { ...result, output: fitted.content };
|
|
105
|
+
const note = { severity: "info", code: "image", message: fitted.notes.join(" ") };
|
|
106
|
+
return { ...result, output: fitted.content, diagnostics: [...(result.diagnostics ?? []), note] };
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=fit.js.map
|