@dxos/assistant 0.8.2 → 0.8.3-main.672df60

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.
@@ -1394,11 +1394,11 @@ import { DataTypes } from "@dxos/schema";
1394
1394
  import { Schema as Schema6, identity, Option as Option2, SchemaAST } from "effect";
1395
1395
  import { createTool as createTool3, ToolResult as ToolResult3 } from "@dxos/ai";
1396
1396
  import { isEncodedReference } from "@dxos/echo-protocol";
1397
- import { EntityKind, getSchemaTypename, getTypeAnnotation, getTypeIdentifierAnnotation, create as create4, Filter as Filter2, getEntityKind, getSchemaDXN, ObjectId as ObjectId3, Query as Query2, ReferenceAnnotationId, RelationSourceId, RelationTargetId } from "@dxos/echo-schema";
1397
+ import { EntityKind, getSchemaTypename, getTypeAnnotation, getTypeIdentifierAnnotation, create as create4, Filter as Filter2, getEntityKind, getSchemaDXN, ObjectId as ObjectId3, Query as Query2, ReferenceAnnotationId, RelationSourceDXNId, RelationTargetDXNId, RelationSourceId, RelationTargetId } from "@dxos/echo-schema";
1398
1398
  import { mapAst } from "@dxos/effect";
1399
1399
  import { DXN as DXN2 } from "@dxos/keys";
1400
1400
  import { log as log7 } from "@dxos/log";
1401
- import { deepMapValues } from "@dxos/util";
1401
+ import { deepMapValues, isNonNullable } from "@dxos/util";
1402
1402
  var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/assistant/src/research/graph.ts";
1403
1403
  var Subgraph = Schema6.Struct({
1404
1404
  /** Objects and relations. */
@@ -1428,7 +1428,7 @@ var isSchemaAddressableByDxn = (schema, dxn) => {
1428
1428
  }
1429
1429
  return false;
1430
1430
  };
1431
- var createLocalSearchTool = (db) => {
1431
+ var createLocalSearchTool = (db, queue) => {
1432
1432
  return createTool3("search", {
1433
1433
  name: "local_search",
1434
1434
  description: "Search the local database for information using a vector index",
@@ -1441,9 +1441,16 @@ var createLocalSearchTool = (db) => {
1441
1441
  const { objects } = await db.query(Query2.select(Filter2.text(query, {
1442
1442
  type: "vector"
1443
1443
  }))).run();
1444
+ const results = [
1445
+ ...objects
1446
+ ];
1447
+ if (queue) {
1448
+ const queueObjects = await queue.queryObjects();
1449
+ results.push(...queueObjects);
1450
+ }
1444
1451
  return ToolResult3.Success(`
1445
1452
  <local_context>
1446
- ${JSON.stringify(objects, null, 2)}
1453
+ ${JSON.stringify(results, null, 2)}
1447
1454
  </local_context>
1448
1455
  `);
1449
1456
  }
@@ -1462,13 +1469,14 @@ var createExtractionSchema = (types) => {
1462
1469
  var getSanitizedSchemaName = (schema) => {
1463
1470
  return getSchemaDXN(schema).asTypeDXN().type.replaceAll(/[^a-zA-Z0-9]+/g, "_");
1464
1471
  };
1465
- var sanitizeObjects = async (types, data, db) => {
1472
+ var sanitizeObjects = async (types, data, db, queue) => {
1466
1473
  const entries = types.map((type) => data[`objects_${getSanitizedSchemaName(type)}`]?.map((object) => ({
1467
1474
  data: object,
1468
1475
  schema: type
1469
1476
  })) ?? []).flat();
1470
1477
  const idMap = /* @__PURE__ */ new Map();
1471
1478
  const existingIds = /* @__PURE__ */ new Set();
1479
+ const enitties = /* @__PURE__ */ new Map();
1472
1480
  const resolveId = (id) => {
1473
1481
  if (ObjectId3.isValid(id)) {
1474
1482
  existingIds.add(id);
@@ -1511,7 +1519,7 @@ var sanitizeObjects = async (types, data, db) => {
1511
1519
  source: data2.source
1512
1520
  }, {
1513
1521
  F: __dxlog_file7,
1514
- L: 205,
1522
+ L: 216,
1515
1523
  S: void 0,
1516
1524
  C: (f, a) => f(...a)
1517
1525
  });
@@ -1522,25 +1530,36 @@ var sanitizeObjects = async (types, data, db) => {
1522
1530
  target: data2.target
1523
1531
  }, {
1524
1532
  F: __dxlog_file7,
1525
- L: 209,
1533
+ L: 220,
1526
1534
  S: void 0,
1527
1535
  C: (f, a) => f(...a)
1528
1536
  });
1529
1537
  }
1530
1538
  delete data2.source;
1531
1539
  delete data2.target;
1532
- data2[RelationSourceId] = sourceDxn;
1533
- data2[RelationTargetId] = targetDxn;
1540
+ data2[RelationSourceDXNId] = sourceDxn;
1541
+ data2[RelationTargetDXNId] = targetDxn;
1534
1542
  }
1535
- return create4(entry.schema, data2);
1536
- }).filter((object) => !existingIds.has(object.id));
1537
- const { objects } = await db.query(Query2.select(Filter2.ids(...existingIds))).run();
1543
+ return {
1544
+ data: data2,
1545
+ schema: entry.schema
1546
+ };
1547
+ }).filter((object) => !existingIds.has(object.data.id));
1548
+ const { objects: dbObjects } = await db.query(Query2.select(Filter2.ids(...existingIds))).run();
1549
+ const queueObjects = await queue?.getObjectsById([
1550
+ ...existingIds
1551
+ ]) ?? [];
1552
+ const objects = [
1553
+ ...dbObjects,
1554
+ ...queueObjects
1555
+ ].filter(isNonNullable);
1538
1556
  log7.info("objects", {
1539
- objects,
1557
+ dbObjects,
1558
+ queueObjects,
1540
1559
  existingIds
1541
1560
  }, {
1542
1561
  F: __dxlog_file7,
1543
- L: 223,
1562
+ L: 241,
1544
1563
  S: void 0,
1545
1564
  C: (f, a) => f(...a)
1546
1565
  });
@@ -1548,7 +1567,37 @@ var sanitizeObjects = async (types, data, db) => {
1548
1567
  if (missing.length > 0) {
1549
1568
  throw new Error(`Object IDs do not point to existing objects: ${missing.join(", ")}`);
1550
1569
  }
1551
- return res;
1570
+ return res.flatMap(({ data: data2, schema }) => {
1571
+ let skip = false;
1572
+ if (RelationSourceDXNId in data2) {
1573
+ const id = data2[RelationSourceDXNId].asEchoDXN()?.echoId;
1574
+ const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
1575
+ if (obj) {
1576
+ delete data2[RelationSourceDXNId];
1577
+ data2[RelationSourceId] = obj;
1578
+ } else {
1579
+ skip = true;
1580
+ }
1581
+ }
1582
+ if (RelationTargetDXNId in data2) {
1583
+ const id = data2[RelationTargetDXNId].asEchoDXN()?.echoId;
1584
+ const obj = objects.find((object) => object.id === id) ?? enitties.get(id);
1585
+ if (obj) {
1586
+ delete data2[RelationTargetDXNId];
1587
+ data2[RelationTargetId] = obj;
1588
+ } else {
1589
+ skip = true;
1590
+ }
1591
+ }
1592
+ if (!skip) {
1593
+ const obj = create4(schema, data2);
1594
+ enitties.set(obj.id, obj);
1595
+ return [
1596
+ obj
1597
+ ];
1598
+ }
1599
+ return [];
1600
+ });
1552
1601
  };
1553
1602
  var SoftRef = Schema6.Struct({
1554
1603
  "/": Schema6.String
@@ -1576,13 +1625,13 @@ var preprocessSchema = (schema) => {
1576
1625
  })
1577
1626
  })) : identity);
1578
1627
  };
1579
- var createGraphWriterTool = ({ db, schemaTypes, onDone = async (x) => x }) => {
1628
+ var createGraphWriterTool = ({ db, queue, schemaTypes, onDone = async (x) => x }) => {
1580
1629
  return createTool3("graph", {
1581
1630
  name: "writer",
1582
1631
  description: "Write to the local graph database",
1583
1632
  schema: createExtractionSchema(schemaTypes),
1584
1633
  execute: async (input) => {
1585
- const data = await sanitizeObjects(schemaTypes, input, db);
1634
+ const data = await sanitizeObjects(schemaTypes, input, db, queue);
1586
1635
  return ToolResult3.Success(await onDone(data));
1587
1636
  }
1588
1637
  });
@@ -1683,18 +1732,23 @@ var createArtifactElement = (id) => `<artifact id=${id} />`;
1683
1732
 
1684
1733
  // packages/core/assistant/src/blueprint/blueprint.ts
1685
1734
  import { Schema as Schema8 } from "effect";
1686
- import { Tool } from "@dxos/ai";
1687
- import { raise } from "@dxos/debug";
1735
+ import { Obj, Type } from "@dxos/echo";
1688
1736
  import { ObjectId as ObjectId4 } from "@dxos/keys";
1689
- var BlueprintStep = Schema8.Struct({
1690
- id: Schema8.String,
1737
+ var BlueprintStepSchema = Schema8.Struct({
1738
+ id: ObjectId4,
1691
1739
  instructions: Schema8.String,
1692
- // TODO(burdon): ExecutableTool can't be serialized.
1693
- tools: Schema8.Array(Tool).pipe(Schema8.mutable)
1740
+ tools: Schema8.Array(Schema8.String)
1694
1741
  });
1695
- var Blueprint = Schema8.Struct({
1696
- steps: Schema8.Array(BlueprintStep).pipe(Schema8.mutable)
1742
+ var BlueprintSchema = Schema8.Struct({
1743
+ steps: Schema8.Array(BlueprintStepSchema.pipe(Schema8.omit("id")))
1697
1744
  });
1745
+ var Blueprint = Schema8.Struct({
1746
+ name: Schema8.optional(Schema8.String),
1747
+ steps: Schema8.Array(BlueprintStepSchema)
1748
+ }).pipe(Type.Obj({
1749
+ typename: "dxos.org/type/Blueprint",
1750
+ version: "0.1.0"
1751
+ }));
1698
1752
  (function(BlueprintBuilder2) {
1699
1753
  BlueprintBuilder2.create = () => new Builder();
1700
1754
  class Builder {
@@ -1710,33 +1764,20 @@ var Blueprint = Schema8.Struct({
1710
1764
  return this;
1711
1765
  }
1712
1766
  build() {
1713
- return {
1767
+ return Obj.make(Blueprint, {
1714
1768
  steps: this._steps
1715
- };
1769
+ });
1716
1770
  }
1717
1771
  }
1718
1772
  })(BlueprintBuilder || (BlueprintBuilder = {}));
1719
1773
  (function(BlueprintParser2) {
1720
- BlueprintParser2.create = (tools = []) => new Parser(tools);
1774
+ BlueprintParser2.create = () => new Parser();
1721
1775
  class Parser {
1722
- constructor(_tools) {
1723
- this._tools = _tools;
1724
- }
1725
- toJSON() {
1726
- return {
1727
- tools: this._tools.map((tool) => ({
1728
- name: tool.name,
1729
- namespace: tool.namespace,
1730
- type: tool.type
1731
- }))
1732
- };
1733
- }
1734
1776
  parse({ steps }) {
1735
1777
  const builder = BlueprintBuilder.create();
1736
1778
  for (const step of steps) {
1737
1779
  builder.step(step.instructions, {
1738
- // TODO(burdon): Tool resolution is duplicated in the session and ollama-client.
1739
- tools: step.tools?.map((tool) => this._tools.find(({ id }) => id === tool) ?? raise(new Error(`Tool not found: ${tool}`)))
1780
+ tools: step.tools ?? []
1740
1781
  });
1741
1782
  }
1742
1783
  return builder.build();
@@ -1752,6 +1793,7 @@ import { createTool as createTool4, Message as Message3, ToolResult as ToolResul
1752
1793
  import { Event as Event2 } from "@dxos/async";
1753
1794
  import { create as create6 } from "@dxos/echo-schema";
1754
1795
  import { log as log9 } from "@dxos/log";
1796
+ import { isNonNullable as isNonNullable2 } from "@dxos/util";
1755
1797
  var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/assistant/src/blueprint/machine.ts";
1756
1798
  var INITIAL_STATE = {
1757
1799
  state: "working",
@@ -1759,7 +1801,8 @@ var INITIAL_STATE = {
1759
1801
  trace: []
1760
1802
  };
1761
1803
  var BlueprintMachine = class {
1762
- constructor(blueprint) {
1804
+ constructor(registry, blueprint) {
1805
+ this.registry = registry;
1763
1806
  this.blueprint = blueprint;
1764
1807
  this.begin = new Event2();
1765
1808
  this.end = new Event2();
@@ -1772,7 +1815,7 @@ var BlueprintMachine = class {
1772
1815
  async runToCompletion(options) {
1773
1816
  log9.info("runToCompletion", options, {
1774
1817
  F: __dxlog_file9,
1775
- L: 67,
1818
+ L: 71,
1776
1819
  S: this,
1777
1820
  C: (f, a) => f(...a)
1778
1821
  });
@@ -1829,6 +1872,7 @@ var BlueprintMachine = class {
1829
1872
  })
1830
1873
  ] : [];
1831
1874
  inputMessages.forEach((message) => this.message.emit(message));
1875
+ const tools = nextStep.tools.map((tool) => this.registry.get(tool)).filter(isNonNullable2);
1832
1876
  const messages = await session.run({
1833
1877
  systemPrompt: `
1834
1878
  You are a smart Rule-Following Agent.
@@ -1845,7 +1889,7 @@ var BlueprintMachine = class {
1845
1889
  ...inputMessages
1846
1890
  ],
1847
1891
  tools: [
1848
- ...nextStep.tools,
1892
+ ...tools,
1849
1893
  report
1850
1894
  ],
1851
1895
  artifacts: [],
@@ -1906,25 +1950,57 @@ var popLastToolCall = (messages) => {
1906
1950
  };
1907
1951
 
1908
1952
  // packages/core/assistant/src/blueprint/logger.ts
1953
+ import { signal } from "@preact/signals-core";
1909
1954
  import chalk from "chalk";
1910
1955
  import { ConsolePrinter as ConsolePrinter2 } from "@dxos/ai";
1956
+ import { combine } from "@dxos/async";
1911
1957
  chalk.level = 2;
1912
- var setConsolePrinter = (machine, extraLogging = false) => {
1958
+ var Logger = class {
1959
+ constructor() {
1960
+ this._messages = signal([]);
1961
+ }
1962
+ get messages() {
1963
+ return this._messages;
1964
+ }
1965
+ clear() {
1966
+ this._messages.value = [];
1967
+ }
1968
+ log(message) {
1969
+ this._messages.value = [
1970
+ ...this._messages.value,
1971
+ message
1972
+ ];
1973
+ }
1974
+ };
1975
+ var setLogger = (machine, logger) => {
1976
+ return combine(machine.begin.on(() => {
1977
+ logger.log("Starting...");
1978
+ }), machine.stepStart.on((step) => {
1979
+ const index = machine.blueprint.steps.indexOf(step);
1980
+ logger.log(`Step ${index + 1} of ${machine.blueprint.steps.length}`);
1981
+ logger.log(`Instructions: ${step.instructions}`);
1982
+ }), machine.stepComplete.on((step) => {
1983
+ const trace = machine.state.trace.find((t) => t.stepId === step.id);
1984
+ logger.log(`Complete: ${trace?.comment}`);
1985
+ }), machine.end.on(() => {
1986
+ logger.log("OK");
1987
+ }));
1988
+ };
1989
+ var setConsolePrinter = (machine, verbose = false) => {
1913
1990
  const printer = new ConsolePrinter2();
1914
- if (extraLogging) {
1915
- machine.stepStart.on((step) => console.log(`
1991
+ return combine(machine.begin.on(() => printTrace(machine.blueprint, machine.state)), machine.stepStart.on((step) => console.log(`
1916
1992
  ${chalk.magenta(`${chalk.bold(`STEP ${machine.blueprint.steps.indexOf(step) + 1} of ${machine.blueprint.steps.length}:`)} ${step.instructions}`)}
1917
- `));
1918
- machine.message.on((msg) => printer.printMessage(msg));
1919
- machine.block.on((block) => printer.printContentBlock(block));
1920
- }
1921
- machine.begin.on(() => printTrace(machine.blueprint, machine.state));
1922
- machine.stepComplete.on(() => printTrace(machine.blueprint, machine.state));
1993
+ `)), machine.stepComplete.on(() => printTrace(machine.blueprint, machine.state)), machine.end.on(() => console.log("DONE")), verbose ? [
1994
+ machine.message.on((msg) => printer.printMessage(msg)),
1995
+ machine.block.on((block) => printer.printContentBlock(block))
1996
+ ] : []);
1923
1997
  };
1998
+ var BREAK_LINE = `
1999
+ ${"_".repeat(80)}
2000
+ `;
1924
2001
  var printTrace = (blueprint, state) => {
1925
- console.log("\n==============================================\n");
1926
- console.log(chalk.bold("\nThe Blueprint:"));
1927
- blueprint.steps.forEach((step, index) => {
2002
+ console.group(chalk.bold("\nBlueprint"));
2003
+ blueprint.steps.forEach((step) => {
1928
2004
  const traceStep = state.trace.find((t) => t.stepId === step.id);
1929
2005
  let color = chalk.gray;
1930
2006
  let bullet = "\u25CB";
@@ -1947,11 +2023,11 @@ var printTrace = (blueprint, state) => {
1947
2023
  console.log(color(`
1948
2024
  ${bullet} ${step.instructions}`));
1949
2025
  if (traceStep?.comment) {
1950
- console.log(chalk.white(` \u21B3 ${traceStep.comment}`));
2026
+ console.log(chalk.white(` \u21B3 ${traceStep.comment}`));
1951
2027
  }
1952
2028
  });
1953
- console.log("\n");
1954
- console.log("\n==============================================\n");
2029
+ console.groupEnd();
2030
+ console.log(BREAK_LINE);
1955
2031
  };
1956
2032
  export {
1957
2033
  AIServiecOverloadedError,
@@ -1960,9 +2036,11 @@ export {
1960
2036
  BlueprintBuilder,
1961
2037
  BlueprintMachine,
1962
2038
  BlueprintParser,
1963
- BlueprintStep,
2039
+ BlueprintSchema,
2040
+ BlueprintStepSchema,
1964
2041
  ExtractionInput,
1965
2042
  ExtractionOutput,
2043
+ Logger,
1966
2044
  ReferencedQuotes,
1967
2045
  Subgraph,
1968
2046
  VersionPin,
@@ -1985,6 +2063,7 @@ export {
1985
2063
  processTranscriptMessage,
1986
2064
  researchFn,
1987
2065
  sanitizeObjects,
1988
- setConsolePrinter
2066
+ setConsolePrinter,
2067
+ setLogger
1989
2068
  };
1990
2069
  //# sourceMappingURL=index.mjs.map