@dxos/assistant 0.8.2-main.fbd8ed0 → 0.8.2-staging.4d6ad0f
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/dist/lib/browser/index.mjs +1983 -64
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +1976 -63
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +1984 -64
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/{src/bin → bin}/chat.d.ts.map +1 -1
- package/dist/types/src/blueprint/blueprint.d.ts +79 -0
- package/dist/types/src/blueprint/blueprint.d.ts.map +1 -0
- package/dist/types/src/blueprint/blueprint.test.d.ts +2 -0
- package/dist/types/src/blueprint/blueprint.test.d.ts.map +1 -0
- package/dist/types/src/blueprint/index.d.ts +4 -0
- package/dist/types/src/blueprint/index.d.ts.map +1 -0
- package/dist/types/src/blueprint/logger.d.ts +3 -0
- package/dist/types/src/blueprint/logger.d.ts.map +1 -0
- package/dist/types/src/{ai-service/parser.d.ts → blueprint/machine.d.ts} +46 -68
- package/dist/types/src/blueprint/machine.d.ts.map +1 -0
- package/dist/types/src/blueprint/test-data.d.ts +3 -0
- package/dist/types/src/blueprint/test-data.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +4 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +2 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts +2 -0
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +210 -0
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +2 -0
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts +3 -0
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +14 -0
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.test.d.ts +2 -0
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction.d.ts +242 -0
- package/dist/types/src/extraction/extraction.d.ts.map +1 -0
- package/dist/types/src/extraction/index.d.ts +5 -0
- package/dist/types/src/extraction/index.d.ts.map +1 -0
- package/dist/types/src/extraction/quotes.d.ts +15 -0
- package/dist/types/src/extraction/quotes.d.ts.map +1 -0
- package/dist/types/src/extraction/quotes.test.d.ts +2 -0
- package/dist/types/src/extraction/quotes.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +4 -2
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/research/exa.d.ts +7 -0
- package/dist/types/src/research/exa.d.ts.map +1 -0
- package/dist/types/src/research/graph.d.ts +39 -0
- package/dist/types/src/research/graph.d.ts.map +1 -0
- package/dist/types/src/research/graph.test.d.ts +2 -0
- package/dist/types/src/research/graph.test.d.ts.map +1 -0
- package/dist/types/src/research/index.d.ts +4 -0
- package/dist/types/src/research/index.d.ts.map +1 -0
- package/dist/types/src/research/research.d.ts +10 -0
- package/dist/types/src/research/research.d.ts.map +1 -0
- package/dist/types/src/research/research.test.d.ts.map +1 -0
- package/dist/types/src/session/index.d.ts +0 -1
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +47 -22
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/version-pin.d.ts +3 -4
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/summarization/summarization.test.d.ts +2 -0
- package/dist/types/src/summarization/summarization.test.d.ts.map +1 -0
- package/dist/types/src/testing/exa-search-1748337321991.d.ts +38 -0
- package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +1 -0
- package/dist/types/src/testing/exa-search-1748337331526.d.ts +37 -0
- package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +1 -0
- package/dist/types/src/testing/exa-search-1748337344119.d.ts +58 -0
- package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +2 -7
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/types.d.ts +3 -0
- package/dist/types/src/types.d.ts.map +1 -0
- package/package.json +22 -38
- package/src/blueprint/blueprint.test.ts +142 -0
- package/src/blueprint/blueprint.ts +95 -0
- package/src/blueprint/index.ts +7 -0
- package/src/blueprint/logger.ts +66 -0
- package/src/blueprint/machine.ts +208 -0
- package/src/blueprint/test-data.ts +55 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +95 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +64 -0
- package/src/extraction/extraction-llm-function/index.ts +5 -0
- package/src/extraction/extraction-llm-function/instructions.tpl +28 -0
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +115 -0
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +54 -0
- package/src/extraction/extraction-ner-function/index.ts +6 -0
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +94 -0
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +97 -0
- package/src/extraction/extraction.ts +75 -0
- package/src/extraction/index.ts +8 -0
- package/src/extraction/quotes.test.ts +27 -0
- package/src/extraction/quotes.ts +57 -0
- package/src/index.ts +4 -4
- package/src/research/exa.ts +100 -0
- package/src/research/graph.test.ts +15 -0
- package/src/research/graph.ts +291 -0
- package/src/research/index.ts +7 -0
- package/src/research/instructions-research.tpl +97 -0
- package/src/research/research.test.ts +189 -0
- package/src/research/research.ts +89 -0
- package/src/session/index.ts +0 -1
- package/src/session/session.test.ts +7 -7
- package/src/session/session.ts +46 -19
- package/src/session/version-pin.ts +2 -3
- package/src/summarization/summarization.test.ts +216 -0
- package/src/testing/exa-search-1748337321991.ts +131 -0
- package/src/testing/exa-search-1748337331526.ts +144 -0
- package/src/testing/exa-search-1748337344119.ts +133 -0
- package/src/testing/index.ts +8 -8
- package/src/types.ts +8 -0
- package/src/typings.d.ts +8 -0
- package/dist/lib/browser/chunk-B4HAWUFW.mjs +0 -2786
- package/dist/lib/browser/chunk-B4HAWUFW.mjs.map +0 -7
- package/dist/lib/browser/testing/index.mjs +0 -658
- package/dist/lib/browser/testing/index.mjs.map +0 -7
- package/dist/lib/node/chunk-NOB7CIIC.cjs +0 -2791
- package/dist/lib/node/chunk-NOB7CIIC.cjs.map +0 -7
- package/dist/lib/node/testing/index.cjs +0 -672
- package/dist/lib/node/testing/index.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-SAWYU3V5.mjs +0 -2788
- package/dist/lib/node-esm/chunk-SAWYU3V5.mjs.map +0 -7
- package/dist/lib/node-esm/testing/index.mjs +0 -659
- package/dist/lib/node-esm/testing/index.mjs.map +0 -7
- package/dist/types/src/ai-service/client.test.d.ts +0 -2
- package/dist/types/src/ai-service/client.test.d.ts.map +0 -1
- package/dist/types/src/ai-service/defs.d.ts +0 -9
- package/dist/types/src/ai-service/defs.d.ts.map +0 -1
- package/dist/types/src/ai-service/edge-client.d.ts +0 -18
- package/dist/types/src/ai-service/edge-client.d.ts.map +0 -1
- package/dist/types/src/ai-service/index.d.ts +0 -10
- package/dist/types/src/ai-service/index.d.ts.map +0 -1
- package/dist/types/src/ai-service/message-collector.d.ts +0 -82
- package/dist/types/src/ai-service/message-collector.d.ts.map +0 -1
- package/dist/types/src/ai-service/ollama-client.d.ts +0 -43
- package/dist/types/src/ai-service/ollama-client.d.ts.map +0 -1
- package/dist/types/src/ai-service/parser.d.ts.map +0 -1
- package/dist/types/src/ai-service/service.d.ts +0 -25
- package/dist/types/src/ai-service/service.d.ts.map +0 -1
- package/dist/types/src/ai-service/stream.d.ts +0 -40
- package/dist/types/src/ai-service/stream.d.ts.map +0 -1
- package/dist/types/src/ai-service/stream.test.d.ts +0 -2
- package/dist/types/src/ai-service/stream.test.d.ts.map +0 -1
- package/dist/types/src/ai-service/testing/index.d.ts +0 -3
- package/dist/types/src/ai-service/testing/index.d.ts.map +0 -1
- package/dist/types/src/ai-service/testing/mock.d.ts +0 -11
- package/dist/types/src/ai-service/testing/mock.d.ts.map +0 -1
- package/dist/types/src/ai-service/testing/test-stream.d.ts +0 -7
- package/dist/types/src/ai-service/testing/test-stream.d.ts.map +0 -1
- package/dist/types/src/ai-service/transform.d.ts +0 -27
- package/dist/types/src/ai-service/transform.d.ts.map +0 -1
- package/dist/types/src/ai-service/types.d.ts +0 -210
- package/dist/types/src/ai-service/types.d.ts.map +0 -1
- package/dist/types/src/ai-service/util/index.d.ts +0 -2
- package/dist/types/src/ai-service/util/index.d.ts.map +0 -1
- package/dist/types/src/ai-service/util/sse.d.ts +0 -39
- package/dist/types/src/ai-service/util/sse.d.ts.map +0 -1
- package/dist/types/src/experimental/conversation/conversation.d.ts +0 -61
- package/dist/types/src/experimental/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/experimental/conversation/conversation.test.d.ts +0 -2
- package/dist/types/src/experimental/conversation/conversation.test.d.ts.map +0 -1
- package/dist/types/src/experimental/conversation/index.d.ts +0 -2
- package/dist/types/src/experimental/conversation/index.d.ts.map +0 -1
- package/dist/types/src/experimental/conversation/types.d.ts +0 -78
- package/dist/types/src/experimental/conversation/types.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/ast.d.ts +0 -56
- package/dist/types/src/experimental/cypher/ast.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/combinators.d.ts +0 -14
- package/dist/types/src/experimental/cypher/combinators.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/combinators.test.d.ts +0 -2
- package/dist/types/src/experimental/cypher/combinators.test.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/echo-data-source.d.ts +0 -16
- package/dist/types/src/experimental/cypher/echo-data-source.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/execution-plan.d.ts +0 -49
- package/dist/types/src/experimental/cypher/execution-plan.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/execution-plan.test.d.ts +0 -2
- package/dist/types/src/experimental/cypher/execution-plan.test.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/index.d.ts +0 -5
- package/dist/types/src/experimental/cypher/index.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/parjs.d.ts +0 -4
- package/dist/types/src/experimental/cypher/parjs.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/parser.d.ts +0 -6
- package/dist/types/src/experimental/cypher/parser.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/query-executor.d.ts +0 -26
- package/dist/types/src/experimental/cypher/query-executor.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/query-executor.test.d.ts +0 -2
- package/dist/types/src/experimental/cypher/query-executor.test.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/schema.d.ts +0 -12
- package/dist/types/src/experimental/cypher/schema.d.ts.map +0 -1
- package/dist/types/src/experimental/cypher/schema.test.d.ts +0 -2
- package/dist/types/src/experimental/cypher/schema.test.d.ts.map +0 -1
- package/dist/types/src/experimental/index.d.ts +0 -3
- package/dist/types/src/experimental/index.d.ts.map +0 -1
- package/dist/types/src/experimental/ner/ner.test.d.ts +0 -2
- package/dist/types/src/experimental/ner/ner.test.d.ts.map +0 -1
- package/dist/types/src/experimental/research/exa.d.ts +0 -6
- package/dist/types/src/experimental/research/exa.d.ts.map +0 -1
- package/dist/types/src/experimental/research/research.test.d.ts.map +0 -1
- package/dist/types/src/session/tools.d.ts +0 -18
- package/dist/types/src/session/tools.d.ts.map +0 -1
- package/dist/types/src/testing/artifacts.test.d.ts +0 -1
- package/dist/types/src/testing/artifacts.test.d.ts.map +0 -1
- package/dist/types/src/testing/data.d.ts +0 -2
- package/dist/types/src/testing/data.d.ts.map +0 -1
- package/dist/types/src/testing/defs.d.ts +0 -5
- package/dist/types/src/testing/defs.d.ts.map +0 -1
- package/dist/types/src/testing/logger.d.ts +0 -12
- package/dist/types/src/testing/logger.d.ts.map +0 -1
- package/dist/types/src/testing/object-extraction.test.d.ts +0 -1
- package/dist/types/src/testing/object-extraction.test.d.ts.map +0 -1
- package/dist/types/src/testing/ollama.d.ts +0 -6
- package/dist/types/src/testing/ollama.d.ts.map +0 -1
- package/dist/types/src/testing/printer.d.ts +0 -6
- package/dist/types/src/testing/printer.d.ts.map +0 -1
- package/dist/types/src/testing/query-promts.d.ts +0 -5
- package/dist/types/src/testing/query-promts.d.ts.map +0 -1
- package/dist/types/src/testing/query.test.d.ts +0 -2
- package/dist/types/src/testing/query.test.d.ts.map +0 -1
- package/dist/types/src/testing/test-data.d.ts +0 -29
- package/dist/types/src/testing/test-data.d.ts.map +0 -1
- package/dist/types/src/testing/test-schema.d.ts +0 -52
- package/dist/types/src/testing/test-schema.d.ts.map +0 -1
- package/dist/types/src/util/index.d.ts +0 -2
- package/dist/types/src/util/index.d.ts.map +0 -1
- package/dist/types/src/util/trim.d.ts +0 -5
- package/dist/types/src/util/trim.d.ts.map +0 -1
- package/src/ai-service/client.test.ts +0 -247
- package/src/ai-service/defs.ts +0 -39
- package/src/ai-service/edge-client.ts +0 -60
- package/src/ai-service/index.ts +0 -13
- package/src/ai-service/message-collector.ts +0 -84
- package/src/ai-service/ollama-client.ts +0 -506
- package/src/ai-service/parser.ts +0 -369
- package/src/ai-service/service.ts +0 -31
- package/src/ai-service/stream.test.ts +0 -125
- package/src/ai-service/stream.ts +0 -118
- package/src/ai-service/testing/index.ts +0 -6
- package/src/ai-service/testing/mock.ts +0 -30
- package/src/ai-service/testing/test-stream.ts +0 -93
- package/src/ai-service/transform.ts +0 -121
- package/src/ai-service/types.ts +0 -112
- package/src/ai-service/util/index.ts +0 -5
- package/src/ai-service/util/sse.ts +0 -341
- package/src/bin/chat.ts +0 -79
- package/src/experimental/conversation/conversation.test.ts +0 -73
- package/src/experimental/conversation/conversation.ts +0 -142
- package/src/experimental/conversation/index.ts +0 -5
- package/src/experimental/conversation/types.ts +0 -126
- package/src/experimental/cypher/ast.ts +0 -75
- package/src/experimental/cypher/combinators.test.ts +0 -137
- package/src/experimental/cypher/combinators.ts +0 -148
- package/src/experimental/cypher/echo-data-source.ts +0 -105
- package/src/experimental/cypher/execution-plan.test.ts +0 -44
- package/src/experimental/cypher/execution-plan.ts +0 -208
- package/src/experimental/cypher/index.ts +0 -8
- package/src/experimental/cypher/parjs-shims.d.ts +0 -10
- package/src/experimental/cypher/parjs.ts +0 -10
- package/src/experimental/cypher/parser.ts +0 -19
- package/src/experimental/cypher/query-executor.test.ts +0 -47
- package/src/experimental/cypher/query-executor.ts +0 -145
- package/src/experimental/cypher/schema.test.ts +0 -17
- package/src/experimental/cypher/schema.ts +0 -86
- package/src/experimental/index.ts +0 -6
- package/src/experimental/ner/ner.test.ts +0 -163
- package/src/experimental/research/exa.ts +0 -38
- package/src/experimental/research/instructions.tpl +0 -64
- package/src/experimental/research/research.test.ts +0 -263
- package/src/session/tools.ts +0 -117
- package/src/testing/artifacts.test.ts +0 -182
- package/src/testing/data.ts +0 -13
- package/src/testing/defs.ts +0 -9
- package/src/testing/logger.ts +0 -129
- package/src/testing/object-extraction.test.ts +0 -71
- package/src/testing/ollama.ts +0 -15
- package/src/testing/printer.ts +0 -41
- package/src/testing/query-promts.ts +0 -75
- package/src/testing/query.test.ts +0 -88
- package/src/testing/test-data.ts +0 -379
- package/src/testing/test-schema.ts +0 -79
- package/src/util/index.ts +0 -5
- package/src/util/trim.ts +0 -15
- package/vendor/parjs-browser.mjs +0 -4
- package/vendor/parjs-default.mjs +0 -8
- /package/dist/types/{src/bin → bin}/chat.d.ts +0 -0
- /package/dist/types/src/{experimental/research → research}/research.test.d.ts +0 -0
|
@@ -1,2788 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
|
|
2
|
-
|
|
3
|
-
// packages/experimental/assistant/src/ai-service/defs.ts
|
|
4
|
-
var DEFAULT_EDGE_MODEL = "@anthropic/claude-3-5-sonnet-20241022";
|
|
5
|
-
var DEFAULT_EDGE_MODELS = [
|
|
6
|
-
// AI Gateway.
|
|
7
|
-
// https://developers.cloudflare.com/ai-gateway
|
|
8
|
-
"@anthropic/claude-3-5-haiku-20241022",
|
|
9
|
-
"@anthropic/claude-3-5-sonnet-20241022",
|
|
10
|
-
"@anthropic/claude-3-7-sonnet-20250219",
|
|
11
|
-
// Workers AI.
|
|
12
|
-
// https://developers.cloudflare.com/workers-ai/models
|
|
13
|
-
"@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
|
|
14
|
-
"@hf/nousresearch/hermes-2-pro-mistral-7b",
|
|
15
|
-
"@ollama/llama-3-1-nemotron-70b-instruct",
|
|
16
|
-
"@ollama/llama-3-1-nemotron-mini-4b-instruct",
|
|
17
|
-
"@ollama/llama-3-2-3b"
|
|
18
|
-
];
|
|
19
|
-
var DEFAULT_OLLAMA_ENDPOINT = "http://localhost:11434";
|
|
20
|
-
var DEFAULT_OLLAMA_MODEL = "llama3.2:1b";
|
|
21
|
-
var DEFAULT_OLLAMA_MODELS = [
|
|
22
|
-
//
|
|
23
|
-
"llama3.2:1b",
|
|
24
|
-
"llama3:70b",
|
|
25
|
-
"deepseek-r1:latest"
|
|
26
|
-
];
|
|
27
|
-
|
|
28
|
-
// packages/experimental/assistant/src/ai-service/stream.ts
|
|
29
|
-
import { Trigger } from "@dxos/async";
|
|
30
|
-
import { log } from "@dxos/log";
|
|
31
|
-
|
|
32
|
-
// packages/experimental/assistant/src/ai-service/util/sse.ts
|
|
33
|
-
async function* iterSSEMessages(response, controller) {
|
|
34
|
-
if (!response.body) {
|
|
35
|
-
controller.abort();
|
|
36
|
-
throw new Error("Attempted to iterate over a response with no body");
|
|
37
|
-
}
|
|
38
|
-
const sseDecoder = new SSEDecoder();
|
|
39
|
-
const lineDecoder = new LineDecoder();
|
|
40
|
-
const iter = readableStreamAsyncIterable(response.body);
|
|
41
|
-
for await (const sseChunk of iterSSEChunks(iter)) {
|
|
42
|
-
for (const line of lineDecoder.decode(sseChunk)) {
|
|
43
|
-
const sse = sseDecoder.decode(line);
|
|
44
|
-
if (sse) {
|
|
45
|
-
yield sse;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
for (const line of lineDecoder.flush()) {
|
|
50
|
-
const sse = sseDecoder.decode(line);
|
|
51
|
-
if (sse) {
|
|
52
|
-
yield sse;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
async function* iterSSEChunks(iterator) {
|
|
57
|
-
let data = new Uint8Array();
|
|
58
|
-
for await (const chunk of iterator) {
|
|
59
|
-
if (chunk == null) {
|
|
60
|
-
continue;
|
|
61
|
-
}
|
|
62
|
-
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
|
|
63
|
-
const newData = new Uint8Array(data.length + binaryChunk.length);
|
|
64
|
-
newData.set(data);
|
|
65
|
-
newData.set(binaryChunk, data.length);
|
|
66
|
-
data = newData;
|
|
67
|
-
let patternIndex;
|
|
68
|
-
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
69
|
-
yield data.slice(0, patternIndex);
|
|
70
|
-
data = data.slice(patternIndex);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
if (data.length > 0) {
|
|
74
|
-
yield data;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
var findDoubleNewlineIndex = (buffer) => {
|
|
78
|
-
const newline = 10;
|
|
79
|
-
const carriage = 13;
|
|
80
|
-
for (let i = 0; i < buffer.length - 2; i++) {
|
|
81
|
-
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
82
|
-
return i + 2;
|
|
83
|
-
}
|
|
84
|
-
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
85
|
-
return i + 2;
|
|
86
|
-
}
|
|
87
|
-
if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
|
|
88
|
-
return i + 4;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return -1;
|
|
92
|
-
};
|
|
93
|
-
var SSEDecoder = class {
|
|
94
|
-
constructor() {
|
|
95
|
-
this.event = null;
|
|
96
|
-
this.data = [];
|
|
97
|
-
this.chunks = [];
|
|
98
|
-
}
|
|
99
|
-
decode(line) {
|
|
100
|
-
if (line.endsWith("\r")) {
|
|
101
|
-
line = line.substring(0, line.length - 1);
|
|
102
|
-
}
|
|
103
|
-
if (!line) {
|
|
104
|
-
if (!this.event && !this.data.length) {
|
|
105
|
-
return null;
|
|
106
|
-
}
|
|
107
|
-
const sse = {
|
|
108
|
-
event: this.event,
|
|
109
|
-
data: this.data.join("\n"),
|
|
110
|
-
raw: this.chunks
|
|
111
|
-
};
|
|
112
|
-
this.event = null;
|
|
113
|
-
this.data = [];
|
|
114
|
-
this.chunks = [];
|
|
115
|
-
return sse;
|
|
116
|
-
}
|
|
117
|
-
this.chunks.push(line);
|
|
118
|
-
if (line.startsWith(":")) {
|
|
119
|
-
return null;
|
|
120
|
-
}
|
|
121
|
-
let [fieldname, _, value] = partition(line, ":");
|
|
122
|
-
if (value.startsWith(" ")) {
|
|
123
|
-
value = value.substring(1);
|
|
124
|
-
}
|
|
125
|
-
if (fieldname === "event") {
|
|
126
|
-
this.event = value;
|
|
127
|
-
} else if (fieldname === "data") {
|
|
128
|
-
this.data.push(value);
|
|
129
|
-
}
|
|
130
|
-
return null;
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
var partition = (str, delimiter) => {
|
|
134
|
-
const index = str.indexOf(delimiter);
|
|
135
|
-
if (index !== -1) {
|
|
136
|
-
return [
|
|
137
|
-
str.substring(0, index),
|
|
138
|
-
delimiter,
|
|
139
|
-
str.substring(index + delimiter.length)
|
|
140
|
-
];
|
|
141
|
-
}
|
|
142
|
-
return [
|
|
143
|
-
str,
|
|
144
|
-
"",
|
|
145
|
-
""
|
|
146
|
-
];
|
|
147
|
-
};
|
|
148
|
-
function readableStreamAsyncIterable(stream) {
|
|
149
|
-
if (stream[Symbol.asyncIterator]) {
|
|
150
|
-
return stream;
|
|
151
|
-
}
|
|
152
|
-
const reader = stream.getReader();
|
|
153
|
-
return {
|
|
154
|
-
next: async () => {
|
|
155
|
-
try {
|
|
156
|
-
const result = await reader.read();
|
|
157
|
-
if (result?.done) {
|
|
158
|
-
reader.releaseLock();
|
|
159
|
-
}
|
|
160
|
-
return result;
|
|
161
|
-
} catch (e) {
|
|
162
|
-
reader.releaseLock();
|
|
163
|
-
throw e;
|
|
164
|
-
}
|
|
165
|
-
},
|
|
166
|
-
return: async () => {
|
|
167
|
-
const cancelPromise = reader.cancel();
|
|
168
|
-
reader.releaseLock();
|
|
169
|
-
await cancelPromise;
|
|
170
|
-
return {
|
|
171
|
-
done: true,
|
|
172
|
-
value: void 0
|
|
173
|
-
};
|
|
174
|
-
},
|
|
175
|
-
[Symbol.asyncIterator]() {
|
|
176
|
-
return this;
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
var LineDecoder = class _LineDecoder {
|
|
181
|
-
static {
|
|
182
|
-
// prettier-ignore
|
|
183
|
-
this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
|
|
184
|
-
"\n",
|
|
185
|
-
"\r"
|
|
186
|
-
]);
|
|
187
|
-
}
|
|
188
|
-
static {
|
|
189
|
-
this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
190
|
-
}
|
|
191
|
-
constructor() {
|
|
192
|
-
this.buffer = [];
|
|
193
|
-
this.trailingCR = false;
|
|
194
|
-
}
|
|
195
|
-
decode(chunk) {
|
|
196
|
-
let text = this.decodeText(chunk);
|
|
197
|
-
if (this.trailingCR) {
|
|
198
|
-
text = "\r" + text;
|
|
199
|
-
this.trailingCR = false;
|
|
200
|
-
}
|
|
201
|
-
if (text.endsWith("\r")) {
|
|
202
|
-
this.trailingCR = true;
|
|
203
|
-
text = text.slice(0, -1);
|
|
204
|
-
}
|
|
205
|
-
if (!text) {
|
|
206
|
-
return [];
|
|
207
|
-
}
|
|
208
|
-
const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
|
|
209
|
-
let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
|
|
210
|
-
if (trailingNewline) {
|
|
211
|
-
lines.pop();
|
|
212
|
-
}
|
|
213
|
-
if (lines.length === 1 && !trailingNewline) {
|
|
214
|
-
this.buffer.push(lines[0]);
|
|
215
|
-
return [];
|
|
216
|
-
}
|
|
217
|
-
if (this.buffer.length > 0) {
|
|
218
|
-
lines = [
|
|
219
|
-
this.buffer.join("") + lines[0],
|
|
220
|
-
...lines.slice(1)
|
|
221
|
-
];
|
|
222
|
-
this.buffer = [];
|
|
223
|
-
}
|
|
224
|
-
if (!trailingNewline) {
|
|
225
|
-
this.buffer = [
|
|
226
|
-
lines.pop() || ""
|
|
227
|
-
];
|
|
228
|
-
}
|
|
229
|
-
return lines;
|
|
230
|
-
}
|
|
231
|
-
decodeText(bytes) {
|
|
232
|
-
if (bytes == null) {
|
|
233
|
-
return "";
|
|
234
|
-
}
|
|
235
|
-
if (typeof bytes === "string") {
|
|
236
|
-
return bytes;
|
|
237
|
-
}
|
|
238
|
-
if (typeof Buffer !== "undefined") {
|
|
239
|
-
if (bytes instanceof Buffer) {
|
|
240
|
-
return bytes.toString();
|
|
241
|
-
}
|
|
242
|
-
if (bytes instanceof Uint8Array) {
|
|
243
|
-
return Buffer.from(bytes).toString();
|
|
244
|
-
}
|
|
245
|
-
throw new Error(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
|
|
246
|
-
}
|
|
247
|
-
if (typeof TextDecoder !== "undefined") {
|
|
248
|
-
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
|
|
249
|
-
this.textDecoder ??= new TextDecoder("utf8");
|
|
250
|
-
return this.textDecoder.decode(bytes);
|
|
251
|
-
}
|
|
252
|
-
throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
|
|
253
|
-
}
|
|
254
|
-
throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
|
|
255
|
-
}
|
|
256
|
-
flush() {
|
|
257
|
-
if (!this.buffer.length && !this.trailingCR) {
|
|
258
|
-
return [];
|
|
259
|
-
}
|
|
260
|
-
const lines = [
|
|
261
|
-
this.buffer.join("")
|
|
262
|
-
];
|
|
263
|
-
this.buffer = [];
|
|
264
|
-
this.trailingCR = false;
|
|
265
|
-
return lines;
|
|
266
|
-
}
|
|
267
|
-
};
|
|
268
|
-
|
|
269
|
-
// packages/experimental/assistant/src/ai-service/stream.ts
|
|
270
|
-
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/stream.ts";
|
|
271
|
-
var createGenerationStream = (response, controller = new AbortController()) => {
|
|
272
|
-
const iterator = async function* () {
|
|
273
|
-
for await (const sse of iterSSEMessages(response, controller)) {
|
|
274
|
-
if (sse.event === "completion") {
|
|
275
|
-
try {
|
|
276
|
-
yield JSON.parse(sse.data);
|
|
277
|
-
} catch (err) {
|
|
278
|
-
log.error("could not parse message into JSON:", {
|
|
279
|
-
data: sse.data,
|
|
280
|
-
raw: sse.raw
|
|
281
|
-
}, {
|
|
282
|
-
F: __dxlog_file,
|
|
283
|
-
L: 22,
|
|
284
|
-
S: this,
|
|
285
|
-
C: (f, a) => f(...a)
|
|
286
|
-
});
|
|
287
|
-
throw err;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
|
|
291
|
-
try {
|
|
292
|
-
yield JSON.parse(sse.data);
|
|
293
|
-
} catch (err) {
|
|
294
|
-
log.error("could not parse message into JSON:", {
|
|
295
|
-
data: sse.data,
|
|
296
|
-
raw: sse.raw
|
|
297
|
-
}, {
|
|
298
|
-
F: __dxlog_file,
|
|
299
|
-
L: 38,
|
|
300
|
-
S: this,
|
|
301
|
-
C: (f, a) => f(...a)
|
|
302
|
-
});
|
|
303
|
-
throw err;
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
if (sse.event === "ping") {
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
if (sse.event === "error") {
|
|
310
|
-
throw new Error(`Message generation error: ${sse.data}`);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
};
|
|
314
|
-
return new GenerationStreamImpl(controller, iterator);
|
|
315
|
-
};
|
|
316
|
-
var GenerationStreamImpl = class {
|
|
317
|
-
constructor(_controller, _getIterator) {
|
|
318
|
-
this._controller = _controller;
|
|
319
|
-
this._getIterator = _getIterator;
|
|
320
|
-
this._done = new Trigger();
|
|
321
|
-
this._iterator = void 0;
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Returns an iterator over the stream.
|
|
325
|
-
*/
|
|
326
|
-
[Symbol.asyncIterator]() {
|
|
327
|
-
return this._createIterator();
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Aborts the stream.
|
|
331
|
-
*/
|
|
332
|
-
abort() {
|
|
333
|
-
this._controller.abort();
|
|
334
|
-
}
|
|
335
|
-
/**
|
|
336
|
-
* Returns the complete message list generated by the AI service.
|
|
337
|
-
*/
|
|
338
|
-
async complete() {
|
|
339
|
-
await this._done.wait();
|
|
340
|
-
}
|
|
341
|
-
/**
|
|
342
|
-
* Creates an iterator over the stream.
|
|
343
|
-
*/
|
|
344
|
-
_createIterator() {
|
|
345
|
-
const self = this;
|
|
346
|
-
return this._iterator ??= (() => {
|
|
347
|
-
const generator = async function* () {
|
|
348
|
-
try {
|
|
349
|
-
for await (const event of self._getIterator()) {
|
|
350
|
-
yield event;
|
|
351
|
-
}
|
|
352
|
-
this._done.wake();
|
|
353
|
-
} catch (err) {
|
|
354
|
-
this._done.throw(err);
|
|
355
|
-
throw err;
|
|
356
|
-
}
|
|
357
|
-
};
|
|
358
|
-
return generator.call(this);
|
|
359
|
-
})();
|
|
360
|
-
}
|
|
361
|
-
};
|
|
362
|
-
|
|
363
|
-
// packages/experimental/assistant/src/ai-service/edge-client.ts
|
|
364
|
-
import { assertArgument, invariant } from "@dxos/invariant";
|
|
365
|
-
import { log as log2 } from "@dxos/log";
|
|
366
|
-
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/edge-client.ts";
|
|
367
|
-
var AIServiceEdgeClient = class {
|
|
368
|
-
constructor({ endpoint }) {
|
|
369
|
-
invariant(endpoint, "endpoint is required", {
|
|
370
|
-
F: __dxlog_file2,
|
|
371
|
-
L: 20,
|
|
372
|
-
S: this,
|
|
373
|
-
A: [
|
|
374
|
-
"endpoint",
|
|
375
|
-
"'endpoint is required'"
|
|
376
|
-
]
|
|
377
|
-
});
|
|
378
|
-
this._endpoint = endpoint;
|
|
379
|
-
}
|
|
380
|
-
/**
|
|
381
|
-
* Generate non-streaming response.
|
|
382
|
-
*/
|
|
383
|
-
async exec(request) {
|
|
384
|
-
throw new Error("Not implemented");
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* Process request and open message stream.
|
|
388
|
-
*/
|
|
389
|
-
async execStream(request) {
|
|
390
|
-
assertArgument(typeof request.model === "string", "model is required");
|
|
391
|
-
log2("requesting", {
|
|
392
|
-
endpoint: this._endpoint
|
|
393
|
-
}, {
|
|
394
|
-
F: __dxlog_file2,
|
|
395
|
-
L: 36,
|
|
396
|
-
S: this,
|
|
397
|
-
C: (f, a) => f(...a)
|
|
398
|
-
});
|
|
399
|
-
const controller = new AbortController();
|
|
400
|
-
const response = await fetch(`${this._endpoint}/generate`, {
|
|
401
|
-
signal: controller.signal,
|
|
402
|
-
method: "POST",
|
|
403
|
-
headers: {
|
|
404
|
-
"Content-Type": "application/json"
|
|
405
|
-
},
|
|
406
|
-
body: JSON.stringify({
|
|
407
|
-
// TODO(dmaretskyi): Errors if tools are not provided.
|
|
408
|
-
tools: request.tools ?? [],
|
|
409
|
-
...request
|
|
410
|
-
})
|
|
411
|
-
});
|
|
412
|
-
if (!response.ok) {
|
|
413
|
-
throw await parseErrorResponse(response);
|
|
414
|
-
}
|
|
415
|
-
invariant(response.body instanceof ReadableStream, void 0, {
|
|
416
|
-
F: __dxlog_file2,
|
|
417
|
-
L: 53,
|
|
418
|
-
S: this,
|
|
419
|
-
A: [
|
|
420
|
-
"response.body instanceof ReadableStream",
|
|
421
|
-
""
|
|
422
|
-
]
|
|
423
|
-
});
|
|
424
|
-
return createGenerationStream(response, controller);
|
|
425
|
-
}
|
|
426
|
-
};
|
|
427
|
-
var parseErrorResponse = async (response) => {
|
|
428
|
-
throw new Error(`AI Service error: ${response.status} ${response.statusText} ${await response.text()}`);
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
// packages/experimental/assistant/src/ai-service/message-collector.ts
|
|
432
|
-
var MessageCollector = class {
|
|
433
|
-
constructor() {
|
|
434
|
-
this._messages = [];
|
|
435
|
-
this._pendingMessage = void 0;
|
|
436
|
-
}
|
|
437
|
-
get messages() {
|
|
438
|
-
return this._messages;
|
|
439
|
-
}
|
|
440
|
-
get pendingMessage() {
|
|
441
|
-
return this._pendingMessage;
|
|
442
|
-
}
|
|
443
|
-
push(event) {
|
|
444
|
-
switch (event.type) {
|
|
445
|
-
case "message_start":
|
|
446
|
-
this._pendingMessage = event.message;
|
|
447
|
-
break;
|
|
448
|
-
case "message_stop":
|
|
449
|
-
if (this._pendingMessage) {
|
|
450
|
-
this._messages.push(this._pendingMessage);
|
|
451
|
-
this._pendingMessage = void 0;
|
|
452
|
-
}
|
|
453
|
-
break;
|
|
454
|
-
case "content_block_start":
|
|
455
|
-
if (this._pendingMessage) {
|
|
456
|
-
this._pendingMessage.content = this._pendingMessage.content || [];
|
|
457
|
-
this._pendingMessage.content[event.index] = event.content;
|
|
458
|
-
}
|
|
459
|
-
break;
|
|
460
|
-
case "content_block_delta":
|
|
461
|
-
if (this._pendingMessage && this._pendingMessage.content) {
|
|
462
|
-
const block = this._pendingMessage.content[event.index];
|
|
463
|
-
if (block && event.delta.type === "text_delta" && block.type === "text") {
|
|
464
|
-
block.text = (block.text || "") + event.delta.text;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
break;
|
|
468
|
-
case "content_block_stop":
|
|
469
|
-
if (this._pendingMessage && this._pendingMessage.content) {
|
|
470
|
-
const block = this._pendingMessage.content[event.index];
|
|
471
|
-
if (block) {
|
|
472
|
-
block.pending = false;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
break;
|
|
476
|
-
case "message_delta":
|
|
477
|
-
if (this._pendingMessage && event.delta) {
|
|
478
|
-
Object.assign(this._pendingMessage, event.delta);
|
|
479
|
-
}
|
|
480
|
-
break;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
pushMessage(message) {
|
|
484
|
-
this._messages.push(message);
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
function* emitMessageAsEvents(message) {
|
|
488
|
-
yield {
|
|
489
|
-
type: "message_start",
|
|
490
|
-
message
|
|
491
|
-
};
|
|
492
|
-
yield {
|
|
493
|
-
type: "message_stop"
|
|
494
|
-
};
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// packages/experimental/assistant/src/ai-service/types.ts
|
|
498
|
-
import { Schema } from "effect";
|
|
499
|
-
import { Tool, Message } from "@dxos/artifact";
|
|
500
|
-
var createArtifactElement = (id) => `<artifact id=${id} />`;
|
|
501
|
-
var LLMModel = Schema.Literal(...DEFAULT_EDGE_MODELS, ...DEFAULT_OLLAMA_MODELS);
|
|
502
|
-
var ToolTypes = Object.freeze({
|
|
503
|
-
// TODO(dmaretskyi): Not implemented yet.
|
|
504
|
-
// DatabaseQuery: 'database_query',
|
|
505
|
-
TextToImage: "text_to_image"
|
|
506
|
-
});
|
|
507
|
-
var GenerateRequest = Schema.Struct({
|
|
508
|
-
/**
|
|
509
|
-
* Preferred model or system default.
|
|
510
|
-
*/
|
|
511
|
-
model: Schema.optional(LLMModel),
|
|
512
|
-
/**
|
|
513
|
-
* Tools available for the LLM.
|
|
514
|
-
*/
|
|
515
|
-
tools: Schema.optional(Schema.Array(Tool).pipe(Schema.mutable)),
|
|
516
|
-
/**
|
|
517
|
-
* System instructions to the LLM.
|
|
518
|
-
*/
|
|
519
|
-
systemPrompt: Schema.optional(Schema.String),
|
|
520
|
-
/**
|
|
521
|
-
* History of messages to include in the context window.
|
|
522
|
-
*/
|
|
523
|
-
// TODO(burdon): Rename messages.
|
|
524
|
-
history: Schema.optional(Schema.Array(Message)),
|
|
525
|
-
/**
|
|
526
|
-
* Current request.
|
|
527
|
-
*/
|
|
528
|
-
prompt: Schema.optional(Message)
|
|
529
|
-
});
|
|
530
|
-
var GenerateResponse = Schema.Struct({
|
|
531
|
-
messages: Schema.Array(Message),
|
|
532
|
-
/**
|
|
533
|
-
* Number of tokens used in the response.
|
|
534
|
-
*/
|
|
535
|
-
tokenCount: Schema.optional(Schema.Number)
|
|
536
|
-
});
|
|
537
|
-
|
|
538
|
-
// packages/experimental/assistant/src/session/tools.ts
|
|
539
|
-
import { Message as Message2, ToolResult } from "@dxos/artifact";
|
|
540
|
-
import { create } from "@dxos/echo-schema";
|
|
541
|
-
import { invariant as invariant2 } from "@dxos/invariant";
|
|
542
|
-
import { log as log3 } from "@dxos/log";
|
|
543
|
-
var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/tools.ts";
|
|
544
|
-
var isToolUse = (message, { onlyToolNames } = {}) => {
|
|
545
|
-
const block = message.content.at(-1);
|
|
546
|
-
invariant2(block, void 0, {
|
|
547
|
-
F: __dxlog_file3,
|
|
548
|
-
L: 12,
|
|
549
|
-
S: void 0,
|
|
550
|
-
A: [
|
|
551
|
-
"block",
|
|
552
|
-
""
|
|
553
|
-
]
|
|
554
|
-
});
|
|
555
|
-
return block.type === "tool_use" && (!onlyToolNames || onlyToolNames.includes(block.name));
|
|
556
|
-
};
|
|
557
|
-
var runTools = async ({ message, tools, extensions }) => {
|
|
558
|
-
const toolCalls = message.content.filter((block) => block.type === "tool_use");
|
|
559
|
-
invariant2(toolCalls.length === 1, void 0, {
|
|
560
|
-
F: __dxlog_file3,
|
|
561
|
-
L: 34,
|
|
562
|
-
S: void 0,
|
|
563
|
-
A: [
|
|
564
|
-
"toolCalls.length === 1",
|
|
565
|
-
""
|
|
566
|
-
]
|
|
567
|
-
});
|
|
568
|
-
const toolCall = toolCalls[0];
|
|
569
|
-
const tool = tools.find((tool2) => tool2.name === toolCall.name);
|
|
570
|
-
if (!tool) {
|
|
571
|
-
const resultMessage = create(Message2, {
|
|
572
|
-
role: "user",
|
|
573
|
-
content: [
|
|
574
|
-
{
|
|
575
|
-
type: "tool_result",
|
|
576
|
-
toolUseId: toolCall.id,
|
|
577
|
-
content: `Tool not found: ${toolCall.name}`,
|
|
578
|
-
isError: true
|
|
579
|
-
}
|
|
580
|
-
]
|
|
581
|
-
});
|
|
582
|
-
return {
|
|
583
|
-
type: "continue",
|
|
584
|
-
message: resultMessage
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
let toolResult;
|
|
588
|
-
try {
|
|
589
|
-
invariant2(tool.execute, void 0, {
|
|
590
|
-
F: __dxlog_file3,
|
|
591
|
-
L: 59,
|
|
592
|
-
S: void 0,
|
|
593
|
-
A: [
|
|
594
|
-
"tool.execute",
|
|
595
|
-
""
|
|
596
|
-
]
|
|
597
|
-
});
|
|
598
|
-
toolResult = await tool.execute(toolCall.input, {
|
|
599
|
-
extensions
|
|
600
|
-
});
|
|
601
|
-
} catch (error) {
|
|
602
|
-
log3("tool error", {
|
|
603
|
-
error
|
|
604
|
-
}, {
|
|
605
|
-
F: __dxlog_file3,
|
|
606
|
-
L: 62,
|
|
607
|
-
S: void 0,
|
|
608
|
-
C: (f, a) => f(...a)
|
|
609
|
-
});
|
|
610
|
-
toolResult = ToolResult.Error(error.message);
|
|
611
|
-
}
|
|
612
|
-
switch (toolResult.kind) {
|
|
613
|
-
case "error": {
|
|
614
|
-
log3("tool error", {
|
|
615
|
-
message: toolResult.message
|
|
616
|
-
}, {
|
|
617
|
-
F: __dxlog_file3,
|
|
618
|
-
L: 68,
|
|
619
|
-
S: void 0,
|
|
620
|
-
C: (f, a) => f(...a)
|
|
621
|
-
});
|
|
622
|
-
const resultMessage = create(Message2, {
|
|
623
|
-
role: "user",
|
|
624
|
-
content: [
|
|
625
|
-
{
|
|
626
|
-
type: "tool_result",
|
|
627
|
-
toolUseId: toolCall.id,
|
|
628
|
-
content: toolResult.message,
|
|
629
|
-
isError: true
|
|
630
|
-
}
|
|
631
|
-
]
|
|
632
|
-
});
|
|
633
|
-
return {
|
|
634
|
-
type: "continue",
|
|
635
|
-
message: resultMessage
|
|
636
|
-
};
|
|
637
|
-
}
|
|
638
|
-
case "success": {
|
|
639
|
-
log3("tool success", {
|
|
640
|
-
result: toolResult.result
|
|
641
|
-
}, {
|
|
642
|
-
F: __dxlog_file3,
|
|
643
|
-
L: 89,
|
|
644
|
-
S: void 0,
|
|
645
|
-
C: (f, a) => f(...a)
|
|
646
|
-
});
|
|
647
|
-
const resultMessage = create(Message2, {
|
|
648
|
-
role: "user",
|
|
649
|
-
content: [
|
|
650
|
-
{
|
|
651
|
-
type: "tool_result",
|
|
652
|
-
toolUseId: toolCall.id,
|
|
653
|
-
content: typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result) ?? ""
|
|
654
|
-
},
|
|
655
|
-
...toolResult.extractContentBlocks ?? []
|
|
656
|
-
]
|
|
657
|
-
});
|
|
658
|
-
return {
|
|
659
|
-
type: "continue",
|
|
660
|
-
message: resultMessage
|
|
661
|
-
};
|
|
662
|
-
}
|
|
663
|
-
case "break": {
|
|
664
|
-
log3("tool break", {
|
|
665
|
-
result: toolResult.result
|
|
666
|
-
}, {
|
|
667
|
-
F: __dxlog_file3,
|
|
668
|
-
L: 110,
|
|
669
|
-
S: void 0,
|
|
670
|
-
C: (f, a) => f(...a)
|
|
671
|
-
});
|
|
672
|
-
return {
|
|
673
|
-
type: "break",
|
|
674
|
-
result: toolResult.result
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
};
|
|
679
|
-
|
|
680
|
-
// packages/experimental/assistant/src/session/version-pin.ts
|
|
681
|
-
import { Schema as Schema2 } from "effect";
|
|
682
|
-
import { getVersion } from "@dxos/echo-db";
|
|
683
|
-
import { ObjectId } from "@dxos/echo-schema";
|
|
684
|
-
var ObjectVersionSchema = Schema2.Unknown;
|
|
685
|
-
var VersionPinSchema = Schema2.Struct({
|
|
686
|
-
// TODO(dmaretskyi): Use Ref when those support encoding.
|
|
687
|
-
objectId: ObjectId,
|
|
688
|
-
// TODO(dmaretskyi): Could be opaque
|
|
689
|
-
version: ObjectVersionSchema
|
|
690
|
-
});
|
|
691
|
-
var VersionPin = class extends VersionPinSchema {
|
|
692
|
-
static {
|
|
693
|
-
this.DISPOSITION = "version-pin";
|
|
694
|
-
}
|
|
695
|
-
static fromObject(object) {
|
|
696
|
-
return VersionPin.make({
|
|
697
|
-
objectId: object.id,
|
|
698
|
-
version: getVersion(object)
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
static createBlock(pin) {
|
|
702
|
-
return {
|
|
703
|
-
type: "json",
|
|
704
|
-
disposition: VersionPin.DISPOSITION,
|
|
705
|
-
json: JSON.stringify(pin)
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
};
|
|
709
|
-
|
|
710
|
-
// packages/experimental/assistant/src/session/session.ts
|
|
711
|
-
import { Option, Schema as Schema4 } from "effect";
|
|
712
|
-
import { defineTool as defineTool2, Message as Message4, structuredOutputParser, ToolResult as ToolResult3 } from "@dxos/artifact";
|
|
713
|
-
import { Event as Event2, synchronized } from "@dxos/async";
|
|
714
|
-
import { ObjectVersion } from "@dxos/echo-db";
|
|
715
|
-
import { create as create3 } from "@dxos/echo-schema";
|
|
716
|
-
import { invariant as invariant5 } from "@dxos/invariant";
|
|
717
|
-
import { log as log6 } from "@dxos/log";
|
|
718
|
-
|
|
719
|
-
// packages/experimental/assistant/src/ai-service/ollama-client.ts
|
|
720
|
-
import { Schema as Schema3 } from "effect";
|
|
721
|
-
import { defineTool, ToolResult as ToolResult2 } from "@dxos/artifact";
|
|
722
|
-
import { ObjectId as ObjectId2 } from "@dxos/echo-schema";
|
|
723
|
-
import { invariant as invariant3 } from "@dxos/invariant";
|
|
724
|
-
import { log as log4 } from "@dxos/log";
|
|
725
|
-
var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/ollama-client.ts";
|
|
726
|
-
var OllamaClient = class {
|
|
727
|
-
/**
|
|
728
|
-
* Check if Ollama server is running and accessible.
|
|
729
|
-
* @returns Promise that resolves to true if Ollama is running, false otherwise.
|
|
730
|
-
*/
|
|
731
|
-
static async isRunning() {
|
|
732
|
-
try {
|
|
733
|
-
const response = await fetch(`${DEFAULT_OLLAMA_ENDPOINT}/api/version`, {
|
|
734
|
-
method: "GET",
|
|
735
|
-
headers: {
|
|
736
|
-
"Content-Type": "application/json"
|
|
737
|
-
},
|
|
738
|
-
signal: AbortSignal.timeout(100)
|
|
739
|
-
});
|
|
740
|
-
return response.ok;
|
|
741
|
-
} catch (error) {
|
|
742
|
-
return false;
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
constructor({ endpoint, tools, overrides, maxToolInvocations } = {}) {
|
|
746
|
-
this._endpoint = endpoint ?? DEFAULT_OLLAMA_ENDPOINT;
|
|
747
|
-
this._tools = tools ?? [];
|
|
748
|
-
this._modelOverride = overrides?.model;
|
|
749
|
-
this._temperatureOverride = overrides?.temperature;
|
|
750
|
-
this._maxToolInvocations = maxToolInvocations ?? 3;
|
|
751
|
-
}
|
|
752
|
-
_getEmbededTools(clientTools) {
|
|
753
|
-
return [
|
|
754
|
-
...this._tools,
|
|
755
|
-
...clientTools.filter((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type]).map((tool) => WELL_KNOWN_TOOLS[tool.type])
|
|
756
|
-
];
|
|
757
|
-
}
|
|
758
|
-
async *_generateStream(request, signal) {
|
|
759
|
-
invariant3(request.prompt === void 0, "Prompt must be in history", {
|
|
760
|
-
F: __dxlog_file4,
|
|
761
|
-
L: 88,
|
|
762
|
-
S: this,
|
|
763
|
-
A: [
|
|
764
|
-
"request.prompt === undefined",
|
|
765
|
-
"'Prompt must be in history'"
|
|
766
|
-
]
|
|
767
|
-
});
|
|
768
|
-
const ollamaRequest = {
|
|
769
|
-
model: this._modelOverride ?? request.model ?? "llama3",
|
|
770
|
-
messages: [],
|
|
771
|
-
stream: true,
|
|
772
|
-
options: {
|
|
773
|
-
temperature: this._temperatureOverride
|
|
774
|
-
}
|
|
775
|
-
};
|
|
776
|
-
if (request.systemPrompt) {
|
|
777
|
-
ollamaRequest.messages.push({
|
|
778
|
-
role: "system",
|
|
779
|
-
content: request.systemPrompt
|
|
780
|
-
});
|
|
781
|
-
}
|
|
782
|
-
if (request.history?.length) {
|
|
783
|
-
for (const message of request.history) {
|
|
784
|
-
const role = message.role === "assistant" ? "assistant" : "user";
|
|
785
|
-
if (message.content.length === 0) {
|
|
786
|
-
continue;
|
|
787
|
-
}
|
|
788
|
-
for (const content of message.content) {
|
|
789
|
-
switch (content.type) {
|
|
790
|
-
case "text": {
|
|
791
|
-
ollamaRequest.messages.push({
|
|
792
|
-
role,
|
|
793
|
-
content: content.text
|
|
794
|
-
});
|
|
795
|
-
break;
|
|
796
|
-
}
|
|
797
|
-
case "tool_use": {
|
|
798
|
-
ollamaRequest.messages.push({
|
|
799
|
-
role: "assistant",
|
|
800
|
-
content: "",
|
|
801
|
-
tool_calls: [
|
|
802
|
-
{
|
|
803
|
-
function: {
|
|
804
|
-
name: content.name,
|
|
805
|
-
arguments: content.input
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
]
|
|
809
|
-
});
|
|
810
|
-
break;
|
|
811
|
-
}
|
|
812
|
-
case "tool_result": {
|
|
813
|
-
ollamaRequest.messages.push({
|
|
814
|
-
role: "tool",
|
|
815
|
-
content: JSON.stringify({
|
|
816
|
-
type: "tool_result",
|
|
817
|
-
toolUseId: content.toolUseId,
|
|
818
|
-
content: content.content
|
|
819
|
-
})
|
|
820
|
-
});
|
|
821
|
-
break;
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
if (request.tools?.length || this._tools.length) {
|
|
828
|
-
const allTools = [
|
|
829
|
-
...request.tools ?? [],
|
|
830
|
-
...this._tools
|
|
831
|
-
];
|
|
832
|
-
const withWellKnownTools = allTools.map((tool) => tool.type !== void 0 && WELL_KNOWN_TOOLS[tool.type] ? WELL_KNOWN_TOOLS[tool.type] : tool);
|
|
833
|
-
if (withWellKnownTools.length > 0) {
|
|
834
|
-
ollamaRequest.tools = withWellKnownTools.map((tool) => ({
|
|
835
|
-
type: "function",
|
|
836
|
-
function: {
|
|
837
|
-
name: tool.name,
|
|
838
|
-
description: tool.description,
|
|
839
|
-
parameters: {
|
|
840
|
-
type: "object",
|
|
841
|
-
properties: tool.parameters?.properties,
|
|
842
|
-
required: tool.parameters?.required
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
}));
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
log4("generate request", {
|
|
849
|
-
history: request.history,
|
|
850
|
-
prompt: request.prompt,
|
|
851
|
-
ollamaRequest
|
|
852
|
-
}, {
|
|
853
|
-
F: __dxlog_file4,
|
|
854
|
-
L: 182,
|
|
855
|
-
S: this,
|
|
856
|
-
C: (f, a) => f(...a)
|
|
857
|
-
});
|
|
858
|
-
const response = await fetch(`${this._endpoint}/api/chat`, {
|
|
859
|
-
method: "POST",
|
|
860
|
-
headers: {
|
|
861
|
-
"Content-Type": "application/json"
|
|
862
|
-
},
|
|
863
|
-
body: JSON.stringify(ollamaRequest),
|
|
864
|
-
signal
|
|
865
|
-
});
|
|
866
|
-
if (!response.ok) {
|
|
867
|
-
throw await parseErrorResponse2(response);
|
|
868
|
-
}
|
|
869
|
-
if (!response.body) {
|
|
870
|
-
throw new Error("Ollama API returned no response body");
|
|
871
|
-
}
|
|
872
|
-
const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new OllamaDecoderStream()).getReader();
|
|
873
|
-
try {
|
|
874
|
-
const messageId = ObjectId2.random();
|
|
875
|
-
yield {
|
|
876
|
-
type: "message_start",
|
|
877
|
-
message: {
|
|
878
|
-
id: messageId,
|
|
879
|
-
role: "assistant",
|
|
880
|
-
content: []
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
const textBlock = {
|
|
884
|
-
type: "text",
|
|
885
|
-
text: ""
|
|
886
|
-
};
|
|
887
|
-
let currentBlockIndex = 0;
|
|
888
|
-
yield {
|
|
889
|
-
type: "content_block_start",
|
|
890
|
-
index: currentBlockIndex,
|
|
891
|
-
content: textBlock
|
|
892
|
-
};
|
|
893
|
-
while (true) {
|
|
894
|
-
const { done, value: data } = await reader.read();
|
|
895
|
-
if (done) {
|
|
896
|
-
break;
|
|
897
|
-
}
|
|
898
|
-
log4("ollama data", {
|
|
899
|
-
data
|
|
900
|
-
}, {
|
|
901
|
-
F: __dxlog_file4,
|
|
902
|
-
L: 244,
|
|
903
|
-
S: this,
|
|
904
|
-
C: (f, a) => f(...a)
|
|
905
|
-
});
|
|
906
|
-
if (data.message?.content) {
|
|
907
|
-
yield {
|
|
908
|
-
type: "content_block_delta",
|
|
909
|
-
index: 0,
|
|
910
|
-
delta: {
|
|
911
|
-
type: "text_delta",
|
|
912
|
-
text: data.message.content
|
|
913
|
-
}
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
if (data.message?.tool_calls && data.message?.tool_calls?.length > 0) {
|
|
917
|
-
if (data.message.tool_calls.length > 1) {
|
|
918
|
-
log4.warn("Ollama returned multiple tool calls. Only the first one will be used.", void 0, {
|
|
919
|
-
F: __dxlog_file4,
|
|
920
|
-
L: 261,
|
|
921
|
-
S: this,
|
|
922
|
-
C: (f, a) => f(...a)
|
|
923
|
-
});
|
|
924
|
-
}
|
|
925
|
-
yield {
|
|
926
|
-
type: "content_block_stop",
|
|
927
|
-
index: currentBlockIndex++
|
|
928
|
-
};
|
|
929
|
-
yield {
|
|
930
|
-
type: "content_block_start",
|
|
931
|
-
index: currentBlockIndex,
|
|
932
|
-
content: {
|
|
933
|
-
type: "tool_use",
|
|
934
|
-
id: ObjectId2.random(),
|
|
935
|
-
name: data.message.tool_calls[0].function.name,
|
|
936
|
-
input: sanitizeToolArguments(data.message.tool_calls[0].function.arguments)
|
|
937
|
-
}
|
|
938
|
-
};
|
|
939
|
-
yield {
|
|
940
|
-
type: "message_delta",
|
|
941
|
-
delta: {
|
|
942
|
-
stopReason: "tool_use"
|
|
943
|
-
}
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
yield {
|
|
948
|
-
type: "content_block_stop",
|
|
949
|
-
index: currentBlockIndex
|
|
950
|
-
};
|
|
951
|
-
yield {
|
|
952
|
-
type: "message_stop"
|
|
953
|
-
};
|
|
954
|
-
} finally {
|
|
955
|
-
reader.releaseLock();
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
/**
|
|
959
|
-
* Generate non-streaming response.
|
|
960
|
-
*/
|
|
961
|
-
async exec(request) {
|
|
962
|
-
throw new Error("Not implemented");
|
|
963
|
-
}
|
|
964
|
-
async execStream(request) {
|
|
965
|
-
const controller = new AbortController();
|
|
966
|
-
try {
|
|
967
|
-
return new GenerationStreamImpl(controller, async function* () {
|
|
968
|
-
const collector = new MessageCollector();
|
|
969
|
-
let toolInvocations = 0;
|
|
970
|
-
while (true) {
|
|
971
|
-
for await (const event of this._generateStream({
|
|
972
|
-
...request,
|
|
973
|
-
history: [
|
|
974
|
-
...request.history ?? [],
|
|
975
|
-
...request.prompt ? [
|
|
976
|
-
request.prompt
|
|
977
|
-
] : [],
|
|
978
|
-
...collector.messages
|
|
979
|
-
],
|
|
980
|
-
prompt: void 0
|
|
981
|
-
}, controller.signal)) {
|
|
982
|
-
collector.push(event);
|
|
983
|
-
yield event;
|
|
984
|
-
}
|
|
985
|
-
if (collector.messages.length > 0 && !isToolUse(collector.messages.at(-1), {
|
|
986
|
-
onlyToolNames: this._getEmbededTools(request.tools ?? []).map((tool) => tool.name)
|
|
987
|
-
})) {
|
|
988
|
-
break;
|
|
989
|
-
}
|
|
990
|
-
if (++toolInvocations > this._maxToolInvocations) {
|
|
991
|
-
throw new Error("Maximum number of tool invocations reached");
|
|
992
|
-
}
|
|
993
|
-
const result = await runTools({
|
|
994
|
-
message: collector.messages.at(-1),
|
|
995
|
-
tools: this._getEmbededTools(request.tools ?? [])
|
|
996
|
-
});
|
|
997
|
-
switch (result.type) {
|
|
998
|
-
case "continue": {
|
|
999
|
-
collector.pushMessage(result.message);
|
|
1000
|
-
yield* emitMessageAsEvents(result.message);
|
|
1001
|
-
break;
|
|
1002
|
-
}
|
|
1003
|
-
case "break": {
|
|
1004
|
-
throw new Error("Tool use breaks not allowed");
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
}.bind(this));
|
|
1009
|
-
} catch (error) {
|
|
1010
|
-
controller.abort();
|
|
1011
|
-
throw error;
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
};
|
|
1015
|
-
var sanitizeToolArguments = (args) => {
|
|
1016
|
-
if (args.type === "object" && typeof args.properties === "object" && Array.isArray(args.required)) {
|
|
1017
|
-
return args.properties;
|
|
1018
|
-
}
|
|
1019
|
-
return args;
|
|
1020
|
-
};
|
|
1021
|
-
var SAMPLE_IMAGE_URL = "https://images.nightcafe.studio/jobs/BNmcRhHCM1JRKoUtqSei/BNmcRhHCM1JRKoUtqSei--1--5b9rv.jpg";
|
|
1022
|
-
var WELL_KNOWN_TOOLS = {
|
|
1023
|
-
[ToolTypes.TextToImage]: defineTool("system", {
|
|
1024
|
-
name: "text-to-image",
|
|
1025
|
-
description: "Generate an image from a text prompt",
|
|
1026
|
-
schema: Schema3.Struct({
|
|
1027
|
-
prompt: Schema3.String.annotations({
|
|
1028
|
-
description: "The text prompt describing the image to generate"
|
|
1029
|
-
})
|
|
1030
|
-
}),
|
|
1031
|
-
execute: async ({ prompt }) => {
|
|
1032
|
-
const image = await fetch(SAMPLE_IMAGE_URL).then(async (res) => Buffer.from(await res.arrayBuffer()));
|
|
1033
|
-
const imageBase64 = image.toString("base64");
|
|
1034
|
-
const id = ObjectId2.random();
|
|
1035
|
-
return ToolResult2.Success(`The generation was successful. Image ID: ${id} Prompt: ${prompt}`, [
|
|
1036
|
-
{
|
|
1037
|
-
type: "image",
|
|
1038
|
-
id,
|
|
1039
|
-
source: {
|
|
1040
|
-
type: "base64",
|
|
1041
|
-
mediaType: "image/jpeg",
|
|
1042
|
-
data: imageBase64
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
]);
|
|
1046
|
-
}
|
|
1047
|
-
})
|
|
1048
|
-
};
|
|
1049
|
-
var OllamaDecoderStream = class extends TransformStream {
|
|
1050
|
-
constructor() {
|
|
1051
|
-
super({
|
|
1052
|
-
transform: (chunk, controller) => {
|
|
1053
|
-
this._buffer += chunk;
|
|
1054
|
-
const lines = this._buffer.split("\n");
|
|
1055
|
-
this._buffer = lines.pop() || "";
|
|
1056
|
-
for (const line of lines) {
|
|
1057
|
-
controller.enqueue(JSON.parse(line.trim()));
|
|
1058
|
-
}
|
|
1059
|
-
},
|
|
1060
|
-
flush: (controller) => {
|
|
1061
|
-
this._buffer = this._buffer.trim();
|
|
1062
|
-
if (this._buffer.length > 0) {
|
|
1063
|
-
controller.enqueue(JSON.parse(this._buffer));
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
});
|
|
1067
|
-
this._buffer = "";
|
|
1068
|
-
}
|
|
1069
|
-
};
|
|
1070
|
-
var ModelDoesNotSupportToolsError = class extends Schema3.TaggedError()("ModelDoesNotSupportToolsError", {
|
|
1071
|
-
model: Schema3.String
|
|
1072
|
-
}) {
|
|
1073
|
-
};
|
|
1074
|
-
var ModelNotFoundError = class extends Schema3.TaggedError()("ModelNotFoundError", {
|
|
1075
|
-
model: Schema3.String
|
|
1076
|
-
}) {
|
|
1077
|
-
};
|
|
1078
|
-
var parseOllamaError = (error) => {
|
|
1079
|
-
{
|
|
1080
|
-
const match = error.match(/^([^']+) does not support tools$/);
|
|
1081
|
-
if (match) {
|
|
1082
|
-
return new ModelDoesNotSupportToolsError({
|
|
1083
|
-
model: match[1]
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
{
|
|
1088
|
-
const match = error.match(/^model "([^"]+)" not found, try pulling it first$/);
|
|
1089
|
-
if (match) {
|
|
1090
|
-
return new ModelNotFoundError({
|
|
1091
|
-
model: match[1]
|
|
1092
|
-
});
|
|
1093
|
-
}
|
|
1094
|
-
}
|
|
1095
|
-
throw new Error(`Ollama API error: ${error}`);
|
|
1096
|
-
};
|
|
1097
|
-
var parseErrorResponse2 = async (response) => {
|
|
1098
|
-
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
1099
|
-
const body = await response.json();
|
|
1100
|
-
return parseOllamaError(body.error);
|
|
1101
|
-
}
|
|
1102
|
-
throw new Error(`Ollama API error: ${response.status} ${response.statusText} ${await response.text()}`);
|
|
1103
|
-
};
|
|
1104
|
-
|
|
1105
|
-
// packages/experimental/assistant/src/ai-service/parser.ts
|
|
1106
|
-
import { Message as Message3 } from "@dxos/artifact";
|
|
1107
|
-
import { Event } from "@dxos/async";
|
|
1108
|
-
import { create as create2 } from "@dxos/echo-schema";
|
|
1109
|
-
import { invariant as invariant4 } from "@dxos/invariant";
|
|
1110
|
-
import { log as log5 } from "@dxos/log";
|
|
1111
|
-
import { isNotFalsy, safeParseJson } from "@dxos/util";
|
|
1112
|
-
|
|
1113
|
-
// packages/experimental/assistant/src/ai-service/transform.ts
|
|
1114
|
-
import * as P from "parsimmon";
|
|
1115
|
-
var textChunk = P.regexp(/[^<]+/).map((content) => ({
|
|
1116
|
-
type: "text",
|
|
1117
|
-
content
|
|
1118
|
-
}));
|
|
1119
|
-
var attribute = P.seq(P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/), P.string("=").trim(P.optWhitespace), P.alt(P.regexp(/"[^"]*"/).map((s) => s.slice(1, -1)), P.regexp(/'[^']*'/).map((s) => s.slice(1, -1)))).map(([name, _, value]) => [
|
|
1120
|
-
name,
|
|
1121
|
-
value
|
|
1122
|
-
]);
|
|
1123
|
-
var tagName = P.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/);
|
|
1124
|
-
var selfClosingTag = P.seqMap(
|
|
1125
|
-
//
|
|
1126
|
-
P.string("<"),
|
|
1127
|
-
tagName,
|
|
1128
|
-
P.optWhitespace.then(attribute).many(),
|
|
1129
|
-
P.optWhitespace.then(P.string("/>")),
|
|
1130
|
-
P.optWhitespace,
|
|
1131
|
-
(_, tag, attributes, __) => ({
|
|
1132
|
-
type: "tag",
|
|
1133
|
-
tag,
|
|
1134
|
-
attributes: Object.fromEntries(attributes),
|
|
1135
|
-
content: [],
|
|
1136
|
-
selfClosing: true
|
|
1137
|
-
})
|
|
1138
|
-
);
|
|
1139
|
-
var openTag = P.seqMap(
|
|
1140
|
-
//
|
|
1141
|
-
P.string("<"),
|
|
1142
|
-
tagName,
|
|
1143
|
-
P.optWhitespace.then(attribute).many(),
|
|
1144
|
-
P.string(">"),
|
|
1145
|
-
P.regexp(/[^<]*/),
|
|
1146
|
-
(_, tag, attributes, __, content) => ({
|
|
1147
|
-
type: "tag",
|
|
1148
|
-
tag,
|
|
1149
|
-
attributes: Object.fromEntries(attributes),
|
|
1150
|
-
content: content.length ? [
|
|
1151
|
-
{
|
|
1152
|
-
type: "text",
|
|
1153
|
-
content
|
|
1154
|
-
}
|
|
1155
|
-
] : []
|
|
1156
|
-
})
|
|
1157
|
-
);
|
|
1158
|
-
var closeTag = P.seqMap(
|
|
1159
|
-
//
|
|
1160
|
-
P.string("</"),
|
|
1161
|
-
tagName,
|
|
1162
|
-
P.string(">"),
|
|
1163
|
-
P.optWhitespace,
|
|
1164
|
-
(_, tag) => ({
|
|
1165
|
-
type: "tag",
|
|
1166
|
-
tag,
|
|
1167
|
-
content: [],
|
|
1168
|
-
closing: true
|
|
1169
|
-
})
|
|
1170
|
-
);
|
|
1171
|
-
var mixedChunk = P.alt(selfClosingTag, openTag, closeTag, textChunk);
|
|
1172
|
-
var StreamTransform = class {
|
|
1173
|
-
constructor() {
|
|
1174
|
-
this._buffer = "";
|
|
1175
|
-
}
|
|
1176
|
-
transform(chunk) {
|
|
1177
|
-
this._buffer += chunk;
|
|
1178
|
-
const results = [];
|
|
1179
|
-
const parser = mixedChunk.many().skip(P.optWhitespace);
|
|
1180
|
-
const result = parser.parse(this._buffer);
|
|
1181
|
-
if (result.status) {
|
|
1182
|
-
for (const chunk2 of result.value) {
|
|
1183
|
-
results.push(chunk2);
|
|
1184
|
-
}
|
|
1185
|
-
this._buffer = "";
|
|
1186
|
-
}
|
|
1187
|
-
return results;
|
|
1188
|
-
}
|
|
1189
|
-
// TODO(burdon): Process remaining buffer?
|
|
1190
|
-
flush() {
|
|
1191
|
-
const remaining = this._buffer;
|
|
1192
|
-
this._buffer = "";
|
|
1193
|
-
return remaining.length > 0 ? [
|
|
1194
|
-
{
|
|
1195
|
-
type: "text",
|
|
1196
|
-
content: remaining
|
|
1197
|
-
}
|
|
1198
|
-
] : [];
|
|
1199
|
-
}
|
|
1200
|
-
};
|
|
1201
|
-
|
|
1202
|
-
// packages/experimental/assistant/src/ai-service/parser.ts
|
|
1203
|
-
var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/ai-service/parser.ts";
|
|
1204
|
-
var MixedStreamParser = class {
|
|
1205
|
-
constructor() {
|
|
1206
|
-
/**
|
|
1207
|
-
* New message.
|
|
1208
|
-
*/
|
|
1209
|
-
this.message = new Event();
|
|
1210
|
-
/**
|
|
1211
|
-
* Complete block added to Message.
|
|
1212
|
-
*/
|
|
1213
|
-
this.block = new Event();
|
|
1214
|
-
/**
|
|
1215
|
-
* Update partial block (while streaming).
|
|
1216
|
-
*/
|
|
1217
|
-
this.update = new Event();
|
|
1218
|
-
this.streamEvent = new Event();
|
|
1219
|
-
}
|
|
1220
|
-
_emitBlock(contentBlock, streamBlock) {
|
|
1221
|
-
const messageBlock = streamBlock ? mergeMessageBlock(contentBlock, streamBlock) : contentBlock;
|
|
1222
|
-
if (messageBlock) {
|
|
1223
|
-
if (messageBlock.type === "text" && messageBlock.text.length === 0) {
|
|
1224
|
-
return;
|
|
1225
|
-
}
|
|
1226
|
-
invariant4(this._message, void 0, {
|
|
1227
|
-
F: __dxlog_file5,
|
|
1228
|
-
L: 49,
|
|
1229
|
-
S: this,
|
|
1230
|
-
A: [
|
|
1231
|
-
"this._message",
|
|
1232
|
-
""
|
|
1233
|
-
]
|
|
1234
|
-
});
|
|
1235
|
-
this._message.content.push(messageBlock);
|
|
1236
|
-
this.block.emit(messageBlock);
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
_emitUpdate(contentBlock, streamBlock) {
|
|
1240
|
-
const messageBlock = mergeMessageBlock(contentBlock, streamBlock);
|
|
1241
|
-
if (messageBlock) {
|
|
1242
|
-
messageBlock.pending = true;
|
|
1243
|
-
this.update.emit(messageBlock);
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
/**
|
|
1247
|
-
* Parse stream until end.
|
|
1248
|
-
*/
|
|
1249
|
-
async parse(stream) {
|
|
1250
|
-
const transformer = new StreamTransform();
|
|
1251
|
-
let contentBlock;
|
|
1252
|
-
let streamBlock;
|
|
1253
|
-
const stack = [];
|
|
1254
|
-
const messagesCollected = [];
|
|
1255
|
-
for await (const event of stream) {
|
|
1256
|
-
log5("streamEvent", {
|
|
1257
|
-
event
|
|
1258
|
-
}, {
|
|
1259
|
-
F: __dxlog_file5,
|
|
1260
|
-
L: 83,
|
|
1261
|
-
S: this,
|
|
1262
|
-
C: (f, a) => f(...a)
|
|
1263
|
-
});
|
|
1264
|
-
this.streamEvent.emit(event);
|
|
1265
|
-
switch (event.type) {
|
|
1266
|
-
//
|
|
1267
|
-
// Messages.
|
|
1268
|
-
//
|
|
1269
|
-
case "message_start": {
|
|
1270
|
-
if (this._message) {
|
|
1271
|
-
log5.warn("unexpected message_start", void 0, {
|
|
1272
|
-
F: __dxlog_file5,
|
|
1273
|
-
L: 94,
|
|
1274
|
-
S: this,
|
|
1275
|
-
C: (f, a) => f(...a)
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
this._message = create2(Message3, {
|
|
1279
|
-
role: event.message.role,
|
|
1280
|
-
content: [
|
|
1281
|
-
...event.message.content
|
|
1282
|
-
]
|
|
1283
|
-
});
|
|
1284
|
-
this.message.emit(this._message);
|
|
1285
|
-
break;
|
|
1286
|
-
}
|
|
1287
|
-
case "message_delta": {
|
|
1288
|
-
if (!this._message) {
|
|
1289
|
-
log5.warn("unexpected message_delta", void 0, {
|
|
1290
|
-
F: __dxlog_file5,
|
|
1291
|
-
L: 104,
|
|
1292
|
-
S: this,
|
|
1293
|
-
C: (f, a) => f(...a)
|
|
1294
|
-
});
|
|
1295
|
-
}
|
|
1296
|
-
break;
|
|
1297
|
-
}
|
|
1298
|
-
case "message_stop": {
|
|
1299
|
-
if (!this._message) {
|
|
1300
|
-
log5.warn("unexpected message_stop", void 0, {
|
|
1301
|
-
F: __dxlog_file5,
|
|
1302
|
-
L: 112,
|
|
1303
|
-
S: this,
|
|
1304
|
-
C: (f, a) => f(...a)
|
|
1305
|
-
});
|
|
1306
|
-
} else {
|
|
1307
|
-
messagesCollected.push(this._message);
|
|
1308
|
-
this._message = void 0;
|
|
1309
|
-
}
|
|
1310
|
-
break;
|
|
1311
|
-
}
|
|
1312
|
-
//
|
|
1313
|
-
// Content blocks.
|
|
1314
|
-
//
|
|
1315
|
-
case "content_block_start": {
|
|
1316
|
-
if (contentBlock) {
|
|
1317
|
-
log5.warn("unexpected content_block_start", {
|
|
1318
|
-
content: contentBlock
|
|
1319
|
-
}, {
|
|
1320
|
-
F: __dxlog_file5,
|
|
1321
|
-
L: 126,
|
|
1322
|
-
S: this,
|
|
1323
|
-
C: (f, a) => f(...a)
|
|
1324
|
-
});
|
|
1325
|
-
}
|
|
1326
|
-
contentBlock = event.content;
|
|
1327
|
-
break;
|
|
1328
|
-
}
|
|
1329
|
-
case "content_block_delta": {
|
|
1330
|
-
if (!contentBlock) {
|
|
1331
|
-
log5.warn("unexpected content_block_delta", void 0, {
|
|
1332
|
-
F: __dxlog_file5,
|
|
1333
|
-
L: 136,
|
|
1334
|
-
S: this,
|
|
1335
|
-
C: (f, a) => f(...a)
|
|
1336
|
-
});
|
|
1337
|
-
break;
|
|
1338
|
-
}
|
|
1339
|
-
switch (event.delta.type) {
|
|
1340
|
-
//
|
|
1341
|
-
// Text
|
|
1342
|
-
//
|
|
1343
|
-
case "text_delta": {
|
|
1344
|
-
const chunks = transformer.transform(event.delta.text);
|
|
1345
|
-
for (const chunk of chunks) {
|
|
1346
|
-
log5("text_delta", {
|
|
1347
|
-
chunk
|
|
1348
|
-
}, {
|
|
1349
|
-
F: __dxlog_file5,
|
|
1350
|
-
L: 147,
|
|
1351
|
-
S: this,
|
|
1352
|
-
C: (f, a) => f(...a)
|
|
1353
|
-
});
|
|
1354
|
-
switch (streamBlock?.type) {
|
|
1355
|
-
//
|
|
1356
|
-
// XML Fragment.
|
|
1357
|
-
//
|
|
1358
|
-
case "tag": {
|
|
1359
|
-
if (chunk.type === "tag") {
|
|
1360
|
-
if (chunk.selfClosing) {
|
|
1361
|
-
streamBlock.content.push(chunk);
|
|
1362
|
-
} else if (chunk.closing) {
|
|
1363
|
-
if (stack.length > 0) {
|
|
1364
|
-
const top = stack.pop();
|
|
1365
|
-
invariant4(top && top.type === "tag", void 0, {
|
|
1366
|
-
F: __dxlog_file5,
|
|
1367
|
-
L: 160,
|
|
1368
|
-
S: this,
|
|
1369
|
-
A: [
|
|
1370
|
-
"top && top.type === 'tag'",
|
|
1371
|
-
""
|
|
1372
|
-
]
|
|
1373
|
-
});
|
|
1374
|
-
log5("pop", {
|
|
1375
|
-
top
|
|
1376
|
-
}, {
|
|
1377
|
-
F: __dxlog_file5,
|
|
1378
|
-
L: 161,
|
|
1379
|
-
S: this,
|
|
1380
|
-
C: (f, a) => f(...a)
|
|
1381
|
-
});
|
|
1382
|
-
top.content.push(streamBlock);
|
|
1383
|
-
streamBlock = top;
|
|
1384
|
-
} else {
|
|
1385
|
-
this._emitBlock(contentBlock, streamBlock);
|
|
1386
|
-
streamBlock = void 0;
|
|
1387
|
-
}
|
|
1388
|
-
} else {
|
|
1389
|
-
stack.push(streamBlock);
|
|
1390
|
-
streamBlock = chunk;
|
|
1391
|
-
}
|
|
1392
|
-
} else {
|
|
1393
|
-
if (streamBlock.content.length === 0) {
|
|
1394
|
-
streamBlock.content.push(chunk);
|
|
1395
|
-
} else {
|
|
1396
|
-
const last = streamBlock.content.at(-1);
|
|
1397
|
-
invariant4(last, void 0, {
|
|
1398
|
-
F: __dxlog_file5,
|
|
1399
|
-
L: 178,
|
|
1400
|
-
S: this,
|
|
1401
|
-
A: [
|
|
1402
|
-
"last",
|
|
1403
|
-
""
|
|
1404
|
-
]
|
|
1405
|
-
});
|
|
1406
|
-
if (last.type === "text") {
|
|
1407
|
-
last.content += chunk.content;
|
|
1408
|
-
} else {
|
|
1409
|
-
streamBlock.content.push(chunk);
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
break;
|
|
1414
|
-
}
|
|
1415
|
-
//
|
|
1416
|
-
// Text Fragment.
|
|
1417
|
-
//
|
|
1418
|
-
case "text": {
|
|
1419
|
-
if (chunk.type === "tag") {
|
|
1420
|
-
this._emitBlock(contentBlock, streamBlock);
|
|
1421
|
-
if (chunk.selfClosing) {
|
|
1422
|
-
this._emitBlock(contentBlock, chunk);
|
|
1423
|
-
streamBlock = void 0;
|
|
1424
|
-
} else {
|
|
1425
|
-
streamBlock = chunk;
|
|
1426
|
-
}
|
|
1427
|
-
} else {
|
|
1428
|
-
streamBlock.content += chunk.content;
|
|
1429
|
-
}
|
|
1430
|
-
break;
|
|
1431
|
-
}
|
|
1432
|
-
//
|
|
1433
|
-
// No current chunk.
|
|
1434
|
-
//
|
|
1435
|
-
default: {
|
|
1436
|
-
if (chunk.type === "tag" && chunk.selfClosing) {
|
|
1437
|
-
this._emitBlock(contentBlock, chunk);
|
|
1438
|
-
} else {
|
|
1439
|
-
streamBlock = chunk;
|
|
1440
|
-
}
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
break;
|
|
1445
|
-
}
|
|
1446
|
-
//
|
|
1447
|
-
// JSON
|
|
1448
|
-
//
|
|
1449
|
-
case "input_json_delta": {
|
|
1450
|
-
if (!contentBlock) {
|
|
1451
|
-
log5.warn("unexpected input_json_delta", {
|
|
1452
|
-
contentBlock
|
|
1453
|
-
}, {
|
|
1454
|
-
F: __dxlog_file5,
|
|
1455
|
-
L: 228,
|
|
1456
|
-
S: this,
|
|
1457
|
-
C: (f, a) => f(...a)
|
|
1458
|
-
});
|
|
1459
|
-
break;
|
|
1460
|
-
}
|
|
1461
|
-
if (streamBlock?.type === "json") {
|
|
1462
|
-
streamBlock.content += event.delta.partial_json;
|
|
1463
|
-
} else {
|
|
1464
|
-
streamBlock = {
|
|
1465
|
-
type: "json",
|
|
1466
|
-
content: event.delta.partial_json
|
|
1467
|
-
};
|
|
1468
|
-
}
|
|
1469
|
-
break;
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
break;
|
|
1473
|
-
}
|
|
1474
|
-
case "content_block_stop": {
|
|
1475
|
-
if (!contentBlock) {
|
|
1476
|
-
log5.warn("unexpected content_block_stop", void 0, {
|
|
1477
|
-
F: __dxlog_file5,
|
|
1478
|
-
L: 245,
|
|
1479
|
-
S: this,
|
|
1480
|
-
C: (f, a) => f(...a)
|
|
1481
|
-
});
|
|
1482
|
-
break;
|
|
1483
|
-
}
|
|
1484
|
-
this._emitBlock(contentBlock, streamBlock);
|
|
1485
|
-
contentBlock = void 0;
|
|
1486
|
-
streamBlock = void 0;
|
|
1487
|
-
break;
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
if (contentBlock && streamBlock) {
|
|
1491
|
-
this._emitUpdate(contentBlock, streamBlock);
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1494
|
-
return messagesCollected;
|
|
1495
|
-
}
|
|
1496
|
-
};
|
|
1497
|
-
var mergeMessageBlock = (contentBlock, streamBlock) => {
|
|
1498
|
-
log5("mergeMessageBlock", {
|
|
1499
|
-
contentBlock,
|
|
1500
|
-
streamBlock
|
|
1501
|
-
}, {
|
|
1502
|
-
F: __dxlog_file5,
|
|
1503
|
-
L: 272,
|
|
1504
|
-
S: void 0,
|
|
1505
|
-
C: (f, a) => f(...a)
|
|
1506
|
-
});
|
|
1507
|
-
switch (streamBlock.type) {
|
|
1508
|
-
//
|
|
1509
|
-
// Text
|
|
1510
|
-
//
|
|
1511
|
-
case "text": {
|
|
1512
|
-
return {
|
|
1513
|
-
...contentBlock,
|
|
1514
|
-
type: "text",
|
|
1515
|
-
text: streamBlock.content
|
|
1516
|
-
};
|
|
1517
|
-
}
|
|
1518
|
-
//
|
|
1519
|
-
// XML
|
|
1520
|
-
//
|
|
1521
|
-
case "tag": {
|
|
1522
|
-
switch (streamBlock.tag) {
|
|
1523
|
-
case "cot": {
|
|
1524
|
-
const content = streamBlock.content.map((block) => {
|
|
1525
|
-
switch (block.type) {
|
|
1526
|
-
case "text":
|
|
1527
|
-
return block.content;
|
|
1528
|
-
default:
|
|
1529
|
-
return null;
|
|
1530
|
-
}
|
|
1531
|
-
}).filter(isNotFalsy).join("\n");
|
|
1532
|
-
return {
|
|
1533
|
-
...contentBlock,
|
|
1534
|
-
type: "text",
|
|
1535
|
-
disposition: "cot",
|
|
1536
|
-
text: content
|
|
1537
|
-
};
|
|
1538
|
-
}
|
|
1539
|
-
case "artifact": {
|
|
1540
|
-
const { attributes } = streamBlock;
|
|
1541
|
-
return {
|
|
1542
|
-
type: "json",
|
|
1543
|
-
disposition: "artifact",
|
|
1544
|
-
json: JSON.stringify(attributes)
|
|
1545
|
-
};
|
|
1546
|
-
}
|
|
1547
|
-
case "suggest": {
|
|
1548
|
-
if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
|
|
1549
|
-
return {
|
|
1550
|
-
type: "json",
|
|
1551
|
-
disposition: "suggest",
|
|
1552
|
-
json: JSON.stringify({
|
|
1553
|
-
text: streamBlock.content[0].content
|
|
1554
|
-
})
|
|
1555
|
-
};
|
|
1556
|
-
}
|
|
1557
|
-
break;
|
|
1558
|
-
}
|
|
1559
|
-
case "proposal": {
|
|
1560
|
-
if (streamBlock.content.length === 1 && streamBlock.content[0].type === "text") {
|
|
1561
|
-
return {
|
|
1562
|
-
type: "json",
|
|
1563
|
-
disposition: "proposal",
|
|
1564
|
-
json: JSON.stringify({
|
|
1565
|
-
text: streamBlock.content[0].content
|
|
1566
|
-
})
|
|
1567
|
-
};
|
|
1568
|
-
}
|
|
1569
|
-
break;
|
|
1570
|
-
}
|
|
1571
|
-
case "select": {
|
|
1572
|
-
return {
|
|
1573
|
-
type: "json",
|
|
1574
|
-
disposition: "select",
|
|
1575
|
-
json: JSON.stringify({
|
|
1576
|
-
options: streamBlock.content.flatMap((content) => content.type === "tag" && content.content.length === 1 && content.content[0].type === "text" ? [
|
|
1577
|
-
content.content[0].content
|
|
1578
|
-
] : [])
|
|
1579
|
-
})
|
|
1580
|
-
};
|
|
1581
|
-
}
|
|
1582
|
-
case "tool-list": {
|
|
1583
|
-
return {
|
|
1584
|
-
type: "json",
|
|
1585
|
-
disposition: "tool_list",
|
|
1586
|
-
json: JSON.stringify({})
|
|
1587
|
-
};
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
break;
|
|
1591
|
-
}
|
|
1592
|
-
//
|
|
1593
|
-
// JSON
|
|
1594
|
-
//
|
|
1595
|
-
case "json": {
|
|
1596
|
-
switch (contentBlock.type) {
|
|
1597
|
-
case "tool_use": {
|
|
1598
|
-
return {
|
|
1599
|
-
...contentBlock,
|
|
1600
|
-
input: safeParseJson(streamBlock.content) ?? {}
|
|
1601
|
-
};
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
|
-
return {
|
|
1605
|
-
...contentBlock,
|
|
1606
|
-
type: "json",
|
|
1607
|
-
disposition: "artifact",
|
|
1608
|
-
json: streamBlock.content
|
|
1609
|
-
};
|
|
1610
|
-
}
|
|
1611
|
-
}
|
|
1612
|
-
};
|
|
1613
|
-
|
|
1614
|
-
// packages/experimental/assistant/src/session/session.ts
|
|
1615
|
-
function _ts_decorate(decorators, target, key, desc) {
|
|
1616
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
1617
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
1618
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
1619
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
1620
|
-
}
|
|
1621
|
-
var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/session/session.ts";
|
|
1622
|
-
var AISession = class _AISession {
|
|
1623
|
-
constructor(_options) {
|
|
1624
|
-
this._options = _options;
|
|
1625
|
-
this._parser = new MixedStreamParser();
|
|
1626
|
-
this._pending = [];
|
|
1627
|
-
this._history = [];
|
|
1628
|
-
this.message = this._parser.message;
|
|
1629
|
-
this.block = this._parser.block;
|
|
1630
|
-
this.update = this._parser.update;
|
|
1631
|
-
this.streamEvent = this._parser.streamEvent;
|
|
1632
|
-
this.userMessage = new Event2();
|
|
1633
|
-
this._parser.message.on((message) => {
|
|
1634
|
-
this._pending.push(message);
|
|
1635
|
-
});
|
|
1636
|
-
}
|
|
1637
|
-
async run(options) {
|
|
1638
|
-
const systemTools = [];
|
|
1639
|
-
switch (this._options.operationModel) {
|
|
1640
|
-
case "planning":
|
|
1641
|
-
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
|
|
1642
|
-
break;
|
|
1643
|
-
case "importing":
|
|
1644
|
-
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
|
|
1645
|
-
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
1646
|
-
requiredArtifactIds.add(artifactDefinitionId);
|
|
1647
|
-
}
|
|
1648
|
-
}));
|
|
1649
|
-
break;
|
|
1650
|
-
case "configured":
|
|
1651
|
-
break;
|
|
1652
|
-
default:
|
|
1653
|
-
throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
|
|
1654
|
-
}
|
|
1655
|
-
this._history = [
|
|
1656
|
-
...options.history
|
|
1657
|
-
];
|
|
1658
|
-
this._pending = [
|
|
1659
|
-
await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)
|
|
1660
|
-
];
|
|
1661
|
-
this.userMessage.emit(this._pending.at(-1));
|
|
1662
|
-
this._stream = void 0;
|
|
1663
|
-
let error;
|
|
1664
|
-
const requiredArtifactIds = new Set(options.requiredArtifactIds ?? []);
|
|
1665
|
-
try {
|
|
1666
|
-
let more = false;
|
|
1667
|
-
do {
|
|
1668
|
-
const tools = [
|
|
1669
|
-
...systemTools,
|
|
1670
|
-
...options.tools,
|
|
1671
|
-
...options.artifacts.filter((artifact) => requiredArtifactIds.has(artifact.id)).flatMap((artifact) => artifact.tools)
|
|
1672
|
-
];
|
|
1673
|
-
log6("request", {
|
|
1674
|
-
pending: this._pending.length,
|
|
1675
|
-
history: this._history.length,
|
|
1676
|
-
tools: tools.map((tool) => tool.name)
|
|
1677
|
-
}, {
|
|
1678
|
-
F: __dxlog_file6,
|
|
1679
|
-
L: 181,
|
|
1680
|
-
S: this,
|
|
1681
|
-
C: (f, a) => f(...a)
|
|
1682
|
-
});
|
|
1683
|
-
this._stream = await options.client.execStream({
|
|
1684
|
-
...options.generationOptions ?? {},
|
|
1685
|
-
// TODO(burdon): Rename messages or separate history/message.
|
|
1686
|
-
history: [
|
|
1687
|
-
...this._history,
|
|
1688
|
-
...this._pending
|
|
1689
|
-
],
|
|
1690
|
-
tools,
|
|
1691
|
-
systemPrompt: options.systemPrompt ?? createBaseInstructions({
|
|
1692
|
-
availableArtifacts: Array.from(requiredArtifactIds),
|
|
1693
|
-
operationModel: this._options.operationModel
|
|
1694
|
-
})
|
|
1695
|
-
});
|
|
1696
|
-
await this._parser.parse(this._stream);
|
|
1697
|
-
await this._stream.complete();
|
|
1698
|
-
log6("response", {
|
|
1699
|
-
pending: this._pending
|
|
1700
|
-
}, {
|
|
1701
|
-
F: __dxlog_file6,
|
|
1702
|
-
L: 206,
|
|
1703
|
-
S: this,
|
|
1704
|
-
C: (f, a) => f(...a)
|
|
1705
|
-
});
|
|
1706
|
-
more = false;
|
|
1707
|
-
const message = this._pending.at(-1);
|
|
1708
|
-
invariant5(message, void 0, {
|
|
1709
|
-
F: __dxlog_file6,
|
|
1710
|
-
L: 211,
|
|
1711
|
-
S: this,
|
|
1712
|
-
A: [
|
|
1713
|
-
"message",
|
|
1714
|
-
""
|
|
1715
|
-
]
|
|
1716
|
-
});
|
|
1717
|
-
if (isToolUse(message)) {
|
|
1718
|
-
log6("tool request...", void 0, {
|
|
1719
|
-
F: __dxlog_file6,
|
|
1720
|
-
L: 213,
|
|
1721
|
-
S: this,
|
|
1722
|
-
C: (f, a) => f(...a)
|
|
1723
|
-
});
|
|
1724
|
-
const response = await runTools({
|
|
1725
|
-
message: this._pending.at(-1),
|
|
1726
|
-
tools,
|
|
1727
|
-
extensions: options.extensions ?? {}
|
|
1728
|
-
});
|
|
1729
|
-
log6("tool response", {
|
|
1730
|
-
response
|
|
1731
|
-
}, {
|
|
1732
|
-
F: __dxlog_file6,
|
|
1733
|
-
L: 220,
|
|
1734
|
-
S: this,
|
|
1735
|
-
C: (f, a) => f(...a)
|
|
1736
|
-
});
|
|
1737
|
-
switch (response.type) {
|
|
1738
|
-
case "continue": {
|
|
1739
|
-
this._pending = [
|
|
1740
|
-
...this._pending,
|
|
1741
|
-
response.message
|
|
1742
|
-
];
|
|
1743
|
-
this.userMessage.emit(response.message);
|
|
1744
|
-
more = true;
|
|
1745
|
-
break;
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
} while (more);
|
|
1750
|
-
} catch (err) {
|
|
1751
|
-
log6.catch(err, void 0, {
|
|
1752
|
-
F: __dxlog_file6,
|
|
1753
|
-
L: 232,
|
|
1754
|
-
S: this,
|
|
1755
|
-
C: (f, a) => f(...a)
|
|
1756
|
-
});
|
|
1757
|
-
if (err instanceof Error && err.message.includes("Overloaded")) {
|
|
1758
|
-
error = new AIServiecOverloadedError("AI service overloaded", {
|
|
1759
|
-
cause: err
|
|
1760
|
-
});
|
|
1761
|
-
} else {
|
|
1762
|
-
error = new Error("AI service error", {
|
|
1763
|
-
cause: err
|
|
1764
|
-
});
|
|
1765
|
-
}
|
|
1766
|
-
} finally {
|
|
1767
|
-
this._stream = void 0;
|
|
1768
|
-
}
|
|
1769
|
-
if (error) {
|
|
1770
|
-
throw error;
|
|
1771
|
-
}
|
|
1772
|
-
return this._pending;
|
|
1773
|
-
}
|
|
1774
|
-
async runStructured(schema, options) {
|
|
1775
|
-
const parser = structuredOutputParser(schema);
|
|
1776
|
-
const result = await this.run({
|
|
1777
|
-
...options,
|
|
1778
|
-
tools: [
|
|
1779
|
-
...options.tools,
|
|
1780
|
-
parser.tool
|
|
1781
|
-
]
|
|
1782
|
-
});
|
|
1783
|
-
return parser.getResult(result);
|
|
1784
|
-
}
|
|
1785
|
-
async _formatUserPrompt(artifactDiffResolver, prompt, history) {
|
|
1786
|
-
const prelude = [];
|
|
1787
|
-
if (artifactDiffResolver) {
|
|
1788
|
-
const versions = gatherObjectVersions(history);
|
|
1789
|
-
const artifactDiff = await artifactDiffResolver(Array.from(versions.entries()).map(([id, version]) => ({
|
|
1790
|
-
id,
|
|
1791
|
-
lastVersion: version
|
|
1792
|
-
})));
|
|
1793
|
-
log6.info("vision", {
|
|
1794
|
-
artifactDiff,
|
|
1795
|
-
versions
|
|
1796
|
-
}, {
|
|
1797
|
-
F: __dxlog_file6,
|
|
1798
|
-
L: 272,
|
|
1799
|
-
S: this,
|
|
1800
|
-
C: (f, a) => f(...a)
|
|
1801
|
-
});
|
|
1802
|
-
for (const [id, { version }] of [
|
|
1803
|
-
...artifactDiff.entries()
|
|
1804
|
-
]) {
|
|
1805
|
-
if (ObjectVersion.equals(version, versions.get(id))) {
|
|
1806
|
-
artifactDiff.delete(id);
|
|
1807
|
-
continue;
|
|
1808
|
-
}
|
|
1809
|
-
prelude.push(VersionPin.createBlock(VersionPin.make({
|
|
1810
|
-
objectId: id,
|
|
1811
|
-
version
|
|
1812
|
-
})));
|
|
1813
|
-
}
|
|
1814
|
-
if (artifactDiff.size > 0) {
|
|
1815
|
-
prelude.push(createArtifactUpdateBlock(artifactDiff));
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
return create3(Message4, {
|
|
1819
|
-
role: "user",
|
|
1820
|
-
content: [
|
|
1821
|
-
...prelude,
|
|
1822
|
-
{
|
|
1823
|
-
type: "text",
|
|
1824
|
-
text: prompt
|
|
1825
|
-
}
|
|
1826
|
-
]
|
|
1827
|
-
});
|
|
1828
|
-
}
|
|
1829
|
-
_createQueryArtifactsTool(artifacts) {
|
|
1830
|
-
return defineTool2("system", {
|
|
1831
|
-
name: "query_artifact_definitions",
|
|
1832
|
-
description: "Query the available artifact definitions",
|
|
1833
|
-
schema: Schema4.Struct({}),
|
|
1834
|
-
execute: async () => {
|
|
1835
|
-
return ToolResult3.Success({
|
|
1836
|
-
artifactDefinitions: artifacts.map((artifact) => ({
|
|
1837
|
-
id: artifact.id,
|
|
1838
|
-
name: artifact.name,
|
|
1839
|
-
description: artifact.description
|
|
1840
|
-
}))
|
|
1841
|
-
});
|
|
1842
|
-
}
|
|
1843
|
-
});
|
|
1844
|
-
}
|
|
1845
|
-
_createRequireTool(artifacts, onRequire) {
|
|
1846
|
-
return defineTool2("system", {
|
|
1847
|
-
name: "require_artifact_definitions",
|
|
1848
|
-
description: "Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.",
|
|
1849
|
-
schema: Schema4.Struct({
|
|
1850
|
-
artifactDefinitionIds: Schema4.Array(Schema4.String).annotations({
|
|
1851
|
-
description: "The ids of the artifact definitions to require",
|
|
1852
|
-
examples: [
|
|
1853
|
-
[
|
|
1854
|
-
"artifact:dxos.org/example/Test"
|
|
1855
|
-
]
|
|
1856
|
-
]
|
|
1857
|
-
})
|
|
1858
|
-
}),
|
|
1859
|
-
execute: async ({ artifactDefinitionIds }) => {
|
|
1860
|
-
const missingArtifactDefinitionIds = artifactDefinitionIds.filter((artifactId) => !artifacts.some((artifact) => artifact.id === artifactId));
|
|
1861
|
-
if (missingArtifactDefinitionIds.length > 0) {
|
|
1862
|
-
return ToolResult3.Error(`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(", ")}`);
|
|
1863
|
-
}
|
|
1864
|
-
onRequire(artifactDefinitionIds);
|
|
1865
|
-
return ToolResult3.Success({});
|
|
1866
|
-
}
|
|
1867
|
-
});
|
|
1868
|
-
}
|
|
1869
|
-
_createPlanningTool(options) {
|
|
1870
|
-
return defineTool2("system", {
|
|
1871
|
-
name: "create_plan",
|
|
1872
|
-
description: "Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.",
|
|
1873
|
-
schema: Schema4.Struct({
|
|
1874
|
-
goal: Schema4.String.annotations({
|
|
1875
|
-
description: "The goal that the plan will achieve."
|
|
1876
|
-
}),
|
|
1877
|
-
steps: Schema4.Array(Schema4.Struct({
|
|
1878
|
-
action: Schema4.String.annotations({
|
|
1879
|
-
description: "Complete, detailed action to perform."
|
|
1880
|
-
}),
|
|
1881
|
-
input: Schema4.String.annotations({
|
|
1882
|
-
description: "The required input data for this step. First step must not require any data."
|
|
1883
|
-
}),
|
|
1884
|
-
output: Schema4.String.annotations({
|
|
1885
|
-
description: "The output data from this step. This is passed to the next step as input."
|
|
1886
|
-
}),
|
|
1887
|
-
requiredArtifactIds: Schema4.Array(Schema4.String).annotations({
|
|
1888
|
-
description: "The ids of the artifacts required to perform this step.",
|
|
1889
|
-
examples: [
|
|
1890
|
-
[
|
|
1891
|
-
"artifact:dxos.org/example/Test"
|
|
1892
|
-
]
|
|
1893
|
-
]
|
|
1894
|
-
})
|
|
1895
|
-
})).annotations({
|
|
1896
|
-
description: "Steps"
|
|
1897
|
-
})
|
|
1898
|
-
}),
|
|
1899
|
-
execute: async ({ goal, steps }) => {
|
|
1900
|
-
const missingArtifactIds = steps.flatMap((step) => step.requiredArtifactIds).filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
1901
|
-
if (missingArtifactIds.length > 0) {
|
|
1902
|
-
return ToolResult3.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(", ")}`);
|
|
1903
|
-
}
|
|
1904
|
-
const stepResults = [];
|
|
1905
|
-
for (const step of steps) {
|
|
1906
|
-
log6("executing step", {
|
|
1907
|
-
action: step.action
|
|
1908
|
-
}, {
|
|
1909
|
-
F: __dxlog_file6,
|
|
1910
|
-
L: 379,
|
|
1911
|
-
S: this,
|
|
1912
|
-
C: (f, a) => f(...a)
|
|
1913
|
-
});
|
|
1914
|
-
const session = new _AISession({
|
|
1915
|
-
operationModel: "importing"
|
|
1916
|
-
});
|
|
1917
|
-
session.message.on((ev) => this.message.emit(ev));
|
|
1918
|
-
session.block.on((ev) => this.block.emit(ev));
|
|
1919
|
-
session.update.on((ev) => this.update.emit(ev));
|
|
1920
|
-
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
1921
|
-
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
1922
|
-
const messages = await session.run({
|
|
1923
|
-
client: options.client,
|
|
1924
|
-
artifacts: options.artifacts,
|
|
1925
|
-
tools: options.tools,
|
|
1926
|
-
history: options.history,
|
|
1927
|
-
extensions: options.extensions,
|
|
1928
|
-
generationOptions: options.generationOptions,
|
|
1929
|
-
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
1930
|
-
artifactDiffResolver: options.artifactDiffResolver,
|
|
1931
|
-
prompt: `
|
|
1932
|
-
You are an agent that executes the subtask in a plan.
|
|
1933
|
-
|
|
1934
|
-
While you know the plan's goal only focus on your subtask
|
|
1935
|
-
Use the data from the previous step to complete your task.
|
|
1936
|
-
Return all of the data from "output" in your last message.
|
|
1937
|
-
|
|
1938
|
-
Current step (that you need to complete):
|
|
1939
|
-
${JSON.stringify({
|
|
1940
|
-
goal,
|
|
1941
|
-
input: step.input,
|
|
1942
|
-
output: step.output,
|
|
1943
|
-
yourTask: step.action
|
|
1944
|
-
}, null, 2)}
|
|
1945
|
-
|
|
1946
|
-
Previous step results:
|
|
1947
|
-
${JSON.stringify(stepResults.at(-1))}.
|
|
1948
|
-
`
|
|
1949
|
-
});
|
|
1950
|
-
const result = messages.at(-1);
|
|
1951
|
-
stepResults.push(result);
|
|
1952
|
-
}
|
|
1953
|
-
return ToolResult3.Success({
|
|
1954
|
-
stepResults
|
|
1955
|
-
});
|
|
1956
|
-
}
|
|
1957
|
-
});
|
|
1958
|
-
}
|
|
1959
|
-
abort() {
|
|
1960
|
-
this._stream?.abort();
|
|
1961
|
-
}
|
|
1962
|
-
};
|
|
1963
|
-
_ts_decorate([
|
|
1964
|
-
synchronized
|
|
1965
|
-
], AISession.prototype, "run", null);
|
|
1966
|
-
var createBaseInstructions = ({ availableArtifacts, operationModel }) => `
|
|
1967
|
-
You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
|
|
1968
|
-
Your task is to process user commands and questions and decide how best to respond.
|
|
1969
|
-
In some cases, you will need to create or reference data objects called artifacts.
|
|
1970
|
-
|
|
1971
|
-
Follow these guidelines carefully:
|
|
1972
|
-
|
|
1973
|
-
Decision-making:
|
|
1974
|
-
|
|
1975
|
-
- Analyze the structure and type of the content in the user's message.
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
${operationModel === "planning" ? `
|
|
1979
|
-
- Can you complete the task using the available artifacts?
|
|
1980
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
1981
|
-
- Identify which artifacts are relevant to the user's request.
|
|
1982
|
-
- Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
|
|
1983
|
-
` : ""}
|
|
1984
|
-
${operationModel === "importing" ? `
|
|
1985
|
-
- Can you complete the task using the available artifacts?
|
|
1986
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
1987
|
-
- Identify which artifacts are relevant to the user's request.
|
|
1988
|
-
- Are the required artifacts already available?
|
|
1989
|
-
- If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
|
|
1990
|
-
- The require'd artifact tools will be available for use after require.
|
|
1991
|
-
` : ""}
|
|
1992
|
-
${operationModel === "configured" ? `
|
|
1993
|
-
- Select the most relevant artifact(s) to complete the task.
|
|
1994
|
-
- Call the appropriate tool to use the artifact(s).
|
|
1995
|
-
` : ""}
|
|
1996
|
-
|
|
1997
|
-
${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join("\n")}` : ""}
|
|
1998
|
-
`;
|
|
1999
|
-
var AIServiecOverloadedError = class extends Schema4.TaggedError()("AIServiecOverloadedError", {}) {
|
|
2000
|
-
};
|
|
2001
|
-
var gatherObjectVersions = (messages) => {
|
|
2002
|
-
const artifactIds = /* @__PURE__ */ new Map();
|
|
2003
|
-
for (const message of messages) {
|
|
2004
|
-
for (const block of message.content) {
|
|
2005
|
-
if (block.type === "json" && block.disposition === VersionPin.DISPOSITION) {
|
|
2006
|
-
const pin = VersionPin.pipe(Schema4.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
|
|
2007
|
-
if (!pin) {
|
|
2008
|
-
continue;
|
|
2009
|
-
}
|
|
2010
|
-
artifactIds.set(pin.objectId, pin.version);
|
|
2011
|
-
}
|
|
2012
|
-
}
|
|
2013
|
-
}
|
|
2014
|
-
return artifactIds;
|
|
2015
|
-
};
|
|
2016
|
-
var createArtifactUpdateBlock = (artifactDiff) => {
|
|
2017
|
-
return {
|
|
2018
|
-
type: "text",
|
|
2019
|
-
disposition: "artifact-update",
|
|
2020
|
-
text: `
|
|
2021
|
-
The following artifacts have been updated since the last message:
|
|
2022
|
-
${Array.from(artifactDiff.entries()).map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `
|
|
2023
|
-
${diff}` : ""}</changed-artifact>`).join("\n")}
|
|
2024
|
-
`
|
|
2025
|
-
};
|
|
2026
|
-
};
|
|
2027
|
-
|
|
2028
|
-
// packages/experimental/assistant/src/experimental/conversation/conversation.ts
|
|
2029
|
-
import { ObjectId as ObjectId3 } from "@dxos/echo-schema";
|
|
2030
|
-
import { invariant as invariant6 } from "@dxos/invariant";
|
|
2031
|
-
import { log as log7 } from "@dxos/log";
|
|
2032
|
-
var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/conversation/conversation.ts";
|
|
2033
|
-
var runLLM = async (params) => {
|
|
2034
|
-
let conversationResult = null;
|
|
2035
|
-
const history = params.history ?? [];
|
|
2036
|
-
const generate = async () => {
|
|
2037
|
-
log7("llm generate", {
|
|
2038
|
-
tools: params.tools
|
|
2039
|
-
}, {
|
|
2040
|
-
F: __dxlog_file7,
|
|
2041
|
-
L: 44,
|
|
2042
|
-
S: void 0,
|
|
2043
|
-
C: (f, a) => f(...a)
|
|
2044
|
-
});
|
|
2045
|
-
const beginTs = Date.now();
|
|
2046
|
-
const stream = await params.client.execStream({
|
|
2047
|
-
model: params.model,
|
|
2048
|
-
history,
|
|
2049
|
-
systemPrompt: params.system,
|
|
2050
|
-
tools: params.tools
|
|
2051
|
-
});
|
|
2052
|
-
for await (const event of stream) {
|
|
2053
|
-
params.logger?.(event);
|
|
2054
|
-
}
|
|
2055
|
-
await stream.complete();
|
|
2056
|
-
const messages = [];
|
|
2057
|
-
const message = messages.at(-1);
|
|
2058
|
-
invariant6(message, void 0, {
|
|
2059
|
-
F: __dxlog_file7,
|
|
2060
|
-
L: 61,
|
|
2061
|
-
S: void 0,
|
|
2062
|
-
A: [
|
|
2063
|
-
"message",
|
|
2064
|
-
""
|
|
2065
|
-
]
|
|
2066
|
-
});
|
|
2067
|
-
log7("llm result", {
|
|
2068
|
-
time: Date.now() - beginTs,
|
|
2069
|
-
message
|
|
2070
|
-
}, {
|
|
2071
|
-
F: __dxlog_file7,
|
|
2072
|
-
L: 63,
|
|
2073
|
-
S: void 0,
|
|
2074
|
-
C: (f, a) => f(...a)
|
|
2075
|
-
});
|
|
2076
|
-
invariant6(message, void 0, {
|
|
2077
|
-
F: __dxlog_file7,
|
|
2078
|
-
L: 64,
|
|
2079
|
-
S: void 0,
|
|
2080
|
-
A: [
|
|
2081
|
-
"message",
|
|
2082
|
-
""
|
|
2083
|
-
]
|
|
2084
|
-
});
|
|
2085
|
-
params.logger?.({
|
|
2086
|
-
type: "message",
|
|
2087
|
-
message
|
|
2088
|
-
});
|
|
2089
|
-
history.push(...messages.map((message2) => ({
|
|
2090
|
-
...message2,
|
|
2091
|
-
content: message2.content.filter((block) => block.type !== "image")
|
|
2092
|
-
})));
|
|
2093
|
-
const isToolUse2 = message.content.at(-1)?.type === "tool_use";
|
|
2094
|
-
if (isToolUse2) {
|
|
2095
|
-
const toolCalls = message.content.filter((block) => block.type === "tool_use");
|
|
2096
|
-
invariant6(toolCalls.length === 1, void 0, {
|
|
2097
|
-
F: __dxlog_file7,
|
|
2098
|
-
L: 75,
|
|
2099
|
-
S: void 0,
|
|
2100
|
-
A: [
|
|
2101
|
-
"toolCalls.length === 1",
|
|
2102
|
-
""
|
|
2103
|
-
]
|
|
2104
|
-
});
|
|
2105
|
-
const toolCall = toolCalls[0];
|
|
2106
|
-
const tool = params.tools.find((tool2) => tool2.name === toolCall.name);
|
|
2107
|
-
if (!tool) {
|
|
2108
|
-
throw new Error(`Tool not found: ${toolCall.name}`);
|
|
2109
|
-
}
|
|
2110
|
-
invariant6(tool.execute, void 0, {
|
|
2111
|
-
F: __dxlog_file7,
|
|
2112
|
-
L: 82,
|
|
2113
|
-
S: void 0,
|
|
2114
|
-
A: [
|
|
2115
|
-
"tool.execute",
|
|
2116
|
-
""
|
|
2117
|
-
]
|
|
2118
|
-
});
|
|
2119
|
-
const toolResult = await tool.execute(toolCall.input);
|
|
2120
|
-
switch (toolResult.kind) {
|
|
2121
|
-
case "error": {
|
|
2122
|
-
log7.warn("tool error", {
|
|
2123
|
-
message: toolResult.message
|
|
2124
|
-
}, {
|
|
2125
|
-
F: __dxlog_file7,
|
|
2126
|
-
L: 86,
|
|
2127
|
-
S: void 0,
|
|
2128
|
-
C: (f, a) => f(...a)
|
|
2129
|
-
});
|
|
2130
|
-
const resultMessage = {
|
|
2131
|
-
id: ObjectId3.random(),
|
|
2132
|
-
role: "user",
|
|
2133
|
-
content: [
|
|
2134
|
-
{
|
|
2135
|
-
type: "tool_result",
|
|
2136
|
-
toolUseId: toolCall.id,
|
|
2137
|
-
content: toolResult.message,
|
|
2138
|
-
isError: true
|
|
2139
|
-
}
|
|
2140
|
-
]
|
|
2141
|
-
};
|
|
2142
|
-
params.logger?.({
|
|
2143
|
-
type: "message",
|
|
2144
|
-
message: resultMessage
|
|
2145
|
-
});
|
|
2146
|
-
history.push(resultMessage);
|
|
2147
|
-
return true;
|
|
2148
|
-
}
|
|
2149
|
-
case "success": {
|
|
2150
|
-
log7("tool success", {
|
|
2151
|
-
result: toolResult.result
|
|
2152
|
-
}, {
|
|
2153
|
-
F: __dxlog_file7,
|
|
2154
|
-
L: 106,
|
|
2155
|
-
S: void 0,
|
|
2156
|
-
C: (f, a) => f(...a)
|
|
2157
|
-
});
|
|
2158
|
-
const resultMessage = {
|
|
2159
|
-
id: ObjectId3.random(),
|
|
2160
|
-
role: "user",
|
|
2161
|
-
content: [
|
|
2162
|
-
{
|
|
2163
|
-
type: "tool_result",
|
|
2164
|
-
toolUseId: toolCall.id,
|
|
2165
|
-
content: JSON.stringify(toolResult.result)
|
|
2166
|
-
}
|
|
2167
|
-
]
|
|
2168
|
-
};
|
|
2169
|
-
params.logger?.({
|
|
2170
|
-
type: "message",
|
|
2171
|
-
message: resultMessage
|
|
2172
|
-
});
|
|
2173
|
-
history.push(resultMessage);
|
|
2174
|
-
return true;
|
|
2175
|
-
}
|
|
2176
|
-
case "break": {
|
|
2177
|
-
log7("tool break", {
|
|
2178
|
-
result: toolResult.result
|
|
2179
|
-
}, {
|
|
2180
|
-
F: __dxlog_file7,
|
|
2181
|
-
L: 125,
|
|
2182
|
-
S: void 0,
|
|
2183
|
-
C: (f, a) => f(...a)
|
|
2184
|
-
});
|
|
2185
|
-
conversationResult = toolResult.result;
|
|
2186
|
-
return false;
|
|
2187
|
-
}
|
|
2188
|
-
}
|
|
2189
|
-
}
|
|
2190
|
-
return false;
|
|
2191
|
-
};
|
|
2192
|
-
while (await generate()) {
|
|
2193
|
-
}
|
|
2194
|
-
return {
|
|
2195
|
-
result: conversationResult,
|
|
2196
|
-
history
|
|
2197
|
-
};
|
|
2198
|
-
};
|
|
2199
|
-
|
|
2200
|
-
// packages/experimental/assistant/src/experimental/cypher/parjs.ts
|
|
2201
|
-
import { parjsCombinators, parjs } from "#parjs";
|
|
2202
|
-
|
|
2203
|
-
// packages/experimental/assistant/src/experimental/cypher/combinators.ts
|
|
2204
|
-
var ws = parjs.whitespace();
|
|
2205
|
-
var nothing = parjs.string("").pipe(parjsCombinators.map(() => null));
|
|
2206
|
-
var optional = (parser) => parser.pipe(parjsCombinators.recover(() => ({
|
|
2207
|
-
kind: "Soft"
|
|
2208
|
-
})), parjsCombinators.or(nothing));
|
|
2209
|
-
var keyword = (word) => parjs.string(word).pipe(parjsCombinators.map(() => word));
|
|
2210
|
-
var identifier = parjs.regexp(/[a-zA-Z_][a-zA-Z0-9_]*/).pipe(parjsCombinators.map((match) => ({
|
|
2211
|
-
astKind: "Identifier",
|
|
2212
|
-
name: match[0]
|
|
2213
|
-
})));
|
|
2214
|
-
var numberLiteral = parjs.regexp(/-?\d+(\.\d+)?/).pipe(parjsCombinators.map(Number));
|
|
2215
|
-
var stringLiteral = parjs.regexp(/"([^"]*)"|'([^']*)'/).pipe(parjsCombinators.map((match) => ({
|
|
2216
|
-
astKind: "StringLiteral",
|
|
2217
|
-
value: match[1] || match[2]
|
|
2218
|
-
})));
|
|
2219
|
-
var variableTag = identifier.pipe(parjsCombinators.map((variable) => variable)).expects("variable tag");
|
|
2220
|
-
var label = identifier.pipe(parjsCombinators.map((name) => name));
|
|
2221
|
-
var property = identifier.pipe(parjsCombinators.then(parjs.string(":"), ws, stringLiteral), parjsCombinators.map(([key, , , value]) => ({
|
|
2222
|
-
key,
|
|
2223
|
-
value
|
|
2224
|
-
})));
|
|
2225
|
-
var properties = property.pipe(parjsCombinators.manySepBy(","), parjsCombinators.between("{", "}"), parjsCombinators.map((properties2) => ({
|
|
2226
|
-
astKind: "Properties",
|
|
2227
|
-
properties: properties2
|
|
2228
|
-
})));
|
|
2229
|
-
var nodePattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("(", ")"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
|
|
2230
|
-
astKind: "NodePattern",
|
|
2231
|
-
variable,
|
|
2232
|
-
label: label2,
|
|
2233
|
-
properties: properties2
|
|
2234
|
-
})));
|
|
2235
|
-
var relationshipPattern = optional(variableTag).pipe(parjsCombinators.then(":"), parjsCombinators.then(ws, label, ws), parjsCombinators.then(optional(properties)), parjsCombinators.between("[", "]"), parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
|
|
2236
|
-
astKind: "RelationshipPattern",
|
|
2237
|
-
variable,
|
|
2238
|
-
label: label2,
|
|
2239
|
-
properties: properties2
|
|
2240
|
-
})));
|
|
2241
|
-
var graphPatternConnector = parjs.string("->").pipe(parjsCombinators.or("<-", "-"), parjsCombinators.map((x) => ({
|
|
2242
|
-
astKind: "GraphPatternConnector",
|
|
2243
|
-
direction: x
|
|
2244
|
-
})));
|
|
2245
|
-
var graphPattern = nodePattern.pipe(parjsCombinators.or(relationshipPattern), parjsCombinators.manySepBy(graphPatternConnector), parjsCombinators.map((segments) => ({
|
|
2246
|
-
astKind: "GraphPattern",
|
|
2247
|
-
segments
|
|
2248
|
-
})));
|
|
2249
|
-
var matchClause = keyword("MATCH").pipe(parjsCombinators.then(ws), parjsCombinators.then(graphPattern), parjsCombinators.map(([, pattern]) => ({
|
|
2250
|
-
astKind: "MatchClause",
|
|
2251
|
-
pattern
|
|
2252
|
-
})));
|
|
2253
|
-
var memberExpression = identifier.pipe(parjsCombinators.manySepBy("."), parjsCombinators.map((path) => ({
|
|
2254
|
-
astKind: "MemberExpression",
|
|
2255
|
-
path
|
|
2256
|
-
})));
|
|
2257
|
-
var equalsPredicate = memberExpression.pipe(parjsCombinators.then(ws, parjs.string("="), ws, stringLiteral), parjsCombinators.map(([left, , , , right]) => ({
|
|
2258
|
-
astKind: "EqualsPredicate",
|
|
2259
|
-
left,
|
|
2260
|
-
right
|
|
2261
|
-
})));
|
|
2262
|
-
var whereClause = keyword("WHERE").pipe(parjsCombinators.then(ws, equalsPredicate.pipe(parjsCombinators.between(ws, ws), parjsCombinators.manySepBy(parjs.string("AND"))), ws), parjsCombinators.map(([, , predicates]) => ({
|
|
2263
|
-
astKind: "WhereClause",
|
|
2264
|
-
predicates
|
|
2265
|
-
})));
|
|
2266
|
-
var returnClause = keyword("RETURN").pipe(parjsCombinators.then(ws, memberExpression.pipe(parjsCombinators.then(optional(parjs.string("AS").pipe(parjsCombinators.between(ws), parjsCombinators.then(identifier))), ws), parjsCombinators.manySepBy(parjs.string(",").pipe(parjsCombinators.then(ws)))), ws), parjsCombinators.map(([, , fields]) => ({
|
|
2267
|
-
astKind: "ReturnClause",
|
|
2268
|
-
fields: fields.map(([f]) => f)
|
|
2269
|
-
})));
|
|
2270
|
-
var cypherQuery = ws.pipe(parjsCombinators.then(matchClause, ws, optional(whereClause), ws, returnClause, ws), parjsCombinators.map(([, matchClause2, , whereClause2, , returnClause2]) => ({
|
|
2271
|
-
astKind: "CypherQuery",
|
|
2272
|
-
matchClause: matchClause2,
|
|
2273
|
-
whereClause: whereClause2,
|
|
2274
|
-
returnClause: returnClause2
|
|
2275
|
-
})));
|
|
2276
|
-
|
|
2277
|
-
// packages/experimental/assistant/src/experimental/cypher/parser.ts
|
|
2278
|
-
var parseCypherQuery = (query) => {
|
|
2279
|
-
const parseResult = cypherQuery.parse(query);
|
|
2280
|
-
if (parseResult.isOk) {
|
|
2281
|
-
return {
|
|
2282
|
-
ast: parseResult.value
|
|
2283
|
-
};
|
|
2284
|
-
} else {
|
|
2285
|
-
throw new Error(`Failed to parse query: ${parseResult}`);
|
|
2286
|
-
}
|
|
2287
|
-
};
|
|
2288
|
-
|
|
2289
|
-
// packages/experimental/assistant/src/experimental/cypher/query-executor.ts
|
|
2290
|
-
import { log as log9 } from "@dxos/log";
|
|
2291
|
-
import { mapValues } from "@dxos/util";
|
|
2292
|
-
|
|
2293
|
-
// packages/experimental/assistant/src/experimental/cypher/execution-plan.ts
|
|
2294
|
-
import { invariant as invariant7 } from "@dxos/invariant";
|
|
2295
|
-
import { log as log8 } from "@dxos/log";
|
|
2296
|
-
var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/execution-plan.ts";
|
|
2297
|
-
var createExecutionPlan = (query) => {
|
|
2298
|
-
return new ExecutionPlanBuilder().build(query);
|
|
2299
|
-
};
|
|
2300
|
-
var ExecutionPlanBuilder = class {
|
|
2301
|
-
constructor() {
|
|
2302
|
-
this.counter = 0;
|
|
2303
|
-
}
|
|
2304
|
-
newVariable() {
|
|
2305
|
-
return `anon_${this.counter++}`;
|
|
2306
|
-
}
|
|
2307
|
-
build(query) {
|
|
2308
|
-
log8("Creating execution plan for query", {
|
|
2309
|
-
query
|
|
2310
|
-
}, {
|
|
2311
|
-
F: __dxlog_file8,
|
|
2312
|
-
L: 76,
|
|
2313
|
-
S: this,
|
|
2314
|
-
C: (f, a) => f(...a)
|
|
2315
|
-
});
|
|
2316
|
-
return {
|
|
2317
|
-
steps: [
|
|
2318
|
-
...this.createStepsForMatchClause(query.ast.matchClause),
|
|
2319
|
-
...query.ast.whereClause ? this.createStepsForWhereClause(query.ast.whereClause) : [],
|
|
2320
|
-
...this.createStepsForReturnClause(query.ast.returnClause)
|
|
2321
|
-
],
|
|
2322
|
-
output: {
|
|
2323
|
-
fields: this.getOutputFields(query.ast.returnClause)
|
|
2324
|
-
}
|
|
2325
|
-
};
|
|
2326
|
-
}
|
|
2327
|
-
createStepsForMatchClause(match) {
|
|
2328
|
-
invariant7(match.pattern.segments.length > 0, void 0, {
|
|
2329
|
-
F: __dxlog_file8,
|
|
2330
|
-
L: 90,
|
|
2331
|
-
S: this,
|
|
2332
|
-
A: [
|
|
2333
|
-
"match.pattern.segments.length > 0",
|
|
2334
|
-
""
|
|
2335
|
-
]
|
|
2336
|
-
});
|
|
2337
|
-
const firstSegment = match.pattern.segments[0];
|
|
2338
|
-
invariant7(firstSegment.astKind === "NodePattern", void 0, {
|
|
2339
|
-
F: __dxlog_file8,
|
|
2340
|
-
L: 92,
|
|
2341
|
-
S: this,
|
|
2342
|
-
A: [
|
|
2343
|
-
"firstSegment.astKind === 'NodePattern'",
|
|
2344
|
-
""
|
|
2345
|
-
]
|
|
2346
|
-
});
|
|
2347
|
-
let lastNodeVariable = firstSegment.variable?.name ?? this.newVariable();
|
|
2348
|
-
const steps = [];
|
|
2349
|
-
steps.push({
|
|
2350
|
-
type: "NodeScan",
|
|
2351
|
-
label: firstSegment.label.name,
|
|
2352
|
-
into: lastNodeVariable
|
|
2353
|
-
});
|
|
2354
|
-
if (firstSegment.properties) {
|
|
2355
|
-
for (const property2 of firstSegment.properties.properties) {
|
|
2356
|
-
steps.push({
|
|
2357
|
-
type: "FilterByProperty",
|
|
2358
|
-
variable: lastNodeVariable,
|
|
2359
|
-
property: property2.key.name,
|
|
2360
|
-
value: property2.value.value
|
|
2361
|
-
});
|
|
2362
|
-
}
|
|
2363
|
-
}
|
|
2364
|
-
for (let i = 1; i < match.pattern.segments.length; i++) {
|
|
2365
|
-
const relationshipSegment = match.pattern.segments[i++];
|
|
2366
|
-
invariant7(relationshipSegment.astKind === "RelationshipPattern", void 0, {
|
|
2367
|
-
F: __dxlog_file8,
|
|
2368
|
-
L: 115,
|
|
2369
|
-
S: this,
|
|
2370
|
-
A: [
|
|
2371
|
-
"relationshipSegment.astKind === 'RelationshipPattern'",
|
|
2372
|
-
""
|
|
2373
|
-
]
|
|
2374
|
-
});
|
|
2375
|
-
const nodeSegment = match.pattern.segments[i];
|
|
2376
|
-
invariant7(nodeSegment.astKind === "NodePattern", void 0, {
|
|
2377
|
-
F: __dxlog_file8,
|
|
2378
|
-
L: 117,
|
|
2379
|
-
S: this,
|
|
2380
|
-
A: [
|
|
2381
|
-
"nodeSegment.astKind === 'NodePattern'",
|
|
2382
|
-
""
|
|
2383
|
-
]
|
|
2384
|
-
});
|
|
2385
|
-
const leftSeparator = match.pattern.segments.separators[i - 2];
|
|
2386
|
-
const rightSeparator = match.pattern.segments.separators[i - 1];
|
|
2387
|
-
const direction = getDirection(leftSeparator.direction, rightSeparator.direction);
|
|
2388
|
-
const relationshipVariable = relationshipSegment.variable?.name ?? this.newVariable();
|
|
2389
|
-
const nodeVariable = nodeSegment.variable?.name ?? this.newVariable();
|
|
2390
|
-
steps.push({
|
|
2391
|
-
type: "RelationshipScan",
|
|
2392
|
-
label: relationshipSegment.label.name,
|
|
2393
|
-
direction,
|
|
2394
|
-
anchor: lastNodeVariable,
|
|
2395
|
-
relationshipInto: relationshipVariable,
|
|
2396
|
-
nodeInto: nodeVariable
|
|
2397
|
-
});
|
|
2398
|
-
if (relationshipSegment.properties) {
|
|
2399
|
-
for (const property2 of relationshipSegment.properties.properties) {
|
|
2400
|
-
steps.push({
|
|
2401
|
-
type: "FilterByProperty",
|
|
2402
|
-
variable: relationshipVariable,
|
|
2403
|
-
property: property2.key.name,
|
|
2404
|
-
value: property2.value.value
|
|
2405
|
-
});
|
|
2406
|
-
}
|
|
2407
|
-
}
|
|
2408
|
-
if (nodeSegment.label) {
|
|
2409
|
-
steps.push({
|
|
2410
|
-
type: "FilterByLabel",
|
|
2411
|
-
variable: nodeVariable,
|
|
2412
|
-
label: nodeSegment.label.name
|
|
2413
|
-
});
|
|
2414
|
-
}
|
|
2415
|
-
if (nodeSegment.properties) {
|
|
2416
|
-
for (const property2 of nodeSegment.properties.properties) {
|
|
2417
|
-
steps.push({
|
|
2418
|
-
type: "FilterByProperty",
|
|
2419
|
-
variable: nodeVariable,
|
|
2420
|
-
property: property2.key.name,
|
|
2421
|
-
value: property2.value.value
|
|
2422
|
-
});
|
|
2423
|
-
}
|
|
2424
|
-
}
|
|
2425
|
-
lastNodeVariable = nodeVariable;
|
|
2426
|
-
}
|
|
2427
|
-
return steps;
|
|
2428
|
-
}
|
|
2429
|
-
createStepsForWhereClause(where) {
|
|
2430
|
-
return [];
|
|
2431
|
-
}
|
|
2432
|
-
createStepsForReturnClause(returnClause2) {
|
|
2433
|
-
return [
|
|
2434
|
-
{
|
|
2435
|
-
type: "ProduceResults",
|
|
2436
|
-
fields: returnClause2.fields.map((field) => ({
|
|
2437
|
-
name: field.path.map((p) => p.name).join("_"),
|
|
2438
|
-
variable: field.path[0].name,
|
|
2439
|
-
path: field.path.length > 1 ? field.path.slice(1).map((p) => p.name).join(".") : "$"
|
|
2440
|
-
}))
|
|
2441
|
-
}
|
|
2442
|
-
];
|
|
2443
|
-
}
|
|
2444
|
-
getOutputFields(returnClause2) {
|
|
2445
|
-
return returnClause2.fields.map((field) => field.path.map((p) => p.name).join("_"));
|
|
2446
|
-
}
|
|
2447
|
-
};
|
|
2448
|
-
var getDirection = (left, right) => {
|
|
2449
|
-
if (left === "-" && right === "->") {
|
|
2450
|
-
return "out";
|
|
2451
|
-
} else if (left === "<-" && right === "-") {
|
|
2452
|
-
return "in";
|
|
2453
|
-
} else if (left === "-" && right === "-") {
|
|
2454
|
-
return "both";
|
|
2455
|
-
}
|
|
2456
|
-
throw new Error(`Invalid direction: ()${left}[]${right}()`);
|
|
2457
|
-
};
|
|
2458
|
-
|
|
2459
|
-
// packages/experimental/assistant/src/experimental/cypher/query-executor.ts
|
|
2460
|
-
var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/query-executor.ts";
|
|
2461
|
-
var executeQueryPlan = async (dataSource, plan) => {
|
|
2462
|
-
let buffer = [];
|
|
2463
|
-
const results = [];
|
|
2464
|
-
for (const step of plan.steps) {
|
|
2465
|
-
log9("begin step", {
|
|
2466
|
-
step
|
|
2467
|
-
}, {
|
|
2468
|
-
F: __dxlog_file9,
|
|
2469
|
-
L: 41,
|
|
2470
|
-
S: void 0,
|
|
2471
|
-
C: (f, a) => f(...a)
|
|
2472
|
-
});
|
|
2473
|
-
switch (step.type) {
|
|
2474
|
-
case "NodeScan": {
|
|
2475
|
-
const nodes = await dataSource.getNodes({
|
|
2476
|
-
label: step.label
|
|
2477
|
-
});
|
|
2478
|
-
buffer.push(...nodes.map((node) => ({
|
|
2479
|
-
[step.into]: node
|
|
2480
|
-
})));
|
|
2481
|
-
break;
|
|
2482
|
-
}
|
|
2483
|
-
case "FilterByLabel": {
|
|
2484
|
-
buffer = buffer.filter((item) => {
|
|
2485
|
-
const node = item[step.variable];
|
|
2486
|
-
return node && node.kind === "node" && node.label === step.label;
|
|
2487
|
-
});
|
|
2488
|
-
break;
|
|
2489
|
-
}
|
|
2490
|
-
case "FilterByProperty": {
|
|
2491
|
-
buffer = buffer.filter((item) => {
|
|
2492
|
-
const node = item[step.variable];
|
|
2493
|
-
return node && node.kind === "node" && node.properties[step.property] === step.value;
|
|
2494
|
-
});
|
|
2495
|
-
break;
|
|
2496
|
-
}
|
|
2497
|
-
case "RelationshipScan": {
|
|
2498
|
-
const relationships = await dataSource.getRelationships({
|
|
2499
|
-
label: step.label
|
|
2500
|
-
});
|
|
2501
|
-
for (const tuple of [
|
|
2502
|
-
...buffer
|
|
2503
|
-
]) {
|
|
2504
|
-
if (tuple[step.anchor].kind !== "node") {
|
|
2505
|
-
continue;
|
|
2506
|
-
}
|
|
2507
|
-
const filteredRelationships = relationships.filter((relationship) => {
|
|
2508
|
-
switch (step.direction) {
|
|
2509
|
-
case "in":
|
|
2510
|
-
return relationship.target.id === tuple[step.anchor].id;
|
|
2511
|
-
case "out":
|
|
2512
|
-
return relationship.source.id === tuple[step.anchor].id;
|
|
2513
|
-
case "both":
|
|
2514
|
-
return relationship.source.id === tuple[step.anchor].id || relationship.target.id === tuple[step.anchor].id;
|
|
2515
|
-
default:
|
|
2516
|
-
throw new Error(`Unknown direction: ${step.direction}`);
|
|
2517
|
-
}
|
|
2518
|
-
});
|
|
2519
|
-
for (let i = 0; i < filteredRelationships.length; i++) {
|
|
2520
|
-
const relationship = filteredRelationships[i];
|
|
2521
|
-
const newTuple = i === 0 ? tuple : {
|
|
2522
|
-
...tuple
|
|
2523
|
-
};
|
|
2524
|
-
if (newTuple !== tuple) {
|
|
2525
|
-
buffer.push(newTuple);
|
|
2526
|
-
}
|
|
2527
|
-
newTuple[step.relationshipInto] = relationship;
|
|
2528
|
-
switch (step.direction) {
|
|
2529
|
-
case "in":
|
|
2530
|
-
newTuple[step.nodeInto] = relationship.source;
|
|
2531
|
-
break;
|
|
2532
|
-
case "out":
|
|
2533
|
-
newTuple[step.nodeInto] = relationship.target;
|
|
2534
|
-
break;
|
|
2535
|
-
case "both":
|
|
2536
|
-
newTuple[step.nodeInto] = relationship.source.id === newTuple[step.anchor].id ? relationship.target : relationship.source;
|
|
2537
|
-
break;
|
|
2538
|
-
}
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
break;
|
|
2542
|
-
}
|
|
2543
|
-
case "ProduceResults": {
|
|
2544
|
-
for (const tuple of buffer) {
|
|
2545
|
-
const result = {};
|
|
2546
|
-
for (const field of step.fields) {
|
|
2547
|
-
result[field.name] = jsonPathGet(tuple[field.variable].properties, field.path);
|
|
2548
|
-
}
|
|
2549
|
-
results.push(result);
|
|
2550
|
-
}
|
|
2551
|
-
break;
|
|
2552
|
-
}
|
|
2553
|
-
}
|
|
2554
|
-
log9("finish step", {
|
|
2555
|
-
buffer: buffer.map((tuple) => mapValues(tuple, (x) => x.id)),
|
|
2556
|
-
results
|
|
2557
|
-
}, {
|
|
2558
|
-
F: __dxlog_file9,
|
|
2559
|
-
L: 118,
|
|
2560
|
-
S: void 0,
|
|
2561
|
-
C: (f, a) => f(...a)
|
|
2562
|
-
});
|
|
2563
|
-
}
|
|
2564
|
-
return results;
|
|
2565
|
-
};
|
|
2566
|
-
var executeQuery = (dataSource, query) => {
|
|
2567
|
-
const plan = createExecutionPlan(parseCypherQuery(query));
|
|
2568
|
-
return executeQueryPlan(dataSource, plan);
|
|
2569
|
-
};
|
|
2570
|
-
var jsonPathGet = (obj, path) => {
|
|
2571
|
-
if (path === "" || path === "$") {
|
|
2572
|
-
return obj;
|
|
2573
|
-
}
|
|
2574
|
-
const parts = path.split(".");
|
|
2575
|
-
if (parts[0] === "$") {
|
|
2576
|
-
parts.shift();
|
|
2577
|
-
}
|
|
2578
|
-
let result = obj;
|
|
2579
|
-
for (const part of parts) {
|
|
2580
|
-
result = result?.[part];
|
|
2581
|
-
}
|
|
2582
|
-
return result;
|
|
2583
|
-
};
|
|
2584
|
-
|
|
2585
|
-
// packages/experimental/assistant/src/experimental/cypher/schema.ts
|
|
2586
|
-
import { raise } from "@dxos/debug";
|
|
2587
|
-
import { JSON_SCHEMA_ECHO_REF_ID } from "@dxos/echo-schema";
|
|
2588
|
-
|
|
2589
|
-
// packages/experimental/assistant/src/util/trim.ts
|
|
2590
|
-
var trim = (strings, ...values) => {
|
|
2591
|
-
const combined = strings.reduce((acc, str, i) => {
|
|
2592
|
-
return acc + str + (values[i] || "");
|
|
2593
|
-
}, "");
|
|
2594
|
-
return combined.replace("/^\n/", "").replace(/\n$/, "");
|
|
2595
|
-
};
|
|
2596
|
-
|
|
2597
|
-
// packages/experimental/assistant/src/experimental/cypher/schema.ts
|
|
2598
|
-
var formatJsonSchemaForLLM = (schemaTypes) => {
|
|
2599
|
-
return schemaTypes.flatMap((schema) => [
|
|
2600
|
-
formatNodeSchema(schema),
|
|
2601
|
-
...formatInferredRelationships(schema, schemaTypes)
|
|
2602
|
-
]);
|
|
2603
|
-
};
|
|
2604
|
-
var formatNodeSchema = (schema) => {
|
|
2605
|
-
const label2 = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
|
|
2606
|
-
const properties2 = Object.entries(schema.properties).filter(([key, prop]) => key !== "id" && !isReference(prop));
|
|
2607
|
-
return trim`
|
|
2608
|
-
<node>
|
|
2609
|
-
(:${label2})
|
|
2610
|
-
|
|
2611
|
-
<description>${schema.description}</description>
|
|
2612
|
-
|
|
2613
|
-
<properties>
|
|
2614
|
-
${properties2.map(([key, value]) => {
|
|
2615
|
-
return trim`
|
|
2616
|
-
<${key}>
|
|
2617
|
-
<type>${value.type}</type>
|
|
2618
|
-
<description>${value.description}</description>
|
|
2619
|
-
</${key}>
|
|
2620
|
-
`;
|
|
2621
|
-
})}
|
|
2622
|
-
</properties>
|
|
2623
|
-
</node>
|
|
2624
|
-
`;
|
|
2625
|
-
};
|
|
2626
|
-
var formatInferredRelationships = (schema, allSchema) => {
|
|
2627
|
-
const nodeLabel = formatNodeLabel(schema.typename ?? raise(new Error("Schema must have $id")));
|
|
2628
|
-
const relationships = Object.entries(schema.properties).filter(([key, prop]) => isReference(prop));
|
|
2629
|
-
return relationships.map(([key, value]) => {
|
|
2630
|
-
const relationshipLabel = formatInferredRelationshipLabel(schema.typename ?? raise(new Error("Schema must have $id")), key);
|
|
2631
|
-
const targetSchema = allSchema.find((schema2) => `dxn:type/${schema2.typename}` === value.reference?.schema.$ref);
|
|
2632
|
-
const targetLabel = targetSchema ? formatNodeLabel(targetSchema?.typename ?? "") : "";
|
|
2633
|
-
return trim`
|
|
2634
|
-
<relationship>
|
|
2635
|
-
(:${nodeLabel})-[:${relationshipLabel}]->(:${targetLabel})
|
|
2636
|
-
|
|
2637
|
-
<description>${value.description}</description>
|
|
2638
|
-
</relationship>
|
|
2639
|
-
`;
|
|
2640
|
-
});
|
|
2641
|
-
};
|
|
2642
|
-
var formatNodeLabel = (typename) => {
|
|
2643
|
-
return typename.replace(/^example\.com\/type\//g, "");
|
|
2644
|
-
};
|
|
2645
|
-
var formatInferredRelationshipLabel = (typename, property2) => {
|
|
2646
|
-
const nodeLabel = formatNodeLabel(typename);
|
|
2647
|
-
return `${nodeLabel}_${property2}`.toUpperCase();
|
|
2648
|
-
};
|
|
2649
|
-
var isReference = (schema) => schema.$id === JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && !Array.isArray(schema.items) && typeof schema.items === "object" && "$id" in schema.items && schema.items.$id === JSON_SCHEMA_ECHO_REF_ID;
|
|
2650
|
-
|
|
2651
|
-
// packages/experimental/assistant/src/experimental/cypher/echo-data-source.ts
|
|
2652
|
-
import { raise as raise2 } from "@dxos/debug";
|
|
2653
|
-
import { Filter } from "@dxos/echo-db";
|
|
2654
|
-
import { getSchema, getSchemaTypename, StoredSchema, toJsonSchema } from "@dxos/echo-schema";
|
|
2655
|
-
import { log as log10 } from "@dxos/log";
|
|
2656
|
-
function _ts_decorate2(decorators, target, key, desc) {
|
|
2657
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
2658
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
2659
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
2660
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
2661
|
-
}
|
|
2662
|
-
var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/experimental/assistant/src/experimental/cypher/echo-data-source.ts";
|
|
2663
|
-
var EchoDataSource = class {
|
|
2664
|
-
constructor(_db) {
|
|
2665
|
-
this._db = _db;
|
|
2666
|
-
}
|
|
2667
|
-
async getNodes({ label: label2 }) {
|
|
2668
|
-
if (!label2) {
|
|
2669
|
-
const { objects: objects2 } = await this._db.query().run();
|
|
2670
|
-
return objects2.map(this._objectToNode);
|
|
2671
|
-
}
|
|
2672
|
-
const schema = (await this._getAllSchema()).find((schema2) => getSchemaTypename(schema2)?.endsWith(label2));
|
|
2673
|
-
if (!schema) {
|
|
2674
|
-
return [];
|
|
2675
|
-
}
|
|
2676
|
-
const { objects } = await this._db.query(Filter.type(schema)).run();
|
|
2677
|
-
return objects.map(this._objectToNode);
|
|
2678
|
-
}
|
|
2679
|
-
async getRelationships({ label: label2 }) {
|
|
2680
|
-
const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename).flatMap((schema) => {
|
|
2681
|
-
const jsonSchema = toJsonSchema(schema);
|
|
2682
|
-
const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
|
|
2683
|
-
return relationships.map(([key, value]) => {
|
|
2684
|
-
const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? raise2(new Error("Schema must have typename")), key);
|
|
2685
|
-
return {
|
|
2686
|
-
label: relationshipLabel,
|
|
2687
|
-
schema,
|
|
2688
|
-
property: key
|
|
2689
|
-
};
|
|
2690
|
-
});
|
|
2691
|
-
});
|
|
2692
|
-
const relationship = syntheticRefRelationships.find((r) => r.label === label2);
|
|
2693
|
-
if (!relationship) {
|
|
2694
|
-
return [];
|
|
2695
|
-
}
|
|
2696
|
-
const { objects } = await this._db.query(Filter.type(relationship.schema)).run();
|
|
2697
|
-
return (await Promise.all(objects.map((object) => this._projectRefRelationship(object, relationship.property)))).flat();
|
|
2698
|
-
}
|
|
2699
|
-
async _getAllSchema() {
|
|
2700
|
-
return [
|
|
2701
|
-
...await this._db.schemaRegistry.query().run(),
|
|
2702
|
-
// TODO(dmaretskyi): Remove once we can serialize recursive schema.
|
|
2703
|
-
...this._db.graph.schemaRegistry.schemas.filter((schema) => getSchemaTypename(schema)?.startsWith("example.org"))
|
|
2704
|
-
].filter((schema) => getSchemaTypename(schema) !== StoredSchema.typename);
|
|
2705
|
-
}
|
|
2706
|
-
_objectToNode(object) {
|
|
2707
|
-
const { id, ...properties2 } = object;
|
|
2708
|
-
return {
|
|
2709
|
-
id,
|
|
2710
|
-
kind: "node",
|
|
2711
|
-
label: formatNodeLabel(getSchemaTypename(getSchema(object))),
|
|
2712
|
-
properties: properties2
|
|
2713
|
-
};
|
|
2714
|
-
}
|
|
2715
|
-
async _projectRefRelationship(object, prop) {
|
|
2716
|
-
if (!object[prop]) {
|
|
2717
|
-
return [];
|
|
2718
|
-
}
|
|
2719
|
-
const value = Array.isArray(object[prop]) ? object[prop] : [
|
|
2720
|
-
object[prop]
|
|
2721
|
-
];
|
|
2722
|
-
return Promise.all(value.map(async (ref) => {
|
|
2723
|
-
const target = await ref.load();
|
|
2724
|
-
return {
|
|
2725
|
-
id: `${object.id}-${prop}-${target.id}`,
|
|
2726
|
-
kind: "relationship",
|
|
2727
|
-
label: formatInferredRelationshipLabel(getSchemaTypename(getSchema(object)), prop),
|
|
2728
|
-
properties: {},
|
|
2729
|
-
source: this._objectToNode(object),
|
|
2730
|
-
target: this._objectToNode(target)
|
|
2731
|
-
};
|
|
2732
|
-
}));
|
|
2733
|
-
}
|
|
2734
|
-
};
|
|
2735
|
-
_ts_decorate2([
|
|
2736
|
-
log10.method(void 0, void 0, {
|
|
2737
|
-
F: __dxlog_file10,
|
|
2738
|
-
L: 18,
|
|
2739
|
-
S: void 0,
|
|
2740
|
-
C: (f, a) => f(...a)
|
|
2741
|
-
})
|
|
2742
|
-
], EchoDataSource.prototype, "getNodes", null);
|
|
2743
|
-
_ts_decorate2([
|
|
2744
|
-
log10.method(void 0, void 0, {
|
|
2745
|
-
F: __dxlog_file10,
|
|
2746
|
-
L: 34,
|
|
2747
|
-
S: void 0,
|
|
2748
|
-
C: (f, a) => f(...a)
|
|
2749
|
-
})
|
|
2750
|
-
], EchoDataSource.prototype, "getRelationships", null);
|
|
2751
|
-
|
|
2752
|
-
export {
|
|
2753
|
-
DEFAULT_EDGE_MODEL,
|
|
2754
|
-
DEFAULT_EDGE_MODELS,
|
|
2755
|
-
DEFAULT_OLLAMA_ENDPOINT,
|
|
2756
|
-
DEFAULT_OLLAMA_MODEL,
|
|
2757
|
-
DEFAULT_OLLAMA_MODELS,
|
|
2758
|
-
createGenerationStream,
|
|
2759
|
-
GenerationStreamImpl,
|
|
2760
|
-
AIServiceEdgeClient,
|
|
2761
|
-
MessageCollector,
|
|
2762
|
-
emitMessageAsEvents,
|
|
2763
|
-
createArtifactElement,
|
|
2764
|
-
LLMModel,
|
|
2765
|
-
ToolTypes,
|
|
2766
|
-
GenerateRequest,
|
|
2767
|
-
GenerateResponse,
|
|
2768
|
-
isToolUse,
|
|
2769
|
-
runTools,
|
|
2770
|
-
VersionPin,
|
|
2771
|
-
AISession,
|
|
2772
|
-
AIServiecOverloadedError,
|
|
2773
|
-
OllamaClient,
|
|
2774
|
-
StreamTransform,
|
|
2775
|
-
MixedStreamParser,
|
|
2776
|
-
mergeMessageBlock,
|
|
2777
|
-
runLLM,
|
|
2778
|
-
parseCypherQuery,
|
|
2779
|
-
executeQueryPlan,
|
|
2780
|
-
executeQuery,
|
|
2781
|
-
trim,
|
|
2782
|
-
formatJsonSchemaForLLM,
|
|
2783
|
-
formatNodeLabel,
|
|
2784
|
-
formatInferredRelationshipLabel,
|
|
2785
|
-
isReference,
|
|
2786
|
-
EchoDataSource
|
|
2787
|
-
};
|
|
2788
|
-
//# sourceMappingURL=chunk-SAWYU3V5.mjs.map
|