@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,163 @@
|
|
|
1
|
+
// What a streamed answer changed in its partial message between two partial commits, so a commit costs the new text.
|
|
2
|
+
import { StreamingJsonParser } from "@diffra-ai/ai/utils/streaming-json";
|
|
3
|
+
import { appendText } from "@diffra-ai/chord/delta";
|
|
4
|
+
import { assignJson } from "./json.js";
|
|
5
|
+
/**
|
|
6
|
+
* Collects, from a response's events, what changed in its partial message since the last commit, so the commit appends
|
|
7
|
+
* new text instead of reassigning growing strings. Reassigning makes Chord compare the old and new string, which costs
|
|
8
|
+
* O(length) per commit.
|
|
9
|
+
*
|
|
10
|
+
* - Text and thinking: the `text_delta` and `thinking_delta` events. The commit appends them where the committed string
|
|
11
|
+
* plus the deltas has the new string's length, and compares otherwise. A block's `*_end` event drops them, because
|
|
12
|
+
* providers may replace the text when a block ends.
|
|
13
|
+
* - Tool-call arguments: a `StreamingJsonParser` per call, fed with the raw argument text of each `toolcall_delta`,
|
|
14
|
+
* reports what each piece changed. The commit applies those changes to the committed arguments in order and leaves
|
|
15
|
+
* the arguments out of the message assignment, so the committed arguments are exactly the parsed text so far.
|
|
16
|
+
* `toolcall_end` ends the tracking; the call's last commit assigns its final arguments.
|
|
17
|
+
*/
|
|
18
|
+
export class PartialChanges {
|
|
19
|
+
#text = new Map();
|
|
20
|
+
#toolCalls = new Map();
|
|
21
|
+
/** Record what `event` changed. */
|
|
22
|
+
observe(event) {
|
|
23
|
+
switch (event.type) {
|
|
24
|
+
case "text_delta":
|
|
25
|
+
case "thinking_delta": {
|
|
26
|
+
const field = event.type === "text_delta" ? "text" : "thinking";
|
|
27
|
+
const pending = this.#text.get(event.contentIndex);
|
|
28
|
+
if (pending?.field === field)
|
|
29
|
+
pending.text += event.delta;
|
|
30
|
+
else
|
|
31
|
+
this.#text.set(event.contentIndex, { field, text: event.delta });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
case "toolcall_start":
|
|
35
|
+
this.#toolCalls.set(event.contentIndex, {
|
|
36
|
+
parser: new StreamingJsonParser(),
|
|
37
|
+
changes: [],
|
|
38
|
+
committed: false,
|
|
39
|
+
});
|
|
40
|
+
return;
|
|
41
|
+
case "toolcall_delta": {
|
|
42
|
+
const call = this.#toolCalls.get(event.contentIndex);
|
|
43
|
+
if (call === undefined)
|
|
44
|
+
return;
|
|
45
|
+
for (const change of call.parser.append(event.delta)) {
|
|
46
|
+
// Arguments are an object: any other root shows as no arguments, so the snapshot is committed instead.
|
|
47
|
+
if (change.path.length === 0 && !isRecord(change.kind === "set" ? value(change) : null)) {
|
|
48
|
+
this.#toolCalls.delete(event.contentIndex);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
call.changes.push(change);
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
case "text_end":
|
|
56
|
+
case "thinking_end":
|
|
57
|
+
this.#text.delete(event.contentIndex);
|
|
58
|
+
return;
|
|
59
|
+
case "toolcall_end":
|
|
60
|
+
this.#toolCalls.delete(event.contentIndex);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Take what changed since the last call, for a commit of `message`, a copy of the partial. Clears the arguments of
|
|
66
|
+
* tracked tool calls in `message`: the commit writes them from the changes. Call `restore()` if the commit fails.
|
|
67
|
+
*/
|
|
68
|
+
take(message) {
|
|
69
|
+
const blocks = new Map();
|
|
70
|
+
for (const [index, { field, text }] of this.#text) {
|
|
71
|
+
blocks.set(index, { kind: "fields", fields: new Map([[field, { kind: "append", text }]]) });
|
|
72
|
+
}
|
|
73
|
+
this.#text = new Map();
|
|
74
|
+
const toolCalls = new Map();
|
|
75
|
+
for (const [index, call] of this.#toolCalls) {
|
|
76
|
+
const block = message.content[index];
|
|
77
|
+
// A tracked call is the tool call its `toolcall_start` named; the narrowing only tells TypeScript.
|
|
78
|
+
if (block?.type !== "toolCall")
|
|
79
|
+
continue;
|
|
80
|
+
toolCalls.set(index, { changes: call.changes, snapshot: block.arguments });
|
|
81
|
+
block.arguments = {};
|
|
82
|
+
blocks.set(index, { kind: "fields", fields: new Map([["arguments", { kind: "keep" }]]) });
|
|
83
|
+
call.changes = [];
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
plan: { kind: "fields", fields: new Map([["content", { kind: "fields", fields: blocks }]]) },
|
|
87
|
+
toolCalls,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Write `message` with what `commit` took into `generation.message`: the message leaf by leaf with the plan, then the
|
|
92
|
+
* argument changes. A tracked call whose block is new here gets its arguments from its changes, which then start at
|
|
93
|
+
* its first piece; when the committed message lost a call whose changes were already committed (another writer reset
|
|
94
|
+
* it), the call falls back to its snapshot from now on.
|
|
95
|
+
*/
|
|
96
|
+
commit(generation, message, commit) {
|
|
97
|
+
const committedBlocks = generation.message?.content.length ?? 0;
|
|
98
|
+
const apply = [];
|
|
99
|
+
for (const [index, { changes, snapshot }] of commit.toolCalls) {
|
|
100
|
+
const call = this.#toolCalls.get(index);
|
|
101
|
+
if (call === undefined)
|
|
102
|
+
continue;
|
|
103
|
+
const block = message.content[index];
|
|
104
|
+
if (index >= committedBlocks && call.committed && block?.type === "toolCall") {
|
|
105
|
+
// The earlier changes are not in the committed message: commit the snapshot and stop tracking the call.
|
|
106
|
+
this.#toolCalls.delete(index);
|
|
107
|
+
block.arguments = snapshot;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
call.committed = true;
|
|
111
|
+
apply.push([index, changes]);
|
|
112
|
+
}
|
|
113
|
+
assignJson(generation, "message", message, commit.plan);
|
|
114
|
+
const content = generation.message?.content ?? [];
|
|
115
|
+
for (const [index, changes] of apply) {
|
|
116
|
+
const block = content[index];
|
|
117
|
+
if (block?.type !== "toolCall")
|
|
118
|
+
continue;
|
|
119
|
+
for (const change of changes)
|
|
120
|
+
applyChange(block, change);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** Put back what a failed commit took, so the next commit applies it first. */
|
|
124
|
+
restore(commit) {
|
|
125
|
+
for (const [index, { changes }] of commit.toolCalls) {
|
|
126
|
+
const call = this.#toolCalls.get(index);
|
|
127
|
+
if (call !== undefined)
|
|
128
|
+
call.changes = [...changes, ...call.changes];
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Apply one argument change to the committed arguments of `block`. */
|
|
133
|
+
function applyChange(block, change) {
|
|
134
|
+
const key = change.path.at(-1);
|
|
135
|
+
if (key === undefined) {
|
|
136
|
+
// Only an object root is tracked (`observe()` drops any other), and only `set` starts it.
|
|
137
|
+
const root = change.kind === "set" ? value(change) : undefined;
|
|
138
|
+
if (isRecord(root))
|
|
139
|
+
block.arguments = root;
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// The path follows the parsed argument text, not a type: each segment names a container `observe()` saw set.
|
|
143
|
+
let parent = block.arguments;
|
|
144
|
+
for (const segment of change.path.slice(0, -1)) {
|
|
145
|
+
parent = parent[segment];
|
|
146
|
+
}
|
|
147
|
+
const slots = parent;
|
|
148
|
+
if (change.kind === "set")
|
|
149
|
+
slots[key] = value(change);
|
|
150
|
+
// appendText() takes object members; a string in an array is reassigned, which compares it whole.
|
|
151
|
+
else if (Array.isArray(parent))
|
|
152
|
+
slots[key] = `${slots[key]}${change.text}`;
|
|
153
|
+
else
|
|
154
|
+
appendText(parent, String(key), change.text);
|
|
155
|
+
}
|
|
156
|
+
/** The value a `set` change reports: JSON data, which diffra-ai types with read-only arrays. */
|
|
157
|
+
function value(change) {
|
|
158
|
+
return change.value;
|
|
159
|
+
}
|
|
160
|
+
function isRecord(value) {
|
|
161
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=partial-changes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"partial-changes.js","sourceRoot":"","sources":["../../src/harness/partial-changes.ts"],"names":[],"mappings":"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MAAM,CAAC,IAAI,CAAC,CAAC;AACpF,CAAC;AAED,gGAAgG;AAChG,SAAS,KAAK,CAAC,MAA4C;IAC1D,OAAO,MAAM,CAAC,KAAkB,CAAC;AAClC,CAAC;AAED,SAAS,QAAQ,CAAC,KAA4B;IAC7C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["// What a streamed answer changed in its partial message between two partial commits, so a commit costs the new text.\n\nimport type { AssistantMessage, AssistantMessageEvent, ToolCall } from \"@diffra-ai/ai\";\nimport { type JsonChange, StreamingJsonParser } from \"@diffra-ai/ai/utils/streaming-json\";\nimport { appendText, type Draft } from \"@diffra-ai/chord/delta\";\nimport type { JsonRepresentation, JsonValue } from \"@diffra-ai/chord/json\";\nimport { type AssignPlan, assignJson } from \"./json.ts\";\nimport type { LiveState } from \"./live.ts\";\n\ntype JsonContainer = Record<string, JsonValue> | JsonValue[];\n\n/** A partial message as `diffra.live.generation.message` holds it. */\nexport type PartialMessage = JsonRepresentation<AssistantMessage>;\n\n/** Committed arguments of a streamed tool call. */\ntype Arguments = JsonRepresentation<ToolCall>[\"arguments\"];\n\n/** What one partial commit writes besides the partial message itself; from `PartialChanges.take()`. */\nexport type PartialCommit = {\n\t/** The plan `assignJson()` writes the message with: text appends, and the arguments it leaves to `changes`. */\n\treadonly plan: AssignPlan;\n\t/** Each tracked tool call by content index: its argument changes since the last commit, in order, and its snapshot. */\n\treadonly toolCalls: ReadonlyMap<number, { readonly changes: readonly JsonChange[]; readonly snapshot: Arguments }>;\n};\n\n/** What a tracked tool call changed since the last commit, and whether any commit took its changes yet. */\ntype ToolCallState = { readonly parser: StreamingJsonParser; changes: JsonChange[]; committed: boolean };\n\n/**\n * Collects, from a response's events, what changed in its partial message since the last commit, so the commit appends\n * new text instead of reassigning growing strings. Reassigning makes Chord compare the old and new string, which costs\n * O(length) per commit.\n *\n * - Text and thinking: the `text_delta` and `thinking_delta` events. The commit appends them where the committed string\n * plus the deltas has the new string's length, and compares otherwise. A block's `*_end` event drops them, because\n * providers may replace the text when a block ends.\n * - Tool-call arguments: a `StreamingJsonParser` per call, fed with the raw argument text of each `toolcall_delta`,\n * reports what each piece changed. The commit applies those changes to the committed arguments in order and leaves\n * the arguments out of the message assignment, so the committed arguments are exactly the parsed text so far.\n * `toolcall_end` ends the tracking; the call's last commit assigns its final arguments.\n */\nexport class PartialChanges {\n\t#text = new Map<number, { readonly field: \"text\" | \"thinking\"; text: string }>();\n\treadonly #toolCalls = new Map<number, ToolCallState>();\n\n\t/** Record what `event` changed. */\n\tobserve(event: AssistantMessageEvent): void {\n\t\tswitch (event.type) {\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"thinking_delta\": {\n\t\t\t\tconst field = event.type === \"text_delta\" ? \"text\" : \"thinking\";\n\t\t\t\tconst pending = this.#text.get(event.contentIndex);\n\t\t\t\tif (pending?.field === field) pending.text += event.delta;\n\t\t\t\telse this.#text.set(event.contentIndex, { field, text: event.delta });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"toolcall_start\":\n\t\t\t\tthis.#toolCalls.set(event.contentIndex, {\n\t\t\t\t\tparser: new StreamingJsonParser(),\n\t\t\t\t\tchanges: [],\n\t\t\t\t\tcommitted: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\tcase \"toolcall_delta\": {\n\t\t\t\tconst call = this.#toolCalls.get(event.contentIndex);\n\t\t\t\tif (call === undefined) return;\n\t\t\t\tfor (const change of call.parser.append(event.delta)) {\n\t\t\t\t\t// Arguments are an object: any other root shows as no arguments, so the snapshot is committed instead.\n\t\t\t\t\tif (change.path.length === 0 && !isRecord(change.kind === \"set\" ? value(change) : null)) {\n\t\t\t\t\t\tthis.#toolCalls.delete(event.contentIndex);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcall.changes.push(change);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_end\":\n\t\t\t\tthis.#text.delete(event.contentIndex);\n\t\t\t\treturn;\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tthis.#toolCalls.delete(event.contentIndex);\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\t/**\n\t * Take what changed since the last call, for a commit of `message`, a copy of the partial. Clears the arguments of\n\t * tracked tool calls in `message`: the commit writes them from the changes. Call `restore()` if the commit fails.\n\t */\n\ttake(message: PartialMessage): PartialCommit {\n\t\tconst blocks = new Map<string | number, AssignPlan>();\n\t\tfor (const [index, { field, text }] of this.#text) {\n\t\t\tblocks.set(index, { kind: \"fields\", fields: new Map([[field, { kind: \"append\", text }]]) });\n\t\t}\n\t\tthis.#text = new Map();\n\t\tconst toolCalls = new Map<number, { readonly changes: readonly JsonChange[]; readonly snapshot: Arguments }>();\n\t\tfor (const [index, call] of this.#toolCalls) {\n\t\t\tconst block = message.content[index];\n\t\t\t// A tracked call is the tool call its `toolcall_start` named; the narrowing only tells TypeScript.\n\t\t\tif (block?.type !== \"toolCall\") continue;\n\t\t\ttoolCalls.set(index, { changes: call.changes, snapshot: block.arguments });\n\t\t\tblock.arguments = {};\n\t\t\tblocks.set(index, { kind: \"fields\", fields: new Map([[\"arguments\", { kind: \"keep\" }]]) });\n\t\t\tcall.changes = [];\n\t\t}\n\t\treturn {\n\t\t\tplan: { kind: \"fields\", fields: new Map([[\"content\", { kind: \"fields\", fields: blocks }]]) },\n\t\t\ttoolCalls,\n\t\t};\n\t}\n\n\t/**\n\t * Write `message` with what `commit` took into `generation.message`: the message leaf by leaf with the plan, then the\n\t * argument changes. A tracked call whose block is new here gets its arguments from its changes, which then start at\n\t * its first piece; when the committed message lost a call whose changes were already committed (another writer reset\n\t * it), the call falls back to its snapshot from now on.\n\t */\n\tcommit(\n\t\tgeneration: Draft<NonNullable<LiveState[\"generation\"]>>,\n\t\tmessage: PartialMessage,\n\t\tcommit: PartialCommit,\n\t): void {\n\t\tconst committedBlocks = generation.message?.content.length ?? 0;\n\t\tconst apply: [number, readonly JsonChange[]][] = [];\n\t\tfor (const [index, { changes, snapshot }] of commit.toolCalls) {\n\t\t\tconst call = this.#toolCalls.get(index);\n\t\t\tif (call === undefined) continue;\n\t\t\tconst block = message.content[index];\n\t\t\tif (index >= committedBlocks && call.committed && block?.type === \"toolCall\") {\n\t\t\t\t// The earlier changes are not in the committed message: commit the snapshot and stop tracking the call.\n\t\t\t\tthis.#toolCalls.delete(index);\n\t\t\t\tblock.arguments = snapshot;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcall.committed = true;\n\t\t\tapply.push([index, changes]);\n\t\t}\n\t\tassignJson(generation, \"message\", message, commit.plan);\n\t\tconst content = generation.message?.content ?? [];\n\t\tfor (const [index, changes] of apply) {\n\t\t\tconst block = content[index];\n\t\t\tif (block?.type !== \"toolCall\") continue;\n\t\t\tfor (const change of changes) applyChange(block, change);\n\t\t}\n\t}\n\n\t/** Put back what a failed commit took, so the next commit applies it first. */\n\trestore(commit: PartialCommit): void {\n\t\tfor (const [index, { changes }] of commit.toolCalls) {\n\t\t\tconst call = this.#toolCalls.get(index);\n\t\t\tif (call !== undefined) call.changes = [...changes, ...call.changes];\n\t\t}\n\t}\n}\n\n/** Apply one argument change to the committed arguments of `block`. */\nfunction applyChange(block: Draft<JsonRepresentation<ToolCall>>, change: JsonChange): void {\n\tconst key = change.path.at(-1);\n\tif (key === undefined) {\n\t\t// Only an object root is tracked (`observe()` drops any other), and only `set` starts it.\n\t\tconst root = change.kind === \"set\" ? value(change) : undefined;\n\t\tif (isRecord(root)) block.arguments = root;\n\t\treturn;\n\t}\n\t// The path follows the parsed argument text, not a type: each segment names a container `observe()` saw set.\n\tlet parent = block.arguments as Draft<JsonContainer>;\n\tfor (const segment of change.path.slice(0, -1)) {\n\t\tparent = (parent as Record<string | number, Draft<JsonContainer>>)[segment]!;\n\t}\n\tconst slots = parent as Record<string | number, JsonValue>;\n\tif (change.kind === \"set\") slots[key] = value(change);\n\t// appendText() takes object members; a string in an array is reassigned, which compares it whole.\n\telse if (Array.isArray(parent)) slots[key] = `${slots[key] as string}${change.text}`;\n\telse appendText(parent as Draft<Record<string, string>>, String(key), change.text);\n}\n\n/** The value a `set` change reports: JSON data, which diffra-ai types with read-only arrays. */\nfunction value(change: Extract<JsonChange, { kind: \"set\" }>): JsonValue {\n\treturn change.value as JsonValue;\n}\n\nfunction isRecord(value: JsonValue | undefined): value is Record<string, JsonValue> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Message, Tool } from "@diffra-ai/ai";
|
|
2
|
+
import type { Context } from "@diffra-ai/chord/context";
|
|
3
|
+
import type { TypedEntryDraft } from "../types.ts";
|
|
4
|
+
import type { ContextView, PromptInput, PromptSection, ToolRegistration } from "./types.ts";
|
|
5
|
+
/** Sections in effect after replaying system messages in order: set in place, `null` deletes, re-adding appends. */
|
|
6
|
+
export declare function replaySections(messages: readonly Message[]): Map<string, string>;
|
|
7
|
+
/**
|
|
8
|
+
* Render the agent's sections in order. `undefined` omits a section; tagged text is wrapped as `<key>\n...\n</key>`. A
|
|
9
|
+
* section that throws keeps its shown text, if any, and is reported; errors after `context` is aborted propagate.
|
|
10
|
+
*/
|
|
11
|
+
export declare function renderSections<Tool extends ToolRegistration>(sections: readonly PromptSection<Tool>[], input: PromptInput<Tool>, shown: ReadonlyMap<string, string>, report: (error: unknown, section: PromptSection<Tool>) => void, context: Context): Promise<Map<string, string>>;
|
|
12
|
+
type SystemDraft = TypedEntryDraft<never>;
|
|
13
|
+
/**
|
|
14
|
+
* Plan the `diffra.system` entries that make the replayed sections and tools of `view` equal `desired` and `tools` in values
|
|
15
|
+
* and order.
|
|
16
|
+
*
|
|
17
|
+
* - A head marker with no later `diffra.system` entry in context: one complete baseline that omits every retained earlier
|
|
18
|
+
* `diffra.system` entry, written even when it restates the replayed values.
|
|
19
|
+
* - Otherwise, when a minimal section patch would leave a different order: remove every shown section, then re-add
|
|
20
|
+
* every desired section in order.
|
|
21
|
+
* - Otherwise the minimal patch of changed values and `null` removals, or nothing.
|
|
22
|
+
*
|
|
23
|
+
* Tool changes ride on the last planned entry, or on one entry of their own.
|
|
24
|
+
*/
|
|
25
|
+
export declare function planSystemEntries(view: ContextView, desired: ReadonlyMap<string, string>, tools: readonly Tool[], timestamp: number): SystemDraft[];
|
|
26
|
+
export {};
|
|
27
|
+
//# sourceMappingURL=prompt.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/harness/prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAiB,IAAI,EAAiB,MAAM,eAAe,CAAC;AAEjF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE5F,oHAAoH;AACpH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAUhF;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,IAAI,SAAS,gBAAgB,EACjE,QAAQ,EAAE,SAAS,aAAa,CAAC,IAAI,CAAC,EAAE,EACxC,KAAK,EAAE,WAAW,CAAC,IAAI,CAAC,EACxB,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EAClC,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,EAC9D,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAiB9B;AAED,KAAK,WAAW,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;AAI1C;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAChC,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACpC,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,SAAS,EAAE,MAAM,GACf,WAAW,EAAE,CAsBf"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { declarationsEqual, getCurrentTools, toToolDeclaration } from "@diffra-ai/ai/utils/transcript";
|
|
2
|
+
import { SystemEntry } from "../entries.js";
|
|
3
|
+
/** Sections in effect after replaying system messages in order: set in place, `null` deletes, re-adding appends. */
|
|
4
|
+
export function replaySections(messages) {
|
|
5
|
+
const shown = new Map();
|
|
6
|
+
for (const message of messages) {
|
|
7
|
+
if (message.role !== "system" || message.sections === undefined)
|
|
8
|
+
continue;
|
|
9
|
+
for (const [key, value] of Object.entries(message.sections)) {
|
|
10
|
+
if (value === null)
|
|
11
|
+
shown.delete(key);
|
|
12
|
+
else
|
|
13
|
+
shown.set(key, value);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return shown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Render the agent's sections in order. `undefined` omits a section; tagged text is wrapped as `<key>\n...\n</key>`. A
|
|
20
|
+
* section that throws keeps its shown text, if any, and is reported; errors after `context` is aborted propagate.
|
|
21
|
+
*/
|
|
22
|
+
export async function renderSections(sections, input, shown, report, context) {
|
|
23
|
+
const desired = new Map();
|
|
24
|
+
for (const section of sections) {
|
|
25
|
+
let text;
|
|
26
|
+
try {
|
|
27
|
+
text = await section.render(input, context);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (context.abortSignal?.aborted)
|
|
31
|
+
throw error;
|
|
32
|
+
report(error, section);
|
|
33
|
+
const kept = shown.get(section.key);
|
|
34
|
+
if (kept !== undefined)
|
|
35
|
+
desired.set(section.key, kept);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (text === undefined)
|
|
39
|
+
continue;
|
|
40
|
+
desired.set(section.key, section.tag === false ? text : `<${section.key}>\n${text}\n</${section.key}>`);
|
|
41
|
+
}
|
|
42
|
+
return desired;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Plan the `diffra.system` entries that make the replayed sections and tools of `view` equal `desired` and `tools` in values
|
|
46
|
+
* and order.
|
|
47
|
+
*
|
|
48
|
+
* - A head marker with no later `diffra.system` entry in context: one complete baseline that omits every retained earlier
|
|
49
|
+
* `diffra.system` entry, written even when it restates the replayed values.
|
|
50
|
+
* - Otherwise, when a minimal section patch would leave a different order: remove every shown section, then re-add
|
|
51
|
+
* every desired section in order.
|
|
52
|
+
* - Otherwise the minimal patch of changed values and `null` removals, or nothing.
|
|
53
|
+
*
|
|
54
|
+
* Tool changes ride on the last planned entry, or on one entry of their own.
|
|
55
|
+
*/
|
|
56
|
+
export function planSystemEntries(view, desired, tools, timestamp) {
|
|
57
|
+
const head = view.head;
|
|
58
|
+
if (head !== undefined && !view.entries.some((entry) => SystemEntry.is(entry) && entry.id > head.id)) {
|
|
59
|
+
const edits = view.entries
|
|
60
|
+
.filter((entry) => SystemEntry.is(entry))
|
|
61
|
+
.map((entry) => ({ target: entry.id, action: "omit" }));
|
|
62
|
+
const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp);
|
|
63
|
+
return [edits.length === 0 ? baseline : { ...baseline, edits }];
|
|
64
|
+
}
|
|
65
|
+
const sections = planSections(replaySections(view.messages), desired);
|
|
66
|
+
const changes = planTools(getCurrentTools(view.messages), tools);
|
|
67
|
+
if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) {
|
|
68
|
+
return sections.map((patch) => systemEntry(patch, undefined, timestamp));
|
|
69
|
+
}
|
|
70
|
+
if (sections.length === 0)
|
|
71
|
+
return [systemEntry(undefined, changes, timestamp)];
|
|
72
|
+
return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : undefined, timestamp));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Tool changes from `offered` to `desired`. A changed declaration is removed and re-added. Replay keeps retained tools
|
|
76
|
+
* in place and appends additions; when that would not yield the desired order, every offered tool is removed and
|
|
77
|
+
* every desired tool re-added in order.
|
|
78
|
+
*/
|
|
79
|
+
function planTools(offered, desired) {
|
|
80
|
+
const wanted = new Map(desired.map((tool) => [tool.name, tool]));
|
|
81
|
+
const kept = offered.filter((tool) => {
|
|
82
|
+
const next = wanted.get(tool.name);
|
|
83
|
+
return next !== undefined && declarationsEqual(tool, next);
|
|
84
|
+
});
|
|
85
|
+
const keptNames = new Set(kept.map((tool) => tool.name));
|
|
86
|
+
const added = desired.filter((tool) => !keptNames.has(tool.name));
|
|
87
|
+
const replayed = [...kept, ...added];
|
|
88
|
+
if (replayed.some((tool, index) => tool.name !== desired[index].name)) {
|
|
89
|
+
return {
|
|
90
|
+
toolsRemoved: offered.map((tool) => ({ name: tool.name })),
|
|
91
|
+
toolsAdded: desired.map(toToolDeclaration),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
toolsRemoved: offered.filter((tool) => !keptNames.has(tool.name)).map((tool) => ({ name: tool.name })),
|
|
96
|
+
toolsAdded: added.map(toToolDeclaration),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Section patches: none, the minimal patch, or a remove-all/re-add-all pair when the order would differ. */
|
|
100
|
+
function planSections(shown, desired) {
|
|
101
|
+
const patchedOrder = [
|
|
102
|
+
...[...shown.keys()].filter((key) => desired.has(key)),
|
|
103
|
+
...[...desired.keys()].filter((key) => !shown.has(key)),
|
|
104
|
+
];
|
|
105
|
+
const desiredOrder = [...desired.keys()];
|
|
106
|
+
if (patchedOrder.some((key, index) => key !== desiredOrder[index])) {
|
|
107
|
+
return [Object.fromEntries([...shown.keys()].map((key) => [key, null])), Object.fromEntries(desired)];
|
|
108
|
+
}
|
|
109
|
+
const patch = {};
|
|
110
|
+
for (const [key, value] of shown) {
|
|
111
|
+
const next = desired.get(key);
|
|
112
|
+
if (next !== value)
|
|
113
|
+
patch[key] = next ?? null;
|
|
114
|
+
}
|
|
115
|
+
for (const [key, value] of desired)
|
|
116
|
+
if (!shown.has(key))
|
|
117
|
+
patch[key] = value;
|
|
118
|
+
return Object.keys(patch).length === 0 ? [] : [patch];
|
|
119
|
+
}
|
|
120
|
+
function systemEntry(sections, tools, timestamp) {
|
|
121
|
+
const message = {
|
|
122
|
+
role: "system",
|
|
123
|
+
content: "",
|
|
124
|
+
...(sections === undefined ? {} : { sections }),
|
|
125
|
+
...(tools === undefined || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }),
|
|
126
|
+
...(tools === undefined || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }),
|
|
127
|
+
timestamp,
|
|
128
|
+
};
|
|
129
|
+
return { model: [message] };
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../src/harness/prompt.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEvG,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAI5C,oHAAoH;AACpH,MAAM,UAAU,cAAc,CAAC,QAA4B;IAC1D,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IACxC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS;YAAE,SAAS;QAC1E,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK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,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC;QAC/C,GAAG,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,YAAY,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC;QACvG,GAAG,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC;QACjG,SAAS;KACT,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["import type { Message, SystemMessage, Tool, ToolReference } from \"@diffra-ai/ai\";\nimport { declarationsEqual, getCurrentTools, toToolDeclaration } from \"@diffra-ai/ai/utils/transcript\";\nimport type { Context } from \"@diffra-ai/chord/context\";\nimport { SystemEntry } from \"../entries.ts\";\nimport type { ContextEdit, TypedEntryDraft } from \"../types.ts\";\nimport type { ContextView, PromptInput, PromptSection, ToolRegistration } from \"./types.ts\";\n\n/** Sections in effect after replaying system messages in order: set in place, `null` deletes, re-adding appends. */\nexport function replaySections(messages: readonly Message[]): Map<string, string> {\n\tconst shown = new Map<string, string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"system\" || message.sections === undefined) continue;\n\t\tfor (const [key, value] of Object.entries(message.sections)) {\n\t\t\tif (value === null) shown.delete(key);\n\t\t\telse shown.set(key, value);\n\t\t}\n\t}\n\treturn shown;\n}\n\n/**\n * Render the agent's sections in order. `undefined` omits a section; tagged text is wrapped as `<key>\\n...\\n</key>`. A\n * section that throws keeps its shown text, if any, and is reported; errors after `context` is aborted propagate.\n */\nexport async function renderSections<Tool extends ToolRegistration>(\n\tsections: readonly PromptSection<Tool>[],\n\tinput: PromptInput<Tool>,\n\tshown: ReadonlyMap<string, string>,\n\treport: (error: unknown, section: PromptSection<Tool>) => void,\n\tcontext: Context,\n): Promise<Map<string, string>> {\n\tconst desired = new Map<string, string>();\n\tfor (const section of sections) {\n\t\tlet text: string | undefined;\n\t\ttry {\n\t\t\ttext = await section.render(input, context);\n\t\t} catch (error) {\n\t\t\tif (context.abortSignal?.aborted) throw error;\n\t\t\treport(error, section);\n\t\t\tconst kept = shown.get(section.key);\n\t\t\tif (kept !== undefined) desired.set(section.key, kept);\n\t\t\tcontinue;\n\t\t}\n\t\tif (text === undefined) continue;\n\t\tdesired.set(section.key, section.tag === false ? text : `<${section.key}>\\n${text}\\n</${section.key}>`);\n\t}\n\treturn desired;\n}\n\ntype SystemDraft = TypedEntryDraft<never>;\n\ntype ToolChanges = { readonly toolsRemoved: ToolReference[]; readonly toolsAdded: Tool[] };\n\n/**\n * Plan the `diffra.system` entries that make the replayed sections and tools of `view` equal `desired` and `tools` in values\n * and order.\n *\n * - A head marker with no later `diffra.system` entry in context: one complete baseline that omits every retained earlier\n * `diffra.system` entry, written even when it restates the replayed values.\n * - Otherwise, when a minimal section patch would leave a different order: remove every shown section, then re-add\n * every desired section in order.\n * - Otherwise the minimal patch of changed values and `null` removals, or nothing.\n *\n * Tool changes ride on the last planned entry, or on one entry of their own.\n */\nexport function planSystemEntries(\n\tview: ContextView,\n\tdesired: ReadonlyMap<string, string>,\n\ttools: readonly Tool[],\n\ttimestamp: number,\n): SystemDraft[] {\n\tconst head = view.head;\n\tif (head !== undefined && !view.entries.some((entry) => SystemEntry.is(entry) && entry.id > head.id)) {\n\t\tconst edits: ContextEdit[] = view.entries\n\t\t\t.filter((entry) => SystemEntry.is(entry))\n\t\t\t.map((entry) => ({ target: entry.id, action: \"omit\" }));\n\t\tconst baseline = systemEntry(\n\t\t\tObject.fromEntries(desired),\n\t\t\t{ toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) },\n\t\t\ttimestamp,\n\t\t);\n\t\treturn [edits.length === 0 ? baseline : { ...baseline, edits }];\n\t}\n\tconst sections = planSections(replaySections(view.messages), desired);\n\tconst changes = planTools(getCurrentTools(view.messages), tools);\n\tif (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) {\n\t\treturn sections.map((patch) => systemEntry(patch, undefined, timestamp));\n\t}\n\tif (sections.length === 0) return [systemEntry(undefined, changes, timestamp)];\n\treturn sections.map((patch, index) =>\n\t\tsystemEntry(patch, index === sections.length - 1 ? changes : undefined, timestamp),\n\t);\n}\n\n/**\n * Tool changes from `offered` to `desired`. A changed declaration is removed and re-added. Replay keeps retained tools\n * in place and appends additions; when that would not yield the desired order, every offered tool is removed and\n * every desired tool re-added in order.\n */\nfunction planTools(offered: readonly Tool[], desired: readonly Tool[]): ToolChanges {\n\tconst wanted = new Map(desired.map((tool) => [tool.name, tool]));\n\tconst kept = offered.filter((tool) => {\n\t\tconst next = wanted.get(tool.name);\n\t\treturn next !== undefined && declarationsEqual(tool, next);\n\t});\n\tconst keptNames = new Set(kept.map((tool) => tool.name));\n\tconst added = desired.filter((tool) => !keptNames.has(tool.name));\n\tconst replayed = [...kept, ...added];\n\tif (replayed.some((tool, index) => tool.name !== desired[index]!.name)) {\n\t\treturn {\n\t\t\ttoolsRemoved: offered.map((tool) => ({ name: tool.name })),\n\t\t\ttoolsAdded: desired.map(toToolDeclaration),\n\t\t};\n\t}\n\treturn {\n\t\ttoolsRemoved: offered.filter((tool) => !keptNames.has(tool.name)).map((tool) => ({ name: tool.name })),\n\t\ttoolsAdded: added.map(toToolDeclaration),\n\t};\n}\n\n/** Section patches: none, the minimal patch, or a remove-all/re-add-all pair when the order would differ. */\nfunction planSections(\n\tshown: ReadonlyMap<string, string>,\n\tdesired: ReadonlyMap<string, string>,\n): Record<string, string | null>[] {\n\tconst patchedOrder = [\n\t\t...[...shown.keys()].filter((key) => desired.has(key)),\n\t\t...[...desired.keys()].filter((key) => !shown.has(key)),\n\t];\n\tconst desiredOrder = [...desired.keys()];\n\tif (patchedOrder.some((key, index) => key !== desiredOrder[index])) {\n\t\treturn [Object.fromEntries([...shown.keys()].map((key) => [key, null])), Object.fromEntries(desired)];\n\t}\n\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [key, value] of shown) {\n\t\tconst next = desired.get(key);\n\t\tif (next !== value) patch[key] = next ?? null;\n\t}\n\tfor (const [key, value] of desired) if (!shown.has(key)) patch[key] = value;\n\treturn Object.keys(patch).length === 0 ? [] : [patch];\n}\n\nfunction systemEntry(\n\tsections: Record<string, string | null> | undefined,\n\ttools: ToolChanges | undefined,\n\ttimestamp: number,\n): SystemDraft {\n\tconst message: SystemMessage = {\n\t\trole: \"system\",\n\t\tcontent: \"\",\n\t\t...(sections === undefined ? {} : { sections }),\n\t\t...(tools === undefined || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }),\n\t\t...(tools === undefined || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }),\n\t\ttimestamp,\n\t};\n\treturn { model: [message] };\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Context } from "@diffra-ai/chord/context";
|
|
2
|
+
import type { TaskRuntime } from "../types.ts";
|
|
3
|
+
/** Stable provider-facing identity of one conversation. */
|
|
4
|
+
export type ProviderState = {
|
|
5
|
+
sessionId: string;
|
|
6
|
+
};
|
|
7
|
+
/** Built-in provider state; every fork starts with a fresh identity instead of copying its parent. */
|
|
8
|
+
export declare const ProviderDoc: import("../types.ts").ConversationDocToken<ProviderState>;
|
|
9
|
+
/** Provider session IDs used by each task runtime's Harness. */
|
|
10
|
+
export declare const providerSessionsByRuntime: WeakMap<object, Set<string>>;
|
|
11
|
+
/**
|
|
12
|
+
* Return and record the persisted provider identity without writing in the normal path. A legacy conversation without
|
|
13
|
+
* `diffra.provider` gets one migration commit whose `tx.doc()` runs `initial()` before the provider request starts.
|
|
14
|
+
*/
|
|
15
|
+
export declare function ensureProviderSessionId<I, S, R, H extends object>(runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<string>;
|
|
16
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/harness/provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,2DAA2D;AAC3D,MAAM,MAAM,aAAa,GAAG;IAC3B,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,sGAAsG;AACtG,eAAO,MAAM,WAAW,2DAQtB,CAAC;AAEH,gEAAgE;AAChE,eAAO,MAAM,yBAAyB,8BAAqC,CAAC;AAE5E;;;GAGG;AACH,wBAAsB,uBAAuB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,SAAS,MAAM,EACtE,OAAO,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAChC,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,MAAM,CAAC,CAYjB"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { uuidv7 } from "@diffra-ai/ai/utils/uuid";
|
|
2
|
+
import { defineDoc } from "../documents.js";
|
|
3
|
+
/** Built-in provider state; every fork starts with a fresh identity instead of copying its parent. */
|
|
4
|
+
export const ProviderDoc = defineDoc({
|
|
5
|
+
kind: "diffra.provider",
|
|
6
|
+
version: 1,
|
|
7
|
+
scope: "conversation",
|
|
8
|
+
history: "latest",
|
|
9
|
+
fork: "initial",
|
|
10
|
+
initial: () => ({ sessionId: uuidv7() }),
|
|
11
|
+
checkpointWhen: () => true,
|
|
12
|
+
});
|
|
13
|
+
/** Provider session IDs used by each task runtime's Harness. */
|
|
14
|
+
export const providerSessionsByRuntime = new WeakMap();
|
|
15
|
+
/**
|
|
16
|
+
* Return and record the persisted provider identity without writing in the normal path. A legacy conversation without
|
|
17
|
+
* `diffra.provider` gets one migration commit whose `tx.doc()` runs `initial()` before the provider request starts.
|
|
18
|
+
*/
|
|
19
|
+
export async function ensureProviderSessionId(runtime, context) {
|
|
20
|
+
const existing = await runtime.snapshot(ProviderDoc, runtime.conversationId, context);
|
|
21
|
+
let sessionId = existing?.sessionId;
|
|
22
|
+
if (sessionId === undefined) {
|
|
23
|
+
await runtime.commit(async (tx) => {
|
|
24
|
+
sessionId = (await tx.doc(ProviderDoc, runtime.conversationId)).sessionId;
|
|
25
|
+
return undefined;
|
|
26
|
+
}, context);
|
|
27
|
+
if (sessionId === undefined)
|
|
28
|
+
throw new Error(`Conversation ${runtime.conversationId} has no provider session ID`);
|
|
29
|
+
}
|
|
30
|
+
providerSessionsByRuntime.get(runtime).add(sessionId);
|
|
31
|
+
return sessionId;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/harness/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAQ5C,sGAAsG;AACtG,MAAM,CAAC,MAAM,WAAW,GAAG,SAAS,CAAgB;IACnD,IAAI,EAAE,iBAAiB;IACvB,OAAO,EAAE,CAAC;IACV,KAAK,EAAE,cAAc;IACrB,OAAO,EAAE,QAAQ;IACjB,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,CAAC;IACxC,cAAc,EAAE,GAAG,EAAE,CAAC,IAAI;CAC1B,CAAC,CAAC;AAEH,gEAAgE;AAChE,MAAM,CAAC,MAAM,yBAAyB,GAAG,IAAI,OAAO,EAAuB,CAAC;AAE5E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC5C,OAAgC,EAChC,OAAgB;IAEhB,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;IACtF,IAAI,SAAS,GAAG,QAAQ,EAAE,SAAS,CAAC;IACpC,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC7B,MAAM,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;YACjC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC;YAC1E,OAAO,SAAS,CAAC;QAClB,CAAC,EAAE,OAAO,CAAC,CAAC;QACZ,IAAI,SAAS,KAAK,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,OAAO,CAAC,cAAc,6BAA6B,CAAC,CAAC;IACnH,CAAC;IACD,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAE,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACvD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { uuidv7 } from \"@diffra-ai/ai/utils/uuid\";\nimport type { Context } from \"@diffra-ai/chord/context\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { TaskRuntime } from \"../types.ts\";\n\n/** Stable provider-facing identity of one conversation. */\nexport type ProviderState = {\n\tsessionId: string;\n};\n\n/** Built-in provider state; every fork starts with a fresh identity instead of copying its parent. */\nexport const ProviderDoc = defineDoc<ProviderState>({\n\tkind: \"diffra.provider\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ sessionId: uuidv7() }),\n\tcheckpointWhen: () => true,\n});\n\n/** Provider session IDs used by each task runtime's Harness. */\nexport const providerSessionsByRuntime = new WeakMap<object, Set<string>>();\n\n/**\n * Return and record the persisted provider identity without writing in the normal path. A legacy conversation without\n * `diffra.provider` gets one migration commit whose `tx.doc()` runs `initial()` before the provider request starts.\n */\nexport async function ensureProviderSessionId<I, S, R, H extends object>(\n\truntime: TaskRuntime<I, S, R, H>,\n\tcontext: Context,\n): Promise<string> {\n\tconst existing = await runtime.snapshot(ProviderDoc, runtime.conversationId, context);\n\tlet sessionId = existing?.sessionId;\n\tif (sessionId === undefined) {\n\t\tawait runtime.commit(async (tx) => {\n\t\t\tsessionId = (await tx.doc(ProviderDoc, runtime.conversationId)).sessionId;\n\t\t\treturn undefined;\n\t\t}, context);\n\t\tif (sessionId === undefined) throw new Error(`Conversation ${runtime.conversationId} has no provider session ID`);\n\t}\n\tproviderSessionsByRuntime.get(runtime)!.add(sessionId);\n\treturn sessionId;\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RegistryValue } from "@diffra-ai/chord";
|
|
2
|
+
import type { Context } from "@diffra-ai/chord/context";
|
|
3
|
+
import type { RegistryReader, RegistrySnapshot, ToolRegistration } from "./types.ts";
|
|
4
|
+
/**
|
|
5
|
+
* A `RegistryReader` over a Chord registry value whose composition is a registry snapshot: `snapshot()` reads the
|
|
6
|
+
* current composition (the last good one while `compose` fails), `subscribe` observes its compositions, its listener
|
|
7
|
+
* called synchronously inside the Chord batch that composed (so it only wakes the scheduler; a Chord call there
|
|
8
|
+
* throws `invalid/reentrant`). `context` is the observation's: aborting it detaches every listener.
|
|
9
|
+
*/
|
|
10
|
+
export declare function registryReader<Tool extends ToolRegistration = ToolRegistration>(value: RegistryValue<RegistrySnapshot<Tool>>, context: Context): RegistryReader<Tool>;
|
|
11
|
+
//# sourceMappingURL=registry-reader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-reader.d.ts","sourceRoot":"","sources":["../../src/harness/registry-reader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErF;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,IAAI,SAAS,gBAAgB,GAAG,gBAAgB,EAC9E,KAAK,EAAE,aAAa,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAC5C,OAAO,EAAE,OAAO,GACd,cAAc,CAAC,IAAI,CAAC,CAiBtB"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// A Harness's registry over a Chord registry (Chord v2 slice 8 §5): the composed value of p3's extensions registry,
|
|
2
|
+
// read as Durable's `RegistryReader`.
|
|
3
|
+
/**
|
|
4
|
+
* A `RegistryReader` over a Chord registry value whose composition is a registry snapshot: `snapshot()` reads the
|
|
5
|
+
* current composition (the last good one while `compose` fails), `subscribe` observes its compositions, its listener
|
|
6
|
+
* called synchronously inside the Chord batch that composed (so it only wakes the scheduler; a Chord call there
|
|
7
|
+
* throws `invalid/reentrant`). `context` is the observation's: aborting it detaches every listener.
|
|
8
|
+
*/
|
|
9
|
+
export function registryReader(value, context) {
|
|
10
|
+
return {
|
|
11
|
+
snapshot: () => value.value,
|
|
12
|
+
subscribe: (listener) => {
|
|
13
|
+
const observation = value.observe({
|
|
14
|
+
advance: (call) => {
|
|
15
|
+
// A failed composition keeps the last snapshot: nothing to reconsider.
|
|
16
|
+
if (call.kind === "value")
|
|
17
|
+
listener();
|
|
18
|
+
},
|
|
19
|
+
end: () => { },
|
|
20
|
+
}, context);
|
|
21
|
+
return () => observation.detach();
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=registry-reader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-reader.js","sourceRoot":"","sources":["../../src/harness/registry-reader.ts"],"names":[],"mappings":"AAAA,oHAAoH;AACpH,sCAAsC;AAMtC;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC7B,KAA4C,EAC5C,OAAgB;IAEhB,OAAO;QACN,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK;QAC3B,SAAS,EAAE,CAAC,QAAQ,EAAE,EAAE;YACvB,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAChC;gBACC,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE;oBACjB,uEAAuE;oBACvE,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO;wBAAE,QAAQ,EAAE,CAAC;gBACvC,CAAC;gBACD,GAAG,EAAE,GAAG,EAAE,GAAE,CAAC;aACb,EACD,OAAO,CACP,CAAC;YACF,OAAO,GAAG,EAAE,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACnC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["// A Harness's registry over a Chord registry (Chord v2 slice 8 §5): the composed value of p3's extensions registry,\n// read as Durable's `RegistryReader`.\n\nimport type { RegistryValue } from \"@diffra-ai/chord\";\nimport type { Context } from \"@diffra-ai/chord/context\";\nimport type { RegistryReader, RegistrySnapshot, ToolRegistration } from \"./types.ts\";\n\n/**\n * A `RegistryReader` over a Chord registry value whose composition is a registry snapshot: `snapshot()` reads the\n * current composition (the last good one while `compose` fails), `subscribe` observes its compositions, its listener\n * called synchronously inside the Chord batch that composed (so it only wakes the scheduler; a Chord call there\n * throws `invalid/reentrant`). `context` is the observation's: aborting it detaches every listener.\n */\nexport function registryReader<Tool extends ToolRegistration = ToolRegistration>(\n\tvalue: RegistryValue<RegistrySnapshot<Tool>>,\n\tcontext: Context,\n): RegistryReader<Tool> {\n\treturn {\n\t\tsnapshot: () => value.value,\n\t\tsubscribe: (listener) => {\n\t\t\tconst observation = value.observe(\n\t\t\t\t{\n\t\t\t\t\tadvance: (call) => {\n\t\t\t\t\t\t// A failed composition keeps the last snapshot: nothing to reconsider.\n\t\t\t\t\t\tif (call.kind === \"value\") listener();\n\t\t\t\t\t},\n\t\t\t\t\tend: () => {},\n\t\t\t\t},\n\t\t\t\tcontext,\n\t\t\t);\n\t\t\treturn () => observation.detach();\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AnyTask, Registry, ToolRegistration } from "./types.ts";
|
|
2
|
+
/** Built-in task definitions every registry holds; they are not an extension and cannot be removed or replaced. */
|
|
3
|
+
export declare const BUILTIN_TASKS: readonly AnyTask[];
|
|
4
|
+
/** Create an application-owned registry holding only the built-in tasks. */
|
|
5
|
+
export declare function createRegistry<Tool extends ToolRegistration = ToolRegistration>(): Registry<Tool>;
|
|
6
|
+
//# sourceMappingURL=registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/harness/registry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,OAAO,EAA4B,QAAQ,EAAoB,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAIlH,mHAAmH;AACnH,eAAO,MAAM,aAAa,EAAE,SAAS,OAAO,EAA+C,CAAC;AAqG5F,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,IAAI,SAAS,gBAAgB,GAAG,gBAAgB,KAAK,QAAQ,CAAC,IAAI,CAAC,CAEjG"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { INSTRUCTIONS_KEY } from "./agent.js";
|
|
2
|
+
import { CompactionTask } from "./compaction.js";
|
|
3
|
+
import { GenerationTask } from "./generation.js";
|
|
4
|
+
import { ToolTask } from "./tool.js";
|
|
5
|
+
const SECTION_KEY = /^[a-z][a-z0-9_-]*$/;
|
|
6
|
+
/** Built-in task definitions every registry holds; they are not an extension and cannot be removed or replaced. */
|
|
7
|
+
export const BUILTIN_TASKS = [GenerationTask, ToolTask, CompactionTask];
|
|
8
|
+
/** Immutable published registry state. */
|
|
9
|
+
class RegistryState {
|
|
10
|
+
#extensions;
|
|
11
|
+
#byName;
|
|
12
|
+
#tasks;
|
|
13
|
+
constructor(extensions) {
|
|
14
|
+
this.#extensions = extensions;
|
|
15
|
+
this.#byName = new Map(extensions.map((extension) => [extension.name, extension]));
|
|
16
|
+
const tasks = new Map();
|
|
17
|
+
for (const task of BUILTIN_TASKS)
|
|
18
|
+
tasks.set(task.definition.name, task);
|
|
19
|
+
for (const extension of extensions) {
|
|
20
|
+
for (const task of extension.tasks ?? []) {
|
|
21
|
+
const name = task.definition.name;
|
|
22
|
+
if (tasks.has(name))
|
|
23
|
+
throw new Error(`Task ${name} of extension ${extension.name} is already installed`);
|
|
24
|
+
tasks.set(name, task);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
this.#tasks = tasks;
|
|
28
|
+
}
|
|
29
|
+
installed() {
|
|
30
|
+
return this.#extensions;
|
|
31
|
+
}
|
|
32
|
+
extension(name) {
|
|
33
|
+
return this.#byName.get(name);
|
|
34
|
+
}
|
|
35
|
+
tools() {
|
|
36
|
+
return this.#extensions.flatMap((extension) => (extension.tools ?? []).map((tool) => ({ extension, tool })));
|
|
37
|
+
}
|
|
38
|
+
sections() {
|
|
39
|
+
return this.#extensions.flatMap((extension) => (extension.sections ?? []).map((section) => ({ extension, section })));
|
|
40
|
+
}
|
|
41
|
+
tasks() {
|
|
42
|
+
return [...this.#tasks.values()];
|
|
43
|
+
}
|
|
44
|
+
task(name) {
|
|
45
|
+
return this.#tasks.get(name);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
class RegistryImpl {
|
|
49
|
+
#current = new RegistryState([]);
|
|
50
|
+
#listeners = new Set();
|
|
51
|
+
snapshot() {
|
|
52
|
+
return this.#current;
|
|
53
|
+
}
|
|
54
|
+
subscribe(listener) {
|
|
55
|
+
this.#listeners.add(listener);
|
|
56
|
+
return () => this.#listeners.delete(listener);
|
|
57
|
+
}
|
|
58
|
+
install(extension) {
|
|
59
|
+
validateExtension(extension);
|
|
60
|
+
const current = this.#current.installed();
|
|
61
|
+
const index = current.findIndex((installed) => installed.name === extension.name);
|
|
62
|
+
const next = index < 0 ? [...current, extension] : current.map((installed, at) => (at === index ? extension : installed));
|
|
63
|
+
this.#publish(next);
|
|
64
|
+
}
|
|
65
|
+
uninstall(extension) {
|
|
66
|
+
const current = this.#current.installed();
|
|
67
|
+
if (!current.some((installed) => installed.name === extension.name))
|
|
68
|
+
return;
|
|
69
|
+
this.#publish(current.filter((installed) => installed.name !== extension.name));
|
|
70
|
+
}
|
|
71
|
+
/** Build and validate the next state, which throws on a task name collision, then publish it synchronously. */
|
|
72
|
+
#publish(extensions) {
|
|
73
|
+
this.#current = new RegistryState(extensions);
|
|
74
|
+
for (const listener of [...this.#listeners])
|
|
75
|
+
listener();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Unique tool names and section keys within one extension; valid, unreserved section keys. */
|
|
79
|
+
function validateExtension(extension) {
|
|
80
|
+
const tools = new Set();
|
|
81
|
+
for (const tool of extension.tools ?? []) {
|
|
82
|
+
if (tools.has(tool.name))
|
|
83
|
+
throw new Error(`Extension ${extension.name} has two tools named ${tool.name}`);
|
|
84
|
+
tools.add(tool.name);
|
|
85
|
+
}
|
|
86
|
+
const sections = new Set();
|
|
87
|
+
for (const { key } of extension.sections ?? []) {
|
|
88
|
+
if (!SECTION_KEY.test(key))
|
|
89
|
+
throw new TypeError(`Section key ${JSON.stringify(key)} must match ${SECTION_KEY}`);
|
|
90
|
+
if (key === INSTRUCTIONS_KEY)
|
|
91
|
+
throw new Error(`Section key ${key} is reserved for the agent's instructions`);
|
|
92
|
+
if (sections.has(key))
|
|
93
|
+
throw new Error(`Extension ${extension.name} has two sections with key ${key}`);
|
|
94
|
+
sections.add(key);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Create an application-owned registry holding only the built-in tasks. */
|
|
98
|
+
export function createRegistry() {
|
|
99
|
+
return new RegistryImpl();
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=registry.js.map
|