@dxos/assistant 0.7.4 → 0.7.5-labs.5f04cf6

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.
Files changed (109) hide show
  1. package/dist/lib/browser/chunk-37SDA65J.mjs +565 -0
  2. package/dist/lib/browser/chunk-37SDA65J.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +936 -47
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +14 -8
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/chunk-UYNIAO5N.cjs +577 -0
  9. package/dist/lib/node/chunk-UYNIAO5N.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +936 -54
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +20 -13
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/lib/node-esm/chunk-AR24K7TY.mjs +567 -0
  16. package/dist/lib/node-esm/chunk-AR24K7TY.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +936 -47
  18. package/dist/lib/node-esm/index.mjs.map +4 -4
  19. package/dist/lib/node-esm/meta.json +1 -1
  20. package/dist/lib/node-esm/testing/index.mjs +14 -8
  21. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  22. package/dist/types/src/ai-service/client.d.ts +16 -32
  23. package/dist/types/src/ai-service/client.d.ts.map +1 -1
  24. package/dist/types/src/ai-service/defs.d.ts +134 -0
  25. package/dist/types/src/ai-service/defs.d.ts.map +1 -0
  26. package/dist/types/src/ai-service/index.d.ts +3 -1
  27. package/dist/types/src/ai-service/index.d.ts.map +1 -1
  28. package/dist/types/src/ai-service/parser.d.ts +40 -0
  29. package/dist/types/src/ai-service/parser.d.ts.map +1 -0
  30. package/dist/types/src/ai-service/stream.d.ts +35 -0
  31. package/dist/types/src/ai-service/stream.d.ts.map +1 -0
  32. package/dist/types/src/ai-service/stream.test.d.ts +2 -0
  33. package/dist/types/src/ai-service/stream.test.d.ts.map +1 -0
  34. package/dist/types/src/ai-service/util/index.d.ts +2 -0
  35. package/dist/types/src/ai-service/util/index.d.ts.map +1 -0
  36. package/dist/types/src/ai-service/{sse.d.ts → util/sse.d.ts} +5 -0
  37. package/dist/types/src/ai-service/util/sse.d.ts.map +1 -0
  38. package/dist/types/src/conversation/conversation.d.ts +56 -5
  39. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  40. package/dist/types/src/conversation/index.d.ts +0 -1
  41. package/dist/types/src/conversation/index.d.ts.map +1 -1
  42. package/dist/types/src/conversation/types.d.ts +44 -13
  43. package/dist/types/src/conversation/types.d.ts.map +1 -1
  44. package/dist/types/src/cypher/combinators.d.ts.map +1 -1
  45. package/dist/types/src/cypher/parjs.d.ts +1 -1
  46. package/dist/types/src/cypher/parjs.d.ts.map +1 -1
  47. package/dist/types/src/cypher/schema.d.ts.map +1 -1
  48. package/dist/types/src/testing/artifacts.test.d.ts +1 -0
  49. package/dist/types/src/testing/artifacts.test.d.ts.map +1 -0
  50. package/dist/types/src/testing/data.d.ts +2 -0
  51. package/dist/types/src/testing/data.d.ts.map +1 -0
  52. package/dist/types/src/testing/defs.d.ts +5 -0
  53. package/dist/types/src/testing/defs.d.ts.map +1 -0
  54. package/dist/types/src/testing/index.d.ts +1 -0
  55. package/dist/types/src/testing/index.d.ts.map +1 -1
  56. package/dist/types/src/testing/logger.d.ts +1 -1
  57. package/dist/types/src/testing/logger.d.ts.map +1 -1
  58. package/dist/types/src/testing/query-promts.d.ts +1 -1
  59. package/dist/types/src/testing/query-promts.d.ts.map +1 -1
  60. package/dist/types/src/testing/test-data.d.ts +1 -1
  61. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  62. package/dist/types/src/testing/test-schema.d.ts +4 -4
  63. package/package.json +20 -18
  64. package/src/ai-service/client.test.ts +28 -28
  65. package/src/ai-service/client.ts +31 -177
  66. package/src/ai-service/defs.ts +98 -0
  67. package/src/ai-service/index.ts +3 -1
  68. package/src/ai-service/parser.ts +183 -0
  69. package/src/ai-service/stream.test.ts +106 -0
  70. package/src/ai-service/stream.test.txt +33 -0
  71. package/src/ai-service/stream.ts +182 -0
  72. package/src/ai-service/util/index.ts +5 -0
  73. package/src/ai-service/{sse.ts → util/sse.ts} +5 -0
  74. package/src/bin/chat.ts +8 -10
  75. package/src/conversation/conversation.test.ts +13 -17
  76. package/src/conversation/conversation.ts +113 -18
  77. package/src/conversation/index.ts +0 -1
  78. package/src/conversation/types.ts +55 -16
  79. package/src/cypher/combinators.test.ts +4 -4
  80. package/src/cypher/combinators.ts +0 -1
  81. package/src/cypher/execution-plan.test.ts +5 -3
  82. package/src/cypher/parjs-shims.d.ts +4 -0
  83. package/src/cypher/parjs.ts +2 -2
  84. package/src/cypher/query-executor.test.ts +1 -1
  85. package/src/cypher/schema.ts +0 -1
  86. package/src/index.ts +1 -1
  87. package/src/testing/artifacts.test.ts +182 -0
  88. package/src/testing/data.ts +13 -0
  89. package/src/testing/defs.ts +8 -0
  90. package/src/testing/index.ts +1 -0
  91. package/src/testing/logger.ts +3 -2
  92. package/src/testing/query-promts.ts +3 -3
  93. package/src/testing/query.test.ts +11 -10
  94. package/src/testing/test-data.ts +1 -1
  95. package/vendor/parjs-browser.mjs +4 -0
  96. package/vendor/parjs-default.mjs +8 -0
  97. package/dist/lib/browser/chunk-AKP45LQH.mjs +0 -1394
  98. package/dist/lib/browser/chunk-AKP45LQH.mjs.map +0 -7
  99. package/dist/lib/node/chunk-G6CGWEMO.cjs +0 -1418
  100. package/dist/lib/node/chunk-G6CGWEMO.cjs.map +0 -7
  101. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs +0 -1396
  102. package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +0 -7
  103. package/dist/types/src/ai-service/schema.d.ts +0 -296
  104. package/dist/types/src/ai-service/schema.d.ts.map +0 -1
  105. package/dist/types/src/ai-service/sse.d.ts.map +0 -1
  106. package/dist/types/src/sanity.test.d.ts +0 -2
  107. package/dist/types/src/sanity.test.d.ts.map +0 -1
  108. package/src/ai-service/schema.ts +0 -260
  109. package/src/sanity.test.ts +0 -9
@@ -2,13 +2,13 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import { type Tool, ToolResult, Message } from '@dxos/artifact';
6
+ import { createStatic, ObjectId } from '@dxos/echo-schema';
5
7
  import { invariant } from '@dxos/invariant';
6
8
  import { type SpaceId } from '@dxos/keys';
7
9
  import { log } from '@dxos/log';
8
10
 
9
- import { type LLMToolDefinition } from './types';
10
- import { ObjectId, type LLMTool } from '../ai-service';
11
- import { type AIServiceClient, type Message, type ResultStreamEvent, type LLMModel } from '../ai-service';
11
+ import { type AIServiceClient, type ResultStreamEvent, type LLMModel } from '../ai-service';
12
12
 
13
13
  export type CreateLLMConversationParams = {
14
14
  model: LLMModel;
@@ -18,11 +18,11 @@ export type CreateLLMConversationParams = {
18
18
  */
19
19
  system?: string;
20
20
 
21
- spaceId: SpaceId;
22
- threadId: ObjectId;
23
-
24
- tools: LLMTool[];
21
+ spaceId?: SpaceId;
22
+ threadId?: ObjectId;
25
23
 
24
+ tools: Tool[];
25
+ history?: Message[];
26
26
  client: AIServiceClient;
27
27
 
28
28
  logger?: (event: ConversationEvent) => void;
@@ -37,45 +37,50 @@ export type ConversationEvent =
37
37
 
38
38
  export const runLLM = async (params: CreateLLMConversationParams) => {
39
39
  let conversationResult: any = null;
40
+ const history = params.history ?? [];
40
41
 
41
42
  const generate = async () => {
42
43
  log('llm generate', { tools: params.tools });
43
44
  const beginTs = Date.now();
44
- const result = await params.client.generate({
45
+ const stream = await params.client.generate({
45
46
  model: params.model,
46
47
  spaceId: params.spaceId,
47
48
  threadId: params.threadId,
49
+ history,
48
50
  systemPrompt: params.system,
49
51
  tools: params.tools as any,
50
52
  });
51
53
 
52
- for await (const event of result) {
54
+ for await (const event of stream) {
53
55
  params.logger?.(event);
54
56
  }
55
- const messages = await result.complete();
57
+ const messages = await stream.complete();
56
58
  const message = messages.at(-1);
57
59
 
58
60
  log('llm result', { time: Date.now() - beginTs, message });
59
61
  invariant(message);
60
62
  params.logger?.({ type: 'message', message });
61
- await params.client.insertMessages(
62
- messages.map((msg) => ({ ...msg, content: msg.content.filter((c) => c.type !== 'image') })),
63
+ history.push(
64
+ ...messages.map(
65
+ (message): Message => ({ ...message, content: message.content.filter((block) => block.type !== 'image') }),
66
+ ),
63
67
  );
64
68
 
65
69
  const isToolUse = message.content.at(-1)?.type === 'tool_use';
66
70
  if (isToolUse) {
67
- const toolCalls = message.content.filter((c) => c.type === 'tool_use');
71
+ const toolCalls = message.content.filter((block) => block.type === 'tool_use');
68
72
  invariant(toolCalls.length === 1);
69
73
  const toolCall = toolCalls[0];
70
- const tool = params.tools.find((t) => t.name === toolCall.name);
74
+ const tool = params.tools.find((tool) => tool.name === toolCall.name);
71
75
  if (!tool) {
72
76
  throw new Error(`Tool not found: ${toolCall.name}`);
73
77
  }
74
78
 
75
- const toolResult = await tool.execute(toolCall.input, {});
79
+ invariant(tool.execute);
80
+ const toolResult = await tool.execute(toolCall.input);
76
81
  switch (toolResult.kind) {
77
82
  case 'error': {
78
- log('tool error', { message: toolResult.message });
83
+ log.warn('tool error', { message: toolResult.message });
79
84
  const resultMessage: Message = {
80
85
  id: ObjectId.random(),
81
86
  spaceId: params.spaceId,
@@ -91,10 +96,11 @@ export const runLLM = async (params: CreateLLMConversationParams) => {
91
96
  ],
92
97
  };
93
98
  params.logger?.({ type: 'message', message: resultMessage });
94
- await params.client.insertMessages([resultMessage]);
99
+ history.push(resultMessage);
95
100
 
96
101
  return true;
97
102
  }
103
+
98
104
  case 'success': {
99
105
  log('tool success', { result: toolResult.result });
100
106
  const resultMessage: Message = {
@@ -111,10 +117,11 @@ export const runLLM = async (params: CreateLLMConversationParams) => {
111
117
  ],
112
118
  };
113
119
  params.logger?.({ type: 'message', message: resultMessage });
114
- await params.client.insertMessages([resultMessage]);
120
+ history.push(resultMessage);
115
121
 
116
122
  return true;
117
123
  }
124
+
118
125
  case 'break': {
119
126
  log('tool break', { result: toolResult.result });
120
127
  conversationResult = toolResult.result;
@@ -130,5 +137,93 @@ export const runLLM = async (params: CreateLLMConversationParams) => {
130
137
 
131
138
  return {
132
139
  result: conversationResult,
140
+ history,
133
141
  };
134
142
  };
143
+
144
+ export const isToolUse = (message: Message) => message.content.at(-1)?.type === 'tool_use';
145
+
146
+ export type RunToolsOptions = {
147
+ message: Message;
148
+ tools: Tool[];
149
+ extensions?: ToolContextExtensions;
150
+ };
151
+
152
+ export type RunToolsResult =
153
+ | {
154
+ type: 'continue';
155
+ message: Message;
156
+ }
157
+ | {
158
+ type: 'break';
159
+ result: unknown;
160
+ };
161
+
162
+ export const runTools = async ({ message, tools, extensions }: RunToolsOptions): Promise<RunToolsResult> => {
163
+ const toolCalls = message.content.filter((block) => block.type === 'tool_use');
164
+ invariant(toolCalls.length === 1);
165
+ const toolCall = toolCalls[0];
166
+ const tool = tools.find((tool) => tool.name === toolCall.name);
167
+ if (!tool) {
168
+ throw new Error(`Tool not found: ${toolCall.name}`);
169
+ }
170
+
171
+ let toolResult: ToolResult;
172
+ try {
173
+ invariant(tool.execute);
174
+ toolResult = await tool.execute(toolCall.input, { extensions });
175
+ } catch (error: any) {
176
+ log('tool error', { error });
177
+ toolResult = ToolResult.Error(error.message);
178
+ }
179
+
180
+ switch (toolResult.kind) {
181
+ case 'error': {
182
+ log('tool error', { message: toolResult.message });
183
+ const resultMessage = createStatic(Message, {
184
+ role: 'user',
185
+ content: [
186
+ {
187
+ type: 'tool_result',
188
+ toolUseId: toolCall.id,
189
+ content: toolResult.message,
190
+ isError: true,
191
+ },
192
+ ],
193
+ });
194
+
195
+ // TODO(burdon): Retry count?
196
+ return {
197
+ type: 'continue',
198
+ message: resultMessage,
199
+ };
200
+ }
201
+
202
+ case 'success': {
203
+ log('tool success', { result: toolResult.result });
204
+ const resultMessage = createStatic(Message, {
205
+ role: 'user',
206
+ content: [
207
+ {
208
+ type: 'tool_result',
209
+ toolUseId: toolCall.id,
210
+ content: typeof toolResult.result === 'string' ? toolResult.result : JSON.stringify(toolResult.result),
211
+ },
212
+ ],
213
+ });
214
+
215
+ return {
216
+ type: 'continue',
217
+ message: resultMessage,
218
+ };
219
+ }
220
+
221
+ case 'break': {
222
+ log('tool break', { result: toolResult.result });
223
+ return {
224
+ type: 'break',
225
+ result: toolResult.result,
226
+ };
227
+ }
228
+ }
229
+ };
@@ -3,4 +3,3 @@
3
3
  //
4
4
 
5
5
  export * from './conversation';
6
- export * from './types';
@@ -4,13 +4,11 @@
4
4
 
5
5
  import { Schema as S } from '@effect/schema';
6
6
 
7
- import { toJsonSchema } from '@dxos/echo-schema';
8
- import { JsonSchemaType } from '@dxos/echo-schema';
7
+ import { type Message, type MessageContentBlock } from '@dxos/artifact';
8
+ import { toJsonSchema, JsonSchemaType, ObjectId } from '@dxos/echo-schema';
9
9
  import type { SpaceId } from '@dxos/keys';
10
10
  import { log } from '@dxos/log';
11
11
 
12
- import { ObjectId, type Message } from '../ai-service';
13
-
14
12
  export const createUserMessage = (spaceId: SpaceId, threadId: ObjectId, text: string): Message => ({
15
13
  id: ObjectId.random(),
16
14
  spaceId,
@@ -19,46 +17,80 @@ export const createUserMessage = (spaceId: SpaceId, threadId: ObjectId, text: st
19
17
  content: [{ type: 'text', text }],
20
18
  });
21
19
 
22
- export const LLMToolDefinition = S.Struct({
20
+ /**
21
+ * @deprecated Use {@link LLMTool} instead.
22
+ */
23
+ export const ToolDefinition = S.Struct({
23
24
  name: S.String,
24
25
  description: S.String,
25
26
  parameters: JsonSchemaType,
26
27
  execute: S.Any,
27
28
  });
28
29
 
29
- export type LLMToolDefinition = {
30
+ /**
31
+ * @deprecated Use {@link LLMTool} instead.
32
+ */
33
+ export type ToolDefinition = {
30
34
  name: string;
31
35
  description: string;
32
36
  parameters: JsonSchemaType;
33
- execute: (params: unknown, context: ToolExecutionContext) => Promise<LLMToolResult>;
37
+ execute: (params: unknown, context: ToolExecutionContext) => Promise<ToolResult>;
34
38
  };
35
39
 
36
- export type ToolExecutionContext = {};
40
+ declare global {
41
+ /**
42
+ * Extensions to the tool execution context.
43
+ *
44
+ * Different modules can extend this definition to add their own properties.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * declare global {
49
+ * interface ToolContextExtensions {
50
+ * chess: {
51
+ * board: string;
52
+ * };
53
+ * }
54
+ * }
55
+ * ```
56
+ *
57
+ * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation
58
+ */
59
+ interface ToolContextExtensions {}
60
+ }
61
+
62
+ export type ToolExecutionContext = {
63
+ extensions: ToolContextExtensions;
64
+ };
37
65
 
38
- export type LLMToolResult =
39
- | { kind: 'success'; result: unknown }
66
+ export type ToolResult =
67
+ | { kind: 'success'; result: unknown; extractContentBlocks?: MessageContentBlock[] }
40
68
  | { kind: 'error'; message: string }
41
69
  | { kind: 'break'; result: unknown };
42
70
 
43
- export const LLMToolResult = Object.freeze({
71
+ export const ToolResult = Object.freeze({
44
72
  /**
45
73
  * The tool execution was successful.
46
74
  * Gives the result back to the LLM.
47
75
  */
48
- Success: (result: unknown): LLMToolResult => ({ kind: 'success', result }),
76
+ Success: (result: unknown, extractContentBlocks?: MessageContentBlock[]): ToolResult => ({
77
+ kind: 'success',
78
+ result,
79
+ extractContentBlocks,
80
+ }),
49
81
 
50
- Error: (message: string): LLMToolResult => ({ kind: 'error', message }),
82
+ Error: (message: string): ToolResult => ({ kind: 'error', message }),
51
83
  /**
52
84
  * Stop the conversation and return the result.
53
85
  */
54
- Break: (result: unknown): LLMToolResult => ({ kind: 'break', result }),
86
+ Break: (result: unknown): ToolResult => ({ kind: 'break', result }),
55
87
  });
56
88
 
57
89
  export type DefineToolParams<Params extends S.Schema.AnyNoContext> = {
58
90
  name: string;
59
91
  description: string;
60
92
  schema: Params;
61
- execute: (params: S.Schema.Type<Params>, context: ToolExecutionContext) => Promise<LLMToolResult>;
93
+ execute: (params: S.Schema.Type<Params>, context: ToolExecutionContext) => Promise<ToolResult>;
62
94
  };
63
95
 
64
96
  export const defineTool = <Params extends S.Schema.AnyNoContext>({
@@ -66,7 +98,7 @@ export const defineTool = <Params extends S.Schema.AnyNoContext>({
66
98
  description,
67
99
  schema,
68
100
  execute,
69
- }: DefineToolParams<Params>): LLMToolDefinition => {
101
+ }: DefineToolParams<Params>): ToolDefinition => {
70
102
  return {
71
103
  name,
72
104
  description,
@@ -78,9 +110,16 @@ export const defineTool = <Params extends S.Schema.AnyNoContext>({
78
110
  };
79
111
  };
80
112
 
113
+ /**
114
+ * Adapts schems to be able to pass to AI providers.
115
+ */
81
116
  const toFunctionParameterSchema = (schema: S.Schema.All) => {
82
117
  const jsonSchema = toJsonSchema(schema);
83
118
  log('tool schema', { jsonSchema });
119
+ delete jsonSchema.anyOf;
120
+ delete jsonSchema.$id;
121
+ jsonSchema.type = 'object';
122
+ jsonSchema.properties ??= {};
84
123
  for (const key in jsonSchema.properties) {
85
124
  if (typeof jsonSchema.properties![key].description !== 'string') {
86
125
  throw new Error(`Property missing description: ${key}`);
@@ -6,7 +6,7 @@
6
6
  /* eslint-disable @typescript-eslint/consistent-type-imports */
7
7
 
8
8
  import { createRequire } from 'node:module';
9
- import type { Parjser } from 'parjs';
9
+ import { type Parjser } from 'parjs';
10
10
  import { describe, test } from 'vitest';
11
11
 
12
12
  import { log } from '@dxos/log';
@@ -58,13 +58,13 @@ describe('Cypher Combinators', () => {
58
58
  const parser = or(node)(relation);
59
59
  const input = '[a:b]';
60
60
  const result = parser.parse(input);
61
- log.info('', { result });
61
+ log('result', { result });
62
62
  });
63
63
 
64
64
  test('properties', ({ expect }) => {
65
65
  const input = "{name: 'John'}";
66
66
  const result = properties.parse(input);
67
- log.info('', { result });
67
+ log('result', { result });
68
68
  expect(result).toMatchObject({ isOk: true });
69
69
  });
70
70
 
@@ -92,7 +92,7 @@ describe('Cypher Combinators', () => {
92
92
  const cases = ['RETURN n, m'];
93
93
  for (const input of cases) {
94
94
  const result = returnClause.parse(input);
95
- log.info('', { result });
95
+ log('result', { result });
96
96
  expect(result).toMatchObject({ isOk: true });
97
97
  }
98
98
  });
@@ -21,7 +21,6 @@ import type {
21
21
  StringLiteral,
22
22
  WhereClause,
23
23
  } from './ast';
24
-
25
24
  import { Parjser, parjs, parjsCombinators } from './parjs';
26
25
 
27
26
  // Helper parsers
@@ -9,10 +9,12 @@ import { log } from '@dxos/log';
9
9
  import { createExecutionPlan } from './execution-plan';
10
10
  import { parseCypherQuery } from './parser';
11
11
 
12
+ // log.config({ filter: 'debug' });
13
+
12
14
  describe('Execution Plan', () => {
13
15
  test('trivial', ({ expect }) => {
14
16
  const plan = createExecutionPlan(parseCypherQuery('MATCH (n:Person) RETURN n'));
15
- log.info('', { plan });
17
+ log('', { plan });
16
18
  expect(plan.steps.map((step) => step.type)).toEqual(['NodeScan', 'ProduceResults']);
17
19
  });
18
20
 
@@ -22,9 +24,9 @@ describe('Execution Plan', () => {
22
24
  "MATCH (org:Org {name: 'DXOS'})-[:ORG_EMPLOYEES]->(c:Contact)<-[:TASK_ASSIGNEE]-(:Task)-[:TASK_PROJECT]->(p:Project {name: 'Composer'}) RETURN c.name",
23
25
  ),
24
26
  );
25
- log.info('', { plan });
27
+ log('', { plan });
26
28
  for (const step of plan.steps) {
27
- log.info('', { step });
29
+ log('step', { step });
28
30
  }
29
31
  expect(plan.steps.map((step) => step.type)).toEqual([
30
32
  'NodeScan',
@@ -1,3 +1,7 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
1
5
  declare module '#parjs' {
2
6
  import * as parjs from 'parjs';
3
7
  import * as parjsCombinators from 'parjs/combinators';
@@ -3,8 +3,8 @@
3
3
  //
4
4
 
5
5
  // Workaround for https://github.com/vitest-dev/vitest/issues/7174.
6
- import { parjsCombinators, parjs } from '#parjs';
7
-
8
6
  import type { Parjser } from 'parjs';
9
7
 
8
+ import { parjsCombinators, parjs } from '#parjs';
9
+
10
10
  export { type Parjser, parjsCombinators, parjs };
@@ -9,7 +9,7 @@ import { log } from '@dxos/log';
9
9
  import { executeQuery } from './query-executor';
10
10
  import { createTestData } from '../testing';
11
11
 
12
- test('run', async ({ expect }) => {
12
+ test.skip('run', async ({ expect }) => {
13
13
  const dataSource = createTestData();
14
14
  // for (const node of dataSource.nodes) {
15
15
  // log.info('node', { id: node.id, label: node.label, name: node.properties.name });
@@ -4,7 +4,6 @@
4
4
 
5
5
  import { raise } from '@dxos/debug';
6
6
  import { JSON_SCHEMA_ECHO_REF_ID, type JsonSchemaType } from '@dxos/echo-schema';
7
- import { DXN } from '@dxos/keys';
8
7
 
9
8
  import { trim } from '../util';
10
9
 
package/src/index.ts CHANGED
@@ -4,4 +4,4 @@
4
4
 
5
5
  export * from './ai-service';
6
6
  export * from './cypher';
7
- export * from './conversation';
7
+ export * from './conversation';
@@ -0,0 +1,182 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ /*
6
+ import { Schema as S } from '@effect/schema';
7
+ import { describe, test } from 'vitest';
8
+
9
+ import { ObjectId, toJsonSchema } from '@dxos/echo-schema';
10
+ import { invariant } from '@dxos/invariant';
11
+ import { SpaceId } from '@dxos/keys';
12
+ import { log } from '@dxos/log';
13
+
14
+ import { AIServiceClientImpl, Tool } from '../ai-service';
15
+ import { defineTool, ToolResult } from '../conversation';
16
+
17
+ // TODO(dmaretskyi): Effect schema.
18
+ const ArtifactDef = S.Struct({
19
+ typename: S.String,
20
+ description: S.String,
21
+ schema: S.Any,
22
+ actions: S.Array(Tool),
23
+ }).pipe(S.mutable);
24
+
25
+ type ArtifactDef = S.Schema.Type<typeof ArtifactDef>;
26
+
27
+ const ListItem = S.Struct({
28
+ name: S.String,
29
+ });
30
+
31
+ const ListSchema = S.Struct({
32
+ id: ObjectId,
33
+ title: S.String,
34
+ items: S.Array(ListItem).pipe(S.mutable),
35
+ }).pipe(S.mutable);
36
+
37
+ type ListSchema = S.Schema.Type<typeof ListSchema>;
38
+
39
+ const list: ArtifactDef = {
40
+ typename: 'example.com/type/List',
41
+ description: 'Ordered set of text items.',
42
+ schema: ListSchema,
43
+ actions: [
44
+ defineTool({
45
+ name: 'list.query',
46
+ description: 'Query all lists',
47
+ schema: S.Struct({}),
48
+ execute: async ({}, context) => {
49
+ return ToolResult.Success(LISTS[id]);
50
+ },
51
+ }),
52
+ defineTool({
53
+ name: 'list.inspect',
54
+ description: 'Get contents of the list',
55
+ schema: S.Struct({
56
+ id: ObjectId.annotations({ description: 'The list to inspect' }),
57
+ }),
58
+ execute: async ({ id }, context) => {
59
+ return ToolResult.Success(LISTS[id]);
60
+ },
61
+ }),
62
+ defineTool({
63
+ name: 'list.add',
64
+ description: 'Add one or more items to an existing list',
65
+ schema: S.Struct({
66
+ id: ObjectId.annotations({ description: 'The list to add items to' }),
67
+ items: S.Array(ListItem).annotations({ description: 'The items to add to the list' }),
68
+ }),
69
+ execute: async ({ id, items }, context) => {
70
+ LISTS[id].items.push(...items);
71
+ return ToolResult.Success(LISTS[id]);
72
+ },
73
+ }),
74
+ ],
75
+ };
76
+
77
+ const LISTS: Record<ObjectId, ListSchema> = {};
78
+
79
+ const artifacts = [list];
80
+
81
+ const getArtifactDefinitions = defineTool({
82
+ name: 'getArtifactDefinitions',
83
+ description: 'Queries the definitions and metadata of artifacts defined in the system',
84
+ schema: S.Any,
85
+ execute: async (_, context) => {
86
+ return ToolResult.Success(
87
+ artifacts.map((artifact) => ({
88
+ typename: artifact.typename,
89
+ description: artifact.description,
90
+ schema: toJsonSchema(artifact.schema),
91
+ actions: artifact.actions.map((action) => ({
92
+ name: action.name,
93
+ description: action.description,
94
+ })),
95
+ })),
96
+ );
97
+ },
98
+ });
99
+
100
+ const ARTIFACT_INSTRUCTIONS = `
101
+ You have ability to interact with artifacts.
102
+ Artifacts are persistent structured objects that have actions associated with them.
103
+
104
+ Before replying to the user you should first query the artifact definitions and metadata.
105
+ If there's
106
+
107
+ `;
108
+
109
+ describe('Artifacts', () => {
110
+ test('shopping list', async () => {
111
+ const client = new AIServiceClientImpl({
112
+ endpoint: ENDPOINT,
113
+ });
114
+
115
+ const custodian: Tool = {
116
+ name: 'custodian',
117
+ description: 'Custodian can tell you the password if you say the magic word',
118
+ parameters: toJsonSchema(
119
+ S.Struct({
120
+ magicWord: S.String.annotations({ description: 'The magic word. Should be exactly "pretty please"' }),
121
+ }),
122
+ ),
123
+ };
124
+
125
+ const spaceId = SpaceId.random();
126
+ const threadId = ObjectId.random();
127
+
128
+ await client.appendMessages([
129
+ {
130
+ id: ObjectId.random(),
131
+ spaceId,
132
+ threadId,
133
+ role: 'user',
134
+ content: [{ type: 'text', text: 'What is the password? Ask the custodian' }],
135
+ },
136
+ ]);
137
+
138
+ const stream = await client.generate({
139
+ model: '@anthropic/claude-3-5-haiku-20241022',
140
+ spaceId,
141
+ threadId,
142
+ systemPrompt: 'You are a helpful assistant.',
143
+ tools: [custodian],
144
+ });
145
+ for await (const event of stream) {
146
+ log.info('event', event);
147
+ }
148
+ const [message] = await stream.complete();
149
+ log.info('full message', {
150
+ message,
151
+ });
152
+ await client.appendMessages([message]);
153
+
154
+ const toolUse = message.content.find(({ type }) => type === 'tool_use')!;
155
+ invariant(toolUse.type === 'tool_use');
156
+ await client.appendMessages([
157
+ {
158
+ id: ObjectId.random(),
159
+ spaceId,
160
+ threadId,
161
+ role: 'user',
162
+ content: [{ type: 'tool_result', toolUseId: toolUse.id, content: 'password="The sky is gray"' }],
163
+ },
164
+ ]);
165
+
166
+ const stream2 = await client.generate({
167
+ model: '@anthropic/claude-3-5-haiku-20241022',
168
+ spaceId,
169
+ threadId,
170
+ systemPrompt: 'You are a helpful assistant.',
171
+ tools: [custodian],
172
+ });
173
+ for await (const event of stream2) {
174
+ log.info('event', event);
175
+ }
176
+ const [message2] = await stream2.complete();
177
+ log.info('full message', {
178
+ message: message2,
179
+ });
180
+ });
181
+ });
182
+ */
@@ -0,0 +1,13 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export const DATA_MESSAGES = [
6
+ `
7
+ <cot>
8
+ ${Array.from({ length: 5 })
9
+ .map((_, i) => `${i + 1}. Step`)
10
+ .join('\n')}
11
+ </cot>
12
+ `,
13
+ ];
@@ -0,0 +1,8 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export const AI_SERVICE_ENDPOINT = {
6
+ LOCAL: 'http://localhost:8788',
7
+ REMOTE: 'https://ai-service.dxos.workers.dev',
8
+ };
@@ -2,6 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ export * from './defs';
5
6
  export * from './logger';
6
7
  export * from './query-promts';
7
8
  export * from './test-data';