@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,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `models.*` for code mode scripts, copied from the coding agent's code mode: the model catalog, and classifier and
|
|
3
|
+
* image model calls.
|
|
4
|
+
*
|
|
5
|
+
* The catalog functions are host globals, journaled like any global. `models.classify()` and `models.generateImages()`
|
|
6
|
+
* are paid effects, so each runs as an internal tool (`callers: ["tools"]`, a reserved name, hidden from scripts'
|
|
7
|
+
* tool listings): a nested durable call with its own task, live row, abort, usage accounting, and replay policy. The
|
|
8
|
+
* code mode tool turns a script's call of the global into a call of that tool.
|
|
9
|
+
*/
|
|
10
|
+
import { obj, unknown } from "@diffra-ai/schema";
|
|
11
|
+
import { defineTool } from "../harness/define.js";
|
|
12
|
+
/** Reserved names of code mode's internal tools; they are never listed to scripts or the model. */
|
|
13
|
+
export const CODEMODE_INTERNAL_PREFIX = "diffra.codemode.";
|
|
14
|
+
export const CLASSIFY_TOOL = `${CODEMODE_INTERNAL_PREFIX}models.classify`;
|
|
15
|
+
export const GENERATE_IMAGES_TOOL = `${CODEMODE_INTERNAL_PREFIX}models.generateImages`;
|
|
16
|
+
/** The global a script calls, by internal tool. */
|
|
17
|
+
export const MODEL_CALLS = {
|
|
18
|
+
"models.classify": CLASSIFY_TOOL,
|
|
19
|
+
"models.generateImages": GENERATE_IMAGES_TOOL,
|
|
20
|
+
};
|
|
21
|
+
/** The catalog functions, host globals of the `models` namespace. */
|
|
22
|
+
export const CATALOG_GLOBALS = [
|
|
23
|
+
"models.getModelsOfType",
|
|
24
|
+
"models.getAvailableOfType",
|
|
25
|
+
"models.getModelOfType",
|
|
26
|
+
];
|
|
27
|
+
/** `models.classify()` and `models.generateImages()` calls one script may have in flight; the rest wait. */
|
|
28
|
+
export const MAX_CONCURRENT_MODEL_CALLS = 4;
|
|
29
|
+
const MODEL_TYPES = new Set(["chat", "image", "classifier"]);
|
|
30
|
+
export const MODELS_DESCRIPTION = [
|
|
31
|
+
"`models` (all functions return promises):",
|
|
32
|
+
'- `models.getModelsOfType(type, provider?)`, `models.getAvailableOfType(type, provider?)` (configured auth only), `models.getModelOfType(type, provider, id)`: the catalog; `type` is "chat", "image", or "classifier".',
|
|
33
|
+
'- `models.classify(model, { state: { ... }, images?: [{ type: "image", data, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } })` resolves to `{ answers: { <id>: ... }, stopReason, errorMessage?, usage? }`.',
|
|
34
|
+
'- `models.generateImages(model, { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data, mimeType }] })` resolves to `{ output: [image blocks], stopReason, errorMessage?, usage? }`; show each image with `image(block)`.',
|
|
35
|
+
`At most ${MAX_CONCURRENT_MODEL_CALLS} classify/generateImages calls run at once; more wait.`,
|
|
36
|
+
].join("\n");
|
|
37
|
+
function isRecord(value) {
|
|
38
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
39
|
+
}
|
|
40
|
+
/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */
|
|
41
|
+
function describeValue(value) {
|
|
42
|
+
if (value === undefined || value === null)
|
|
43
|
+
return String(value);
|
|
44
|
+
if (Array.isArray(value))
|
|
45
|
+
return value.length === 0 ? "an empty array" : "an array";
|
|
46
|
+
if (typeof value === "object") {
|
|
47
|
+
const keys = Object.keys(value);
|
|
48
|
+
if (keys.length === 0)
|
|
49
|
+
return "{}";
|
|
50
|
+
return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
|
|
51
|
+
}
|
|
52
|
+
return typeof value === "string" ? "a string" : `a ${typeof value}`;
|
|
53
|
+
}
|
|
54
|
+
/** `an image`, `a classifier`. */
|
|
55
|
+
function withArticle(word) {
|
|
56
|
+
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
57
|
+
}
|
|
58
|
+
function toModelType(value) {
|
|
59
|
+
if (typeof value === "string" && MODEL_TYPES.has(value))
|
|
60
|
+
return value;
|
|
61
|
+
throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`);
|
|
62
|
+
}
|
|
63
|
+
function toProvider(value) {
|
|
64
|
+
if (value === undefined || value === null)
|
|
65
|
+
return undefined;
|
|
66
|
+
if (typeof value !== "string")
|
|
67
|
+
throw new Error("provider must be a string");
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
/** Catalog entry for scripts. `headers` is dropped because configured headers can carry credentials. */
|
|
71
|
+
function toModelInfo(model) {
|
|
72
|
+
const info = { ...model };
|
|
73
|
+
delete info.headers;
|
|
74
|
+
return JSON.parse(JSON.stringify(info));
|
|
75
|
+
}
|
|
76
|
+
/** The catalog functions: what a script's call of `name` with `args` (the argument list) resolves to. */
|
|
77
|
+
export async function catalogCall(name, args, models, context) {
|
|
78
|
+
const list = Array.isArray(args) ? args : [];
|
|
79
|
+
const [type, provider, id] = list;
|
|
80
|
+
if (name === "models.getModelsOfType")
|
|
81
|
+
return models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);
|
|
82
|
+
if (name === "models.getAvailableOfType") {
|
|
83
|
+
const available = await models.getAvailableOfType(toModelType(type), toProvider(provider), {
|
|
84
|
+
...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),
|
|
85
|
+
});
|
|
86
|
+
return available.map(toModelInfo);
|
|
87
|
+
}
|
|
88
|
+
if (typeof provider !== "string" || typeof id !== "string") {
|
|
89
|
+
throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${list.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);
|
|
90
|
+
}
|
|
91
|
+
const model = models.getModelOfType(toModelType(type), provider, id);
|
|
92
|
+
return model === undefined ? undefined : toModelInfo(model);
|
|
93
|
+
}
|
|
94
|
+
const CLASSIFIER_CONTEXT_SHAPE = '{ state: { ... }, images?: [{ type: "image", data: <base64>, mimeType }], questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';
|
|
95
|
+
/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */
|
|
96
|
+
function checkClassifierContext(context) {
|
|
97
|
+
const fail = (problem) => new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}.`);
|
|
98
|
+
if (!isRecord(context))
|
|
99
|
+
throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
|
|
100
|
+
if (!isRecord(context.state))
|
|
101
|
+
throw fail(`context.state must be an object, got ${describeValue(context.state)}`);
|
|
102
|
+
const { images } = context;
|
|
103
|
+
if (images !== undefined) {
|
|
104
|
+
if (!Array.isArray(images))
|
|
105
|
+
throw fail(`context.images must be an array, got ${describeValue(images)}`);
|
|
106
|
+
images.forEach((image, index) => {
|
|
107
|
+
if (!isRecord(image) ||
|
|
108
|
+
image.type !== "image" ||
|
|
109
|
+
typeof image.data !== "string" ||
|
|
110
|
+
typeof image.mimeType !== "string") {
|
|
111
|
+
throw fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
const { questions } = context;
|
|
116
|
+
if (!isRecord(questions) || Object.keys(questions).length === 0) {
|
|
117
|
+
throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
|
|
118
|
+
}
|
|
119
|
+
const isStrings = (values) => values.length > 0 && values.every((value) => typeof value === "string");
|
|
120
|
+
for (const [id, question] of Object.entries(questions)) {
|
|
121
|
+
const at = `context.questions.${id}`;
|
|
122
|
+
if (!isRecord(question))
|
|
123
|
+
throw fail(`${at} must be a question object, got ${describeValue(question)}`);
|
|
124
|
+
if (typeof question.instructions !== "string")
|
|
125
|
+
throw fail(`${at}.instructions must be a string`);
|
|
126
|
+
const { criteria } = question;
|
|
127
|
+
if (question.type === "choice") {
|
|
128
|
+
if (!isRecord(criteria) || !isStrings(Object.values(criteria))) {
|
|
129
|
+
throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else if (question.type === "score") {
|
|
133
|
+
if (!Array.isArray(criteria) || !isStrings(criteria)) {
|
|
134
|
+
throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (question.type === "bool") {
|
|
138
|
+
if (!isRecord(criteria) || typeof criteria.true !== "string" || typeof criteria.false !== "string") {
|
|
139
|
+
throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(question.type)}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return context;
|
|
147
|
+
}
|
|
148
|
+
/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */
|
|
149
|
+
function checkImagesContext(context) {
|
|
150
|
+
const fail = (problem) => new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }.`);
|
|
151
|
+
if (!isRecord(context))
|
|
152
|
+
throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
|
|
153
|
+
const { input } = context;
|
|
154
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
155
|
+
throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
|
|
156
|
+
}
|
|
157
|
+
input.forEach((block, index) => {
|
|
158
|
+
if (isRecord(block) && block.type === "text" && typeof block.text === "string")
|
|
159
|
+
return;
|
|
160
|
+
if (isRecord(block) &&
|
|
161
|
+
block.type === "image" &&
|
|
162
|
+
typeof block.data === "string" &&
|
|
163
|
+
typeof block.mimeType === "string")
|
|
164
|
+
return;
|
|
165
|
+
throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
|
|
166
|
+
});
|
|
167
|
+
return context;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Resolve the script's model by provider and id only, so a script-supplied baseUrl or headers never receive the
|
|
171
|
+
* credentials, with errors that say what to do.
|
|
172
|
+
*/
|
|
173
|
+
function resolveModel(name, type, model, models) {
|
|
174
|
+
const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
|
|
175
|
+
if (!isRecord(model) || typeof model.provider !== "string" || typeof model.id !== "string") {
|
|
176
|
+
const undefinedHint = model === undefined || model === null
|
|
177
|
+
? " models.getModelOfType() returns undefined for an unknown provider or id."
|
|
178
|
+
: "";
|
|
179
|
+
throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`);
|
|
180
|
+
}
|
|
181
|
+
const { provider, id } = model;
|
|
182
|
+
const resolved = models.getModelOfType(type, provider, id);
|
|
183
|
+
if (resolved !== undefined)
|
|
184
|
+
return resolved;
|
|
185
|
+
const actualType = [...MODEL_TYPES].find((other) => other !== type && models.getModelOfType(other, provider, id) !== undefined);
|
|
186
|
+
throw new Error(actualType
|
|
187
|
+
? `"${provider}/${id}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`
|
|
188
|
+
: `Unknown ${type} model "${provider}/${id}". ${listHint}`);
|
|
189
|
+
}
|
|
190
|
+
const ModelCallParameters = obj({ model: unknown(), context: unknown() }, { open: true });
|
|
191
|
+
/** The result of a model call as the tool returns it: the whole result for the script, usage counted by the Harness. */
|
|
192
|
+
function modelResult(label, result, value) {
|
|
193
|
+
const ok = result.stopReason === "stop";
|
|
194
|
+
return {
|
|
195
|
+
output: [
|
|
196
|
+
{
|
|
197
|
+
type: "text",
|
|
198
|
+
text: ok ? `${label} done` : `${label} ${result.stopReason}: ${result.errorMessage ?? ""}`,
|
|
199
|
+
},
|
|
200
|
+
],
|
|
201
|
+
structuredOutput: JSON.parse(JSON.stringify(value)),
|
|
202
|
+
...(ok ? {} : { isError: true }),
|
|
203
|
+
...(result.usage === undefined ? {} : { usage: result.usage }),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** The internal tools behind `models.classify()` and `models.generateImages()`. */
|
|
207
|
+
export function createModelTools() {
|
|
208
|
+
const classify = defineTool({
|
|
209
|
+
name: CLASSIFY_TOOL,
|
|
210
|
+
description: "models.classify() of code mode scripts.",
|
|
211
|
+
parameters: ModelCallParameters,
|
|
212
|
+
structuredOutputSchema: unknown(),
|
|
213
|
+
callers: ["tools"],
|
|
214
|
+
execute: async (args, api, context) => {
|
|
215
|
+
const model = resolveModel("models.classify", "classifier", args.model, api.models);
|
|
216
|
+
const checked = checkClassifierContext(args.context);
|
|
217
|
+
const result = await api.models.classify(model, checked, {
|
|
218
|
+
telemetry: context.telemetry,
|
|
219
|
+
...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),
|
|
220
|
+
});
|
|
221
|
+
return modelResult(`classify ${model.provider}/${model.id}`, result, result);
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
const generateImages = defineTool({
|
|
225
|
+
name: GENERATE_IMAGES_TOOL,
|
|
226
|
+
description: "models.generateImages() of code mode scripts.",
|
|
227
|
+
parameters: ModelCallParameters,
|
|
228
|
+
structuredOutputSchema: unknown(),
|
|
229
|
+
callers: ["tools"],
|
|
230
|
+
execute: async (args, api, context) => {
|
|
231
|
+
const model = resolveModel("models.generateImages", "image", args.model, api.models);
|
|
232
|
+
const checked = checkImagesContext(args.context);
|
|
233
|
+
const result = await api.models.generateImages(model, checked, {
|
|
234
|
+
telemetry: context.telemetry,
|
|
235
|
+
...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),
|
|
236
|
+
});
|
|
237
|
+
return modelResult(`generateImages ${model.provider}/${model.id}`, result, result);
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
return [classify, generateImages];
|
|
241
|
+
}
|
|
242
|
+
//# sourceMappingURL=models.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/codemode/models.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGlD,mGAAmG;AACnG,MAAM,CAAC,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAC3D,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,wBAAwB,iBAAiB,CAAC;AAC1E,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,wBAAwB,uBAAuB,CAAC;AAEvF,mDAAmD;AACnD,MAAM,CAAC,MAAM,WAAW,GAAqC;IAC5D,iBAAiB,EAAE,aAAa;IAChC,uBAAuB,EAAE,oBAAoB;CAC7C,CAAC;AAEF,qEAAqE;AACrE,MAAM,CAAC,MAAM,eAAe,GAAG;IAC9B,wBAAwB;IACxB,2BAA2B;IAC3B,uBAAuB;CACd,CAAC;AAEX,4GAA4G;AAC5G,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAE5C,MAAM,WAAW,GAAwB,IAAI,GAAG,CAAY,CAAC,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;AAE7F,MAAM,CAAC,MAAM,kBAAkB,GAAG;IACjC,2CAA2C;IAC3C,yNAAyN;IACzN,0aAA0a;IAC1a,kPAAkP;IAClP,WAAW,0BAA0B,wDAAwD;CAC7F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,2GAA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EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9E,CAAC;KACD,CAAC,CAAC;IACH,MAAM,cAAc,GAAG,UAAU,CAAC;QACjC,IAAI,EAAE,oBAAoB;QAC1B,WAAW,EAAE,+CAA+C;QAC5D,UAAU,EAAE,mBAAmB;QAC/B,sBAAsB,EAAE,OAAO,EAAE;QACjC,OAAO,EAAE,CAAC,OAAO,CAAC;QAClB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE;YACrC,MAAM,KAAK,GAAG,YAAY,CAAC,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACrF,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACjD,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE;gBAC9D,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,GAAG,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC;aAC7E,CAAC,CAAC;YACH,OAAO,WAAW,CAAC,kBAAkB,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QACpF,CAAC;KACD,CAAC,CAAC;IACH,OAAO,CAAC,QAAuC,EAAE,cAA6C,CAAC,CAAC;AACjG,CAAC","sourcesContent":["/**\n * `models.*` for code mode scripts, copied from the coding agent's code mode: the model catalog, and classifier and\n * image model calls.\n *\n * The catalog functions are host globals, journaled like any global. `models.classify()` and `models.generateImages()`\n * are paid effects, so each runs as an internal tool (`callers: [\"tools\"]`, a reserved name, hidden from scripts'\n * tool listings): a nested durable call with its own task, live row, abort, usage accounting, and replay policy. The\n * code mode tool turns a script's call of the global into a call of that tool.\n */\n\nimport type { AnyModel, ClassifierContext, ImagesContext, Models, ModelType, ModelTypeMap, Usage } from \"@diffra-ai/ai\";\nimport type { Context } from \"@diffra-ai/chord/context\";\nimport type { JsonValue } from \"@diffra-ai/chord/json\";\nimport { obj, unknown } from \"@diffra-ai/schema\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\n\n/** Reserved names of code mode's internal tools; they are never listed to scripts or the model. */\nexport const CODEMODE_INTERNAL_PREFIX = \"diffra.codemode.\";\nexport const CLASSIFY_TOOL = `${CODEMODE_INTERNAL_PREFIX}models.classify`;\nexport const GENERATE_IMAGES_TOOL = `${CODEMODE_INTERNAL_PREFIX}models.generateImages`;\n\n/** The global a script calls, by internal tool. */\nexport const MODEL_CALLS: Readonly<Record<string, string>> = {\n\t\"models.classify\": CLASSIFY_TOOL,\n\t\"models.generateImages\": GENERATE_IMAGES_TOOL,\n};\n\n/** The catalog functions, host globals of the `models` namespace. */\nexport const CATALOG_GLOBALS = [\n\t\"models.getModelsOfType\",\n\t\"models.getAvailableOfType\",\n\t\"models.getModelOfType\",\n] as const;\n\n/** `models.classify()` and `models.generateImages()` calls one script may have in flight; the rest wait. */\nexport const MAX_CONCURRENT_MODEL_CALLS = 4;\n\nconst MODEL_TYPES: ReadonlySet<string> = new Set<ModelType>([\"chat\", \"image\", \"classifier\"]);\n\nexport const MODELS_DESCRIPTION = [\n\t\"`models` (all functions return promises):\",\n\t'- `models.getModelsOfType(type, provider?)`, `models.getAvailableOfType(type, provider?)` (configured auth only), `models.getModelOfType(type, provider, id)`: the catalog; `type` is \"chat\", \"image\", or \"classifier\".',\n\t'- `models.classify(model, { state: { ... }, images?: [{ type: \"image\", data, mimeType }], questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } })` resolves to `{ answers: { <id>: ... }, stopReason, errorMessage?, usage? }`.',\n\t'- `models.generateImages(model, { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data, mimeType }] })` resolves to `{ output: [image blocks], stopReason, errorMessage?, usage? }`; show each image with `image(block)`.',\n\t`At most ${MAX_CONCURRENT_MODEL_CALLS} classify/generateImages calls run at once; more wait.`,\n].join(\"\\n\");\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */\nfunction describeValue(value: unknown): string {\n\tif (value === undefined || value === null) return String(value);\n\tif (Array.isArray(value)) return value.length === 0 ? \"an empty array\" : \"an array\";\n\tif (typeof value === \"object\") {\n\t\tconst keys = Object.keys(value);\n\t\tif (keys.length === 0) return \"{}\";\n\t\treturn `{ ${keys.slice(0, 6).join(\", \")}${keys.length > 6 ? \", ...\" : \"\"} }`;\n\t}\n\treturn typeof value === \"string\" ? \"a string\" : `a ${typeof value}`;\n}\n\n/** `an image`, `a classifier`. */\nfunction withArticle(word: string): string {\n\treturn `${/^[aeiou]/.test(word) ? \"an\" : \"a\"} ${word}`;\n}\n\nfunction toModelType(value: unknown): ModelType {\n\tif (typeof value === \"string\" && MODEL_TYPES.has(value)) return value as ModelType;\n\tthrow new Error(`Unknown model type ${JSON.stringify(value)}. Use \"chat\", \"image\", or \"classifier\".`);\n}\n\nfunction toProvider(value: unknown): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(\"provider must be a string\");\n\treturn value;\n}\n\n/** Catalog entry for scripts. `headers` is dropped because configured headers can carry credentials. */\nfunction toModelInfo(model: AnyModel): JsonValue {\n\tconst info: Record<string, unknown> = { ...model };\n\tdelete info.headers;\n\treturn JSON.parse(JSON.stringify(info)) as JsonValue;\n}\n\n/** The catalog functions: what a script's call of `name` with `args` (the argument list) resolves to. */\nexport async function catalogCall(\n\tname: string,\n\targs: unknown,\n\tmodels: Models,\n\tcontext: Context,\n): Promise<JsonValue | undefined> {\n\tconst list = Array.isArray(args) ? args : [];\n\tconst [type, provider, id] = list;\n\tif (name === \"models.getModelsOfType\")\n\t\treturn models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);\n\tif (name === \"models.getAvailableOfType\") {\n\t\tconst available = await models.getAvailableOfType(toModelType(type), toProvider(provider), {\n\t\t\t...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),\n\t\t});\n\t\treturn available.map(toModelInfo);\n\t}\n\tif (typeof provider !== \"string\" || typeof id !== \"string\") {\n\t\tthrow new Error(\n\t\t\t`models.getModelOfType(type, provider, id) expects three strings, got (${list.map(describeValue).join(\", \")}). The provider and the id are separate arguments, for example models.getModelOfType(\"classifier\", \"typesafe\", \"jev-latest\").`,\n\t\t);\n\t}\n\tconst model = models.getModelOfType(toModelType(type), provider, id);\n\treturn model === undefined ? undefined : toModelInfo(model);\n}\n\nconst CLASSIFIER_CONTEXT_SHAPE =\n\t'{ state: { ... }, images?: [{ type: \"image\", data: <base64>, mimeType }], questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';\n\n/** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */\nfunction checkClassifierContext(context: unknown): ClassifierContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}.`);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tif (!isRecord(context.state)) throw fail(`context.state must be an object, got ${describeValue(context.state)}`);\n\tconst { images } = context;\n\tif (images !== undefined) {\n\t\tif (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);\n\t\timages.forEach((image: unknown, index) => {\n\t\t\tif (\n\t\t\t\t!isRecord(image) ||\n\t\t\t\timage.type !== \"image\" ||\n\t\t\t\ttypeof image.data !== \"string\" ||\n\t\t\t\ttypeof image.mimeType !== \"string\"\n\t\t\t) {\n\t\t\t\tthrow fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);\n\t\t\t}\n\t\t});\n\t}\n\tconst { questions } = context;\n\tif (!isRecord(questions) || Object.keys(questions).length === 0) {\n\t\tthrow fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);\n\t}\n\tconst isStrings = (values: unknown[]) => values.length > 0 && values.every((value) => typeof value === \"string\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tconst at = `context.questions.${id}`;\n\t\tif (!isRecord(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);\n\t\tif (typeof question.instructions !== \"string\") throw fail(`${at}.instructions must be a string`);\n\t\tconst { criteria } = question;\n\t\tif (question.type === \"choice\") {\n\t\t\tif (!isRecord(criteria) || !isStrings(Object.values(criteria))) {\n\t\t\t\tthrow fail(`${at} is a \"choice\" question, so criteria must map each label to its meaning`);\n\t\t\t}\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (!Array.isArray(criteria) || !isStrings(criteria)) {\n\t\t\t\tthrow fail(`${at} is a \"score\" question, so criteria must list the levels as strings, lowest first`);\n\t\t\t}\n\t\t} else if (question.type === \"bool\") {\n\t\t\tif (!isRecord(criteria) || typeof criteria.true !== \"string\" || typeof criteria.false !== \"string\") {\n\t\t\t\tthrow fail(`${at} is a \"bool\" question, so criteria must be { true: string, false: string }`);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow fail(`${at}.type must be \"choice\", \"score\", or \"bool\", got ${JSON.stringify(question.type)}`);\n\t\t}\n\t}\n\treturn context as unknown as ClassifierContext;\n}\n\n/** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */\nfunction checkImagesContext(context: unknown): ImagesContext {\n\tconst fail = (problem: string) =>\n\t\tnew Error(\n\t\t\t`models.generateImages() ${problem}. Expected context: { input: [{ type: \"text\", text: <prompt> }, ...optional { type: \"image\", data: <base64>, mimeType } references] }.`,\n\t\t);\n\tif (!isRecord(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);\n\tconst { input } = context;\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\tthrow fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);\n\t}\n\tinput.forEach((block: unknown, index) => {\n\t\tif (isRecord(block) && block.type === \"text\" && typeof block.text === \"string\") return;\n\t\tif (\n\t\t\tisRecord(block) &&\n\t\t\tblock.type === \"image\" &&\n\t\t\ttypeof block.data === \"string\" &&\n\t\t\ttypeof block.mimeType === \"string\"\n\t\t)\n\t\t\treturn;\n\t\tthrow fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);\n\t});\n\treturn context as unknown as ImagesContext;\n}\n\n/**\n * Resolve the script's model by provider and id only, so a script-supplied baseUrl or headers never receive the\n * credentials, with errors that say what to do.\n */\nfunction resolveModel<TType extends \"classifier\" | \"image\">(\n\tname: string,\n\ttype: TType,\n\tmodel: unknown,\n\tmodels: Models,\n): ModelTypeMap[TType] {\n\tconst listHint = `List the ${type} models you can use with models.getAvailableOfType(\"${type}\").`;\n\tif (!isRecord(model) || typeof model.provider !== \"string\" || typeof model.id !== \"string\") {\n\t\tconst undefinedHint =\n\t\t\tmodel === undefined || model === null\n\t\t\t\t? \" models.getModelOfType() returns undefined for an unknown provider or id.\"\n\t\t\t\t: \"\";\n\t\tthrow new Error(\n\t\t\t`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`,\n\t\t);\n\t}\n\tconst { provider, id } = model;\n\tconst resolved = models.getModelOfType(type, provider, id);\n\tif (resolved !== undefined) return resolved;\n\tconst actualType = [...MODEL_TYPES].find(\n\t\t(other) => other !== type && models.getModelOfType(other as ModelType, provider, id) !== undefined,\n\t);\n\tthrow new Error(\n\t\tactualType\n\t\t\t? `\"${provider}/${id}\" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`\n\t\t\t: `Unknown ${type} model \"${provider}/${id}\". ${listHint}`,\n\t);\n}\n\nconst ModelCallParameters = obj({ model: unknown(), context: unknown() }, { open: true });\n\n/** The result of a model call as the tool returns it: the whole result for the script, usage counted by the Harness. */\nfunction modelResult(\n\tlabel: string,\n\tresult: { stopReason: string; errorMessage?: string; usage?: Usage },\n\tvalue: unknown,\n) {\n\tconst ok = result.stopReason === \"stop\";\n\treturn {\n\t\toutput: [\n\t\t\t{\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: ok ? `${label} done` : `${label} ${result.stopReason}: ${result.errorMessage ?? \"\"}`,\n\t\t\t},\n\t\t],\n\t\tstructuredOutput: JSON.parse(JSON.stringify(value)) as JsonValue,\n\t\t...(ok ? {} : { isError: true }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t};\n}\n\n/** The internal tools behind `models.classify()` and `models.generateImages()`. */\nexport function createModelTools(): ToolRegistration[] {\n\tconst classify = defineTool({\n\t\tname: CLASSIFY_TOOL,\n\t\tdescription: \"models.classify() of code mode scripts.\",\n\t\tparameters: ModelCallParameters,\n\t\tstructuredOutputSchema: unknown(),\n\t\tcallers: [\"tools\"],\n\t\texecute: async (args, api, context) => {\n\t\t\tconst model = resolveModel(\"models.classify\", \"classifier\", args.model, api.models);\n\t\t\tconst checked = checkClassifierContext(args.context);\n\t\t\tconst result = await api.models.classify(model, checked, {\n\t\t\t\ttelemetry: context.telemetry,\n\t\t\t\t...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),\n\t\t\t});\n\t\t\treturn modelResult(`classify ${model.provider}/${model.id}`, result, result);\n\t\t},\n\t});\n\tconst generateImages = defineTool({\n\t\tname: GENERATE_IMAGES_TOOL,\n\t\tdescription: \"models.generateImages() of code mode scripts.\",\n\t\tparameters: ModelCallParameters,\n\t\tstructuredOutputSchema: unknown(),\n\t\tcallers: [\"tools\"],\n\t\texecute: async (args, api, context) => {\n\t\t\tconst model = resolveModel(\"models.generateImages\", \"image\", args.model, api.models);\n\t\t\tconst checked = checkImagesContext(args.context);\n\t\t\tconst result = await api.models.generateImages(model, checked, {\n\t\t\t\ttelemetry: context.telemetry,\n\t\t\t\t...(context.abortSignal === undefined ? {} : { signal: context.abortSignal }),\n\t\t\t});\n\t\t\treturn modelResult(`generateImages ${model.provider}/${model.id}`, result, result);\n\t\t},\n\t});\n\treturn [classify as unknown as ToolRegistration, generateImages as unknown as ToolRegistration];\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A script's result as the model reads it, copied from the coding agent's code mode: a "Script completed/failed"
|
|
3
|
+
* header with the wall time, the script's text items (`==> text N/M <==` when there are several), its `console` lines
|
|
4
|
+
* in one `<console_output>` block, the returned value, and on failure the error with the calls already made. Text past
|
|
5
|
+
* the token budget is cut to its start and end, with the complete text in a temp file; images are saved to temp files
|
|
6
|
+
* too, with their path next to them, because a script has no other way to hand their bytes on.
|
|
7
|
+
*/
|
|
8
|
+
import type { ImageContent, TextContent } from "@diffra-ai/ai";
|
|
9
|
+
import type { CodemodeResult } from "@diffra-ai/codemode/portable";
|
|
10
|
+
type Item = TextContent | ImageContent;
|
|
11
|
+
/** Writes a file of the result under a fixed name; its path, or why it could not be written. */
|
|
12
|
+
export type OutputFile = (name: string, data: string | Uint8Array) => Promise<{
|
|
13
|
+
readonly kind: "saved";
|
|
14
|
+
readonly path: string;
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: "failed";
|
|
17
|
+
readonly error: string;
|
|
18
|
+
}>;
|
|
19
|
+
/** The tool's output limits, which the Harness enforces by cutting without a spill file: results stay inside them. */
|
|
20
|
+
type Limits = {
|
|
21
|
+
readonly maxBytes: number;
|
|
22
|
+
readonly maxLines: number;
|
|
23
|
+
};
|
|
24
|
+
/** Default token budget for script output. */
|
|
25
|
+
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 10000;
|
|
26
|
+
/** The tool result's content for a script's result, and the path of the complete text when it was cut. */
|
|
27
|
+
export declare function formatResult(result: CodemodeResult, options: {
|
|
28
|
+
/** Images `models.generateImages()` returned; when the script showed none, the result says so. */
|
|
29
|
+
readonly generatedImages: number;
|
|
30
|
+
readonly wallMs: number;
|
|
31
|
+
readonly maxOutputTokens: number;
|
|
32
|
+
readonly calls: readonly {
|
|
33
|
+
name: string;
|
|
34
|
+
status: string;
|
|
35
|
+
}[];
|
|
36
|
+
readonly limits: Limits;
|
|
37
|
+
readonly write: OutputFile;
|
|
38
|
+
}): Promise<{
|
|
39
|
+
content: Item[];
|
|
40
|
+
fullOutputPath?: string;
|
|
41
|
+
}>;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=output.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../../src/codemode/output.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAsB,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGvF,KAAK,IAAI,GAAG,WAAW,GAAG,YAAY,CAAC;AAEvC,gGAAgG;AAChG,MAAM,MAAM,UAAU,GAAG,CACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GAAG,UAAU,KACrB,OAAO,CAAC;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAEtH,sHAAsH;AACtH,KAAK,MAAM,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAIvE,8CAA8C;AAC9C,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAwJhD,0GAA0G;AAC1G,wBAAsB,YAAY,CACjC,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE;IACR,kGAAkG;IAClG,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC5D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;CAC3B,GACC,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAoBvD"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { fromBase64 } from "../tools/image-processor.js";
|
|
2
|
+
/** Lines of the result besides the script's text: the header, markers, notes. */
|
|
3
|
+
const LINE_MARGIN = 100;
|
|
4
|
+
/** Default token budget for script output. */
|
|
5
|
+
export const DEFAULT_MAX_OUTPUT_TOKENS = 10_000;
|
|
6
|
+
/** Characters per token when estimating. */
|
|
7
|
+
const CHARS_PER_TOKEN = 4;
|
|
8
|
+
/** File extensions of the image types `image()` accepts. */
|
|
9
|
+
const IMAGE_EXTENSIONS = {
|
|
10
|
+
"image/png": ".png",
|
|
11
|
+
"image/jpeg": ".jpg",
|
|
12
|
+
"image/gif": ".gif",
|
|
13
|
+
"image/webp": ".webp",
|
|
14
|
+
};
|
|
15
|
+
/** Like the script's `text()`: strings as is, other values as compact JSON. */
|
|
16
|
+
function valueText(value) {
|
|
17
|
+
if (typeof value === "string")
|
|
18
|
+
return value;
|
|
19
|
+
return JSON.stringify(value) ?? String(value);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Lay out the script's output so the model can tell items apart: with more than one text item, each starts with a
|
|
23
|
+
* `==> text N/M <==` line; `console` lines follow all other output in one `<console_output>` block.
|
|
24
|
+
*/
|
|
25
|
+
function formatItems(output) {
|
|
26
|
+
const total = output.filter((item) => item.type === "text" && !item.console).length;
|
|
27
|
+
const items = [];
|
|
28
|
+
const consoleLines = [];
|
|
29
|
+
let index = 0;
|
|
30
|
+
for (const item of output) {
|
|
31
|
+
if (item.type === "image")
|
|
32
|
+
items.push(item);
|
|
33
|
+
else if (item.console)
|
|
34
|
+
consoleLines.push(item.text);
|
|
35
|
+
else {
|
|
36
|
+
index++;
|
|
37
|
+
items.push({ type: "text", text: total > 1 ? `==> text ${index}/${total} <==\n${item.text}` : item.text });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (consoleLines.length > 0) {
|
|
41
|
+
items.push({ type: "text", text: `<console_output>\n${consoleLines.join("\n")}\n</console_output>` });
|
|
42
|
+
}
|
|
43
|
+
return items;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Join adjacent text items into one, each part starting on its own line. The separator check looks at the last
|
|
47
|
+
* non-empty part, not the joined text: reading the end of a growing concatenation makes V8 copy it on every item, which
|
|
48
|
+
* is quadratic.
|
|
49
|
+
*/
|
|
50
|
+
function joinAdjacentText(items) {
|
|
51
|
+
const joined = [];
|
|
52
|
+
let parts = [];
|
|
53
|
+
let lastPart = "";
|
|
54
|
+
const flush = () => {
|
|
55
|
+
if (parts.length > 0)
|
|
56
|
+
joined.push({ type: "text", text: parts.join("") });
|
|
57
|
+
parts = [];
|
|
58
|
+
lastPart = "";
|
|
59
|
+
};
|
|
60
|
+
for (const item of items) {
|
|
61
|
+
if (item.type !== "text") {
|
|
62
|
+
flush();
|
|
63
|
+
joined.push(item);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (lastPart !== "" && !lastPart.endsWith("\n")) {
|
|
67
|
+
parts.push("\n");
|
|
68
|
+
lastPart = "\n";
|
|
69
|
+
}
|
|
70
|
+
parts.push(item.text);
|
|
71
|
+
if (item.text !== "")
|
|
72
|
+
lastPart = item.text;
|
|
73
|
+
}
|
|
74
|
+
flush();
|
|
75
|
+
return joined;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Apply the token budget: when the combined text exceeds it, the text items become one item that keeps the start and
|
|
79
|
+
* end of the text, and images follow it. The complete text is written to a temp file.
|
|
80
|
+
*/
|
|
81
|
+
async function truncate(items, maxTokens, limits, write) {
|
|
82
|
+
const texts = items.filter((item) => item.type === "text").map((item) => item.text);
|
|
83
|
+
const combined = texts.join("\n");
|
|
84
|
+
// Within the limits too: a UTF-16 unit is at most 3 UTF-8 bytes, and the rest of the result is a few short lines.
|
|
85
|
+
const budget = Math.min(maxTokens * CHARS_PER_TOKEN, Math.floor(limits.maxBytes / 4));
|
|
86
|
+
const lineBudget = Math.floor((limits.maxLines - LINE_MARGIN) / 2);
|
|
87
|
+
const lines = combined.split("\n").length;
|
|
88
|
+
if (texts.length === 0 || (combined.length <= budget && lines <= 2 * lineBudget))
|
|
89
|
+
return { items: [...items] };
|
|
90
|
+
const headChars = Math.floor(budget / 2);
|
|
91
|
+
const tailChars = budget - headChars;
|
|
92
|
+
const head = combined.slice(0, headChars).split("\n").slice(0, lineBudget).join("\n");
|
|
93
|
+
const tail = tailChars > 0 ? combined.slice(-tailChars).split("\n").slice(-lineBudget).join("\n") : "";
|
|
94
|
+
const removed = combined.length - head.length - tail.length;
|
|
95
|
+
let text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\nTotal output lines: ${combined.split("\n").length}\n\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;
|
|
96
|
+
const spilled = await write("output.txt", combined);
|
|
97
|
+
text +=
|
|
98
|
+
spilled.kind === "saved"
|
|
99
|
+
? `\n\n[Full output: ${spilled.path} (read with offset/limit)]`
|
|
100
|
+
: `\n\n[Could not save the full output: ${spilled.error}]`;
|
|
101
|
+
return {
|
|
102
|
+
items: [{ type: "text", text }, ...items.filter((item) => item.type === "image")],
|
|
103
|
+
...(spilled.kind === "saved" ? { fullOutputPath: spilled.path } : {}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Save each image to a file and put a text item with its path before it; an image shown twice is saved once. */
|
|
107
|
+
async function saveImages(items, write) {
|
|
108
|
+
const labels = new Map();
|
|
109
|
+
const label = async ({ data, mimeType }, index) => {
|
|
110
|
+
const bytes = fromBase64(data);
|
|
111
|
+
const kind = `${mimeType}, ${bytes.length} bytes`;
|
|
112
|
+
// A failed write must not discard the result of a script whose calls already ran: it becomes part of the label.
|
|
113
|
+
const saved = await write(`image-${index}${IMAGE_EXTENSIONS[mimeType] ?? ".bin"}`, bytes);
|
|
114
|
+
return saved.kind === "saved"
|
|
115
|
+
? `[Image saved to ${saved.path} (${kind})]`
|
|
116
|
+
: `[Image (${kind}) could not be saved: ${saved.error}]`;
|
|
117
|
+
};
|
|
118
|
+
const result = await Promise.all(items.map(async (item) => {
|
|
119
|
+
if (item.type !== "image")
|
|
120
|
+
return [item];
|
|
121
|
+
let pending = labels.get(item.data);
|
|
122
|
+
if (pending === undefined) {
|
|
123
|
+
pending = label(item, labels.size + 1);
|
|
124
|
+
labels.set(item.data, pending);
|
|
125
|
+
}
|
|
126
|
+
return [{ type: "text", text: await pending }, item];
|
|
127
|
+
}));
|
|
128
|
+
return result.flat();
|
|
129
|
+
}
|
|
130
|
+
function formatError(result, calls) {
|
|
131
|
+
const { error } = result;
|
|
132
|
+
const head = error.kind === "script"
|
|
133
|
+
? (error.stack ?? `${error.name ?? "Error"}: ${error.message}`)
|
|
134
|
+
: error.kind === "timeout"
|
|
135
|
+
? `Script timed out: ${error.message}`
|
|
136
|
+
: error.kind === "aborted"
|
|
137
|
+
? `Script aborted: ${error.message}`
|
|
138
|
+
: `Script sandbox failed: ${error.message}`;
|
|
139
|
+
const summary = calls.length === 0
|
|
140
|
+
? "No tool calls were made."
|
|
141
|
+
: `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ")}`;
|
|
142
|
+
return `${head}\n\n${summary}`;
|
|
143
|
+
}
|
|
144
|
+
/** The tool result's content for a script's result, and the path of the complete text when it was cut. */
|
|
145
|
+
export async function formatResult(result, options) {
|
|
146
|
+
const output = [...result.output];
|
|
147
|
+
if (result.ok && result.value !== undefined)
|
|
148
|
+
output.push({ type: "text", text: valueText(result.value) });
|
|
149
|
+
const items = formatItems(output);
|
|
150
|
+
if (!result.ok)
|
|
151
|
+
items.push({ type: "text", text: `Script error:\n${formatError(result, options.calls)}` });
|
|
152
|
+
const generated = options.generatedImages;
|
|
153
|
+
if (generated > 0 && !items.some((item) => item.type === "image")) {
|
|
154
|
+
items.push({
|
|
155
|
+
type: "text",
|
|
156
|
+
text: `Note: models.generateImages() returned ${generated} image${generated === 1 ? "" : "s"} that the script did not show. Show each image block of result.output with image(block).`,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
const truncated = await truncate(joinAdjacentText(items), options.maxOutputTokens, options.limits, options.write);
|
|
160
|
+
// After truncation, which joins the text items and moves images after them, so each path stays next to its image.
|
|
161
|
+
const content = joinAdjacentText(await saveImages(truncated.items, options.write));
|
|
162
|
+
const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${(options.wallMs / 1000).toFixed(1)} seconds\nOutput:\n`;
|
|
163
|
+
return {
|
|
164
|
+
content: [{ type: "text", text: header }, ...content],
|
|
165
|
+
...(truncated.fullOutputPath === undefined ? {} : { fullOutputPath: truncated.fullOutputPath }),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=output.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output.js","sourceRoot":"","sources":["../../src/codemode/output.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAYzD,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QACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC;QACrD,GAAG,CAAC,SAAS,CAAC,cAAc,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,SAAS,CAAC,cAAc,EAAE,CAAC;KAC/F,CAAC;AACH,CAAC","sourcesContent":["/**\n * A script's result as the model reads it, copied from the coding agent's code mode: a \"Script completed/failed\"\n * header with the wall time, the script's text items (`==> text N/M <==` when there are several), its `console` lines\n * in one `<console_output>` block, the returned value, and on failure the error with the calls already made. Text past\n * the token budget is cut to its start and end, with the complete text in a temp file; images are saved to temp files\n * too, with their path next to them, because a script has no other way to hand their bytes on.\n */\nimport type { ImageContent, TextContent } from \"@diffra-ai/ai\";\nimport type { CodemodeOutputItem, CodemodeResult } from \"@diffra-ai/codemode/portable\";\nimport { fromBase64 } from \"../tools/image-processor.ts\";\n\ntype Item = TextContent | ImageContent;\n\n/** Writes a file of the result under a fixed name; its path, or why it could not be written. */\nexport type OutputFile = (\n\tname: string,\n\tdata: string | Uint8Array,\n) => Promise<{ readonly kind: \"saved\"; readonly path: string } | { readonly kind: \"failed\"; readonly error: string }>;\n\n/** The tool's output limits, which the Harness enforces by cutting without a spill file: results stay inside them. */\ntype Limits = { readonly maxBytes: number; readonly maxLines: number };\n/** Lines of the result besides the script's text: the header, markers, notes. */\nconst LINE_MARGIN = 100;\n\n/** Default token budget for script output. */\nexport const DEFAULT_MAX_OUTPUT_TOKENS = 10_000;\n/** Characters per token when estimating. */\nconst CHARS_PER_TOKEN = 4;\n\n/** File extensions of the image types `image()` accepts. */\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n\t\"image/png\": \".png\",\n\t\"image/jpeg\": \".jpg\",\n\t\"image/gif\": \".gif\",\n\t\"image/webp\": \".webp\",\n};\n\n/** Like the script's `text()`: strings as is, other values as compact JSON. */\nfunction valueText(value: unknown): string {\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value) ?? String(value);\n}\n\n/**\n * Lay out the script's output so the model can tell items apart: with more than one text item, each starts with a\n * `==> text N/M <==` line; `console` lines follow all other output in one `<console_output>` block.\n */\nfunction formatItems(output: readonly CodemodeOutputItem[]): Item[] {\n\tconst total = output.filter((item) => item.type === \"text\" && !item.console).length;\n\tconst items: Item[] = [];\n\tconst consoleLines: string[] = [];\n\tlet index = 0;\n\tfor (const item of output) {\n\t\tif (item.type === \"image\") items.push(item);\n\t\telse if (item.console) consoleLines.push(item.text);\n\t\telse {\n\t\t\tindex++;\n\t\t\titems.push({ type: \"text\", text: total > 1 ? `==> text ${index}/${total} <==\\n${item.text}` : item.text });\n\t\t}\n\t}\n\tif (consoleLines.length > 0) {\n\t\titems.push({ type: \"text\", text: `<console_output>\\n${consoleLines.join(\"\\n\")}\\n</console_output>` });\n\t}\n\treturn items;\n}\n\n/**\n * Join adjacent text items into one, each part starting on its own line. The separator check looks at the last\n * non-empty part, not the joined text: reading the end of a growing concatenation makes V8 copy it on every item, which\n * is quadratic.\n */\nfunction joinAdjacentText(items: readonly Item[]): Item[] {\n\tconst joined: Item[] = [];\n\tlet parts: string[] = [];\n\tlet lastPart = \"\";\n\tconst flush = () => {\n\t\tif (parts.length > 0) joined.push({ type: \"text\", text: parts.join(\"\") });\n\t\tparts = [];\n\t\tlastPart = \"\";\n\t};\n\tfor (const item of items) {\n\t\tif (item.type !== \"text\") {\n\t\t\tflush();\n\t\t\tjoined.push(item);\n\t\t\tcontinue;\n\t\t}\n\t\tif (lastPart !== \"\" && !lastPart.endsWith(\"\\n\")) {\n\t\t\tparts.push(\"\\n\");\n\t\t\tlastPart = \"\\n\";\n\t\t}\n\t\tparts.push(item.text);\n\t\tif (item.text !== \"\") lastPart = item.text;\n\t}\n\tflush();\n\treturn joined;\n}\n\n/**\n * Apply the token budget: when the combined text exceeds it, the text items become one item that keeps the start and\n * end of the text, and images follow it. The complete text is written to a temp file.\n */\nasync function truncate(\n\titems: readonly Item[],\n\tmaxTokens: number,\n\tlimits: Limits,\n\twrite: OutputFile,\n): Promise<{ items: Item[]; fullOutputPath?: string }> {\n\tconst texts = items.filter((item): item is TextContent => item.type === \"text\").map((item) => item.text);\n\tconst combined = texts.join(\"\\n\");\n\t// Within the limits too: a UTF-16 unit is at most 3 UTF-8 bytes, and the rest of the result is a few short lines.\n\tconst budget = Math.min(maxTokens * CHARS_PER_TOKEN, Math.floor(limits.maxBytes / 4));\n\tconst lineBudget = Math.floor((limits.maxLines - LINE_MARGIN) / 2);\n\tconst lines = combined.split(\"\\n\").length;\n\tif (texts.length === 0 || (combined.length <= budget && lines <= 2 * lineBudget)) return { items: [...items] };\n\tconst headChars = Math.floor(budget / 2);\n\tconst tailChars = budget - headChars;\n\tconst head = combined.slice(0, headChars).split(\"\\n\").slice(0, lineBudget).join(\"\\n\");\n\tconst tail = tailChars > 0 ? combined.slice(-tailChars).split(\"\\n\").slice(-lineBudget).join(\"\\n\") : \"\";\n\tconst removed = combined.length - head.length - tail.length;\n\tlet text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\\nTotal output lines: ${combined.split(\"\\n\").length}\\n\\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;\n\tconst spilled = await write(\"output.txt\", combined);\n\ttext +=\n\t\tspilled.kind === \"saved\"\n\t\t\t? `\\n\\n[Full output: ${spilled.path} (read with offset/limit)]`\n\t\t\t: `\\n\\n[Could not save the full output: ${spilled.error}]`;\n\treturn {\n\t\titems: [{ type: \"text\", text }, ...items.filter((item) => item.type === \"image\")],\n\t\t...(spilled.kind === \"saved\" ? { fullOutputPath: spilled.path } : {}),\n\t};\n}\n\n/** Save each image to a file and put a text item with its path before it; an image shown twice is saved once. */\nasync function saveImages(items: readonly Item[], write: OutputFile): Promise<Item[]> {\n\tconst labels = new Map<string, Promise<string>>();\n\tconst label = async ({ data, mimeType }: ImageContent, index: number): Promise<string> => {\n\t\tconst bytes = fromBase64(data);\n\t\tconst kind = `${mimeType}, ${bytes.length} bytes`;\n\t\t// A failed write must not discard the result of a script whose calls already ran: it becomes part of the label.\n\t\tconst saved = await write(`image-${index}${IMAGE_EXTENSIONS[mimeType] ?? \".bin\"}`, bytes);\n\t\treturn saved.kind === \"saved\"\n\t\t\t? `[Image saved to ${saved.path} (${kind})]`\n\t\t\t: `[Image (${kind}) could not be saved: ${saved.error}]`;\n\t};\n\tconst result = await Promise.all(\n\t\titems.map(async (item): Promise<Item[]> => {\n\t\t\tif (item.type !== \"image\") return [item];\n\t\t\tlet pending = labels.get(item.data);\n\t\t\tif (pending === undefined) {\n\t\t\t\tpending = label(item, labels.size + 1);\n\t\t\t\tlabels.set(item.data, pending);\n\t\t\t}\n\t\t\treturn [{ type: \"text\", text: await pending }, item];\n\t\t}),\n\t);\n\treturn result.flat();\n}\n\nfunction formatError(\n\tresult: Extract<CodemodeResult, { ok: false }>,\n\tcalls: readonly { name: string; status: string }[],\n) {\n\tconst { error } = result;\n\tconst head =\n\t\terror.kind === \"script\"\n\t\t\t? (error.stack ?? `${error.name ?? \"Error\"}: ${error.message}`)\n\t\t\t: error.kind === \"timeout\"\n\t\t\t\t? `Script timed out: ${error.message}`\n\t\t\t\t: error.kind === \"aborted\"\n\t\t\t\t\t? `Script aborted: ${error.message}`\n\t\t\t\t\t: `Script sandbox failed: ${error.message}`;\n\tconst summary =\n\t\tcalls.length === 0\n\t\t\t? \"No tool calls were made.\"\n\t\t\t: `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(\", \")}`;\n\treturn `${head}\\n\\n${summary}`;\n}\n\n/** The tool result's content for a script's result, and the path of the complete text when it was cut. */\nexport async function formatResult(\n\tresult: CodemodeResult,\n\toptions: {\n\t\t/** Images `models.generateImages()` returned; when the script showed none, the result says so. */\n\t\treadonly generatedImages: number;\n\t\treadonly wallMs: number;\n\t\treadonly maxOutputTokens: number;\n\t\treadonly calls: readonly { name: string; status: string }[];\n\t\treadonly limits: Limits;\n\t\treadonly write: OutputFile;\n\t},\n): Promise<{ content: Item[]; fullOutputPath?: string }> {\n\tconst output = [...result.output];\n\tif (result.ok && result.value !== undefined) output.push({ type: \"text\", text: valueText(result.value) });\n\tconst items = formatItems(output);\n\tif (!result.ok) items.push({ type: \"text\", text: `Script error:\\n${formatError(result, options.calls)}` });\n\tconst generated = options.generatedImages;\n\tif (generated > 0 && !items.some((item) => item.type === \"image\")) {\n\t\titems.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: `Note: models.generateImages() returned ${generated} image${generated === 1 ? \"\" : \"s\"} that the script did not show. Show each image block of result.output with image(block).`,\n\t\t});\n\t}\n\tconst truncated = await truncate(joinAdjacentText(items), options.maxOutputTokens, options.limits, options.write);\n\t// After truncation, which joins the text items and moves images after them, so each path stays next to its image.\n\tconst content = joinAdjacentText(await saveImages(truncated.items, options.write));\n\tconst header = `${result.ok ? \"Script completed\" : \"Script failed\"}\\nWall time ${(options.wallMs / 1000).toFixed(1)} seconds\\nOutput:\\n`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: header }, ...content],\n\t\t...(truncated.fullOutputPath === undefined ? {} : { fullOutputPath: truncated.fullOutputPath }),\n\t};\n}\n"]}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Op } from "@diffra-ai/chord/delta";
|
|
2
|
+
import { type JsonValue } from "@diffra-ai/chord/json";
|
|
3
|
+
import type { CheckpointInfo, CommonDocDefinition, ConversationDocFamilyToken, ConversationDocToken, DocumentAddress, DocumentCreate, DocumentId, DocumentRecord, DocumentSemantics, JsonObject, LatestConversationSemantics, RewindableConversationDocFamilyToken, RewindableConversationDocToken, RewindableConversationSemantics, SessionDocFamilyToken, SessionDocToken, StoredDocument, TaskDocFamilyToken, TaskDocToken } from "./types.ts";
|
|
4
|
+
type FamilyInput<T extends JsonObject, I extends JsonValue> = Omit<CommonDocDefinition<T>, "initial"> & {
|
|
5
|
+
readonly family: true;
|
|
6
|
+
initial(seed: I): T;
|
|
7
|
+
};
|
|
8
|
+
/** Define a Session-scoped singleton document. */
|
|
9
|
+
export declare function defineDoc<T extends JsonObject>(definition: CommonDocDefinition<T> & {
|
|
10
|
+
readonly scope: "session";
|
|
11
|
+
}): SessionDocToken<T>;
|
|
12
|
+
/** Define a latest-only conversation singleton document. */
|
|
13
|
+
export declare function defineDoc<T extends JsonObject>(definition: CommonDocDefinition<T> & LatestConversationSemantics): ConversationDocToken<T>;
|
|
14
|
+
/** Define a rewindable conversation singleton document. */
|
|
15
|
+
export declare function defineDoc<T extends JsonObject>(definition: CommonDocDefinition<T> & RewindableConversationSemantics): RewindableConversationDocToken<T>;
|
|
16
|
+
/** Define a task-scoped singleton document. */
|
|
17
|
+
export declare function defineDoc<T extends JsonObject>(definition: CommonDocDefinition<T> & {
|
|
18
|
+
readonly scope: "task";
|
|
19
|
+
}): TaskDocToken<T>;
|
|
20
|
+
/** Define a Session-scoped document family. */
|
|
21
|
+
export declare function defineDocFamily<T extends JsonObject, I extends JsonValue>(definition: FamilyInput<T, I> & {
|
|
22
|
+
readonly scope: "session";
|
|
23
|
+
}): SessionDocFamilyToken<T, I>;
|
|
24
|
+
/** Define a latest-only conversation document family. */
|
|
25
|
+
export declare function defineDocFamily<T extends JsonObject, I extends JsonValue>(definition: FamilyInput<T, I> & LatestConversationSemantics): ConversationDocFamilyToken<T, I>;
|
|
26
|
+
/** Define a rewindable conversation document family. */
|
|
27
|
+
export declare function defineDocFamily<T extends JsonObject, I extends JsonValue>(definition: FamilyInput<T, I> & RewindableConversationSemantics): RewindableConversationDocFamilyToken<T, I>;
|
|
28
|
+
/** Define a task-scoped document family. */
|
|
29
|
+
export declare function defineDocFamily<T extends JsonObject, I extends JsonValue>(definition: FamilyInput<T, I> & {
|
|
30
|
+
readonly scope: "task";
|
|
31
|
+
}): TaskDocFamilyToken<T, I>;
|
|
32
|
+
/** Erased definition shape used by the Session after overload resolution. */
|
|
33
|
+
export type AnyDocDefinition = DocumentSemantics & {
|
|
34
|
+
readonly kind: string;
|
|
35
|
+
readonly version: number;
|
|
36
|
+
readonly family?: true;
|
|
37
|
+
initial(seed?: JsonValue): JsonObject;
|
|
38
|
+
migrate?(value: JsonObject, fromVersion: number): JsonObject;
|
|
39
|
+
checkpointWhen(value: Readonly<JsonObject>, ops: readonly Op[], info: CheckpointInfo): boolean;
|
|
40
|
+
};
|
|
41
|
+
/** Erased singleton or family token. */
|
|
42
|
+
export type AnyDocToken = {
|
|
43
|
+
readonly definition: AnyDocDefinition;
|
|
44
|
+
};
|
|
45
|
+
/** Logical address plus its string identity for maps. */
|
|
46
|
+
export type ResolvedAddress = {
|
|
47
|
+
readonly address: DocumentAddress;
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly nextArgument: number;
|
|
50
|
+
};
|
|
51
|
+
/** Resolve an overloaded argument list and return the index after the owner and family key. */
|
|
52
|
+
export declare function resolveAddress(definition: AnyDocDefinition, args: readonly unknown[]): ResolvedAddress;
|
|
53
|
+
/** Stable string identity of one logical address. */
|
|
54
|
+
export declare function addressId(address: DocumentAddress): string;
|
|
55
|
+
/** Build the storage create record for a new incarnation at an address. */
|
|
56
|
+
export declare function documentCreate(definition: AnyDocDefinition, address: DocumentAddress, id: DocumentId): DocumentCreate;
|
|
57
|
+
/** Reject typed access whose token disagrees with the persisted scope, history, or fork semantics. */
|
|
58
|
+
export declare function checkRecordScope(definition: AnyDocDefinition, record: DocumentCreate | DocumentRecord): void;
|
|
59
|
+
/** Reject typed access to a stored version the supplied definition cannot use. */
|
|
60
|
+
export declare function checkRecordVersion(definition: AnyDocDefinition, record: DocumentCreate | DocumentRecord, version: number): void;
|
|
61
|
+
/** Validate and materialize a detached stored value for typed access. */
|
|
62
|
+
export declare function materializeDocument(definition: AnyDocDefinition, stored: StoredDocument): JsonObject;
|
|
63
|
+
/** Validate and materialize one detached value before its first persisted incarnation. */
|
|
64
|
+
export declare function materializeDocumentValue(definition: AnyDocDefinition, record: DocumentCreate | DocumentRecord, version: number, value: JsonObject): JsonObject;
|
|
65
|
+
export {};
|
|
66
|
+
//# sourceMappingURL=documents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../src/documents.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,KAAK,EACX,cAAc,EACd,mBAAmB,EACnB,0BAA0B,EAC1B,oBAAoB,EAMpB,eAAe,EACf,cAAc,EACd,UAAU,EACV,cAAc,EACd,iBAAiB,EAEjB,UAAU,EACV,2BAA2B,EAC3B,oCAAoC,EACpC,8BAA8B,EAC9B,+BAA+B,EAC/B,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,YAAY,EAEZ,MAAM,YAAY,CAAC;AAEpB,KAAK,WAAW,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC,SAAS,SAAS,IAAI,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,GAAG;IACvG,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC;IACtB,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;CACpB,CAAC;AAEF,kDAAkD;AAClD,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAC7C,UAAU,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAA;CAAE,GAChE,eAAe,CAAC,CAAC,CAAC,CAAC;AACtB,4DAA4D;AAC5D,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAC7C,UAAU,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,2BAA2B,GAC9D,oBAAoB,CAAC,CAAC,CAAC,CAAC;AAC3B,2DAA2D;AAC3D,wBAAgB,SAAS,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