effect-assistant 0.1.0 → 0.2.0

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 (80) hide show
  1. package/README.md +1 -1
  2. package/dist/AssistantEvent.d.ts +3 -66
  3. package/dist/AssistantEvent.d.ts.map +1 -1
  4. package/dist/AssistantEvent.js +1 -51
  5. package/dist/AssistantEvent.js.map +1 -1
  6. package/dist/AssistantLoop.d.ts +7 -5
  7. package/dist/AssistantLoop.d.ts.map +1 -1
  8. package/dist/AssistantLoop.js +6 -3
  9. package/dist/AssistantLoop.js.map +1 -1
  10. package/dist/Block.js.map +1 -1
  11. package/dist/BlockKit.d.ts +11 -15
  12. package/dist/BlockKit.d.ts.map +1 -1
  13. package/dist/BlockKit.js +3 -6
  14. package/dist/BlockKit.js.map +1 -1
  15. package/dist/ChatView.d.ts +7 -58
  16. package/dist/ChatView.d.ts.map +1 -1
  17. package/dist/ChatView.js +15 -68
  18. package/dist/ChatView.js.map +1 -1
  19. package/dist/Compaction.d.ts +2 -2
  20. package/dist/Compaction.d.ts.map +1 -1
  21. package/dist/Compaction.js +6 -13
  22. package/dist/Compaction.js.map +1 -1
  23. package/dist/ToolDiscovery.d.ts +4 -5
  24. package/dist/ToolDiscovery.d.ts.map +1 -1
  25. package/dist/ToolDiscovery.js +5 -4
  26. package/dist/ToolDiscovery.js.map +1 -1
  27. package/dist/ToolFailure.d.ts +1 -1
  28. package/dist/ToolFailure.js +1 -1
  29. package/dist/ToolFailure.js.map +1 -1
  30. package/dist/index.d.ts +1 -3
  31. package/dist/index.js +3 -5
  32. package/dist/internal/chat.js +6 -31
  33. package/dist/internal/chat.js.map +1 -1
  34. package/dist/internal/history.js +2 -40
  35. package/dist/internal/history.js.map +1 -1
  36. package/dist/internal/loop.d.ts +2 -2
  37. package/dist/internal/loop.d.ts.map +1 -1
  38. package/dist/internal/loop.js +20 -55
  39. package/dist/internal/loop.js.map +1 -1
  40. package/dist/internal/specialists.js +2 -3
  41. package/dist/internal/specialists.js.map +1 -1
  42. package/dist/internal/toolkit.d.ts +6 -20
  43. package/dist/internal/toolkit.d.ts.map +1 -1
  44. package/dist/internal/toolkit.js +10 -31
  45. package/dist/internal/toolkit.js.map +1 -1
  46. package/dist/internal/tools.js +1 -20
  47. package/dist/internal/tools.js.map +1 -1
  48. package/dist/internal/turns.d.ts.map +1 -1
  49. package/dist/internal/turns.js +2 -9
  50. package/dist/internal/turns.js.map +1 -1
  51. package/package.json +3 -2
  52. package/src/AssistantEvent.ts +0 -66
  53. package/src/AssistantLoop.ts +7 -5
  54. package/src/Block.ts +1 -1
  55. package/src/BlockKit.ts +12 -25
  56. package/src/ChatView.ts +10 -81
  57. package/src/Compaction.ts +2 -19
  58. package/src/ToolDiscovery.ts +5 -13
  59. package/src/ToolFailure.ts +1 -1
  60. package/src/index.ts +0 -10
  61. package/src/internal/chat.ts +4 -53
  62. package/src/internal/history.ts +2 -74
  63. package/src/internal/loop.ts +31 -101
  64. package/src/internal/specialists.ts +3 -7
  65. package/src/internal/toolkit.ts +17 -60
  66. package/src/internal/tools.ts +2 -53
  67. package/src/internal/turns.ts +7 -26
  68. package/dist/Decision.d.ts +0 -145
  69. package/dist/Decision.d.ts.map +0 -1
  70. package/dist/Decision.js +0 -178
  71. package/dist/Decision.js.map +0 -1
  72. package/dist/DecisionId.d.ts +0 -37
  73. package/dist/DecisionId.d.ts.map +0 -1
  74. package/dist/DecisionId.js +0 -44
  75. package/dist/DecisionId.js.map +0 -1
  76. package/dist/internal/decisions.js +0 -66
  77. package/dist/internal/decisions.js.map +0 -1
  78. package/src/Decision.ts +0 -241
  79. package/src/DecisionId.ts +0 -46
  80. package/src/internal/decisions.ts +0 -131
@@ -1,8 +1,6 @@
1
1
  import { fromKey } from "./uuid.js";
2
2
  import { AssistantMessage, MessageBlock, isLibraryEvent } from "../AssistantEvent.js";
3
3
  import { CurrentChat } from "../CurrentChat.js";
4
- import { Props, fromEntries } from "../Decision.js";
5
- import { fromEntries as fromEntries$1 } from "../BlockKit.js";
6
4
  import { AssistantToolCall } from "../AssistantToolCall.js";
7
5
  import { ToolFailure, fail } from "../ToolFailure.js";
8
6
  import { fromWithHandler } from "./toolkit.js";
@@ -55,18 +53,6 @@ const plainHandlers = PlainTools.toHandlers({
55
53
  const plainTools = Effect.gen(function* () {
56
54
  return yield* Effect.provideContext(PlainTools, yield* plainHandlers);
57
55
  });
58
- const decodeDecisionProps = Schema.decodeUnknownOption(Props);
59
- const checkDecisions = Effect.fnUntraced(function* (ids) {
60
- const states = fromEntries(yield* CurrentChat.use((chat) => chat.entries));
61
- const notWaiting = ids.filter((id) => states.get(id)?.outcome !== void 0 || !states.has(id));
62
- if (notWaiting.length > 0) return yield* fail(`Not waiting for the user's decision: ${notWaiting.join(", ")}. Use the ids of decisions that wait for one.`, { reason: "NotWaitingForDecision" });
63
- });
64
- const checkCloses = Effect.fnUntraced(function* (ids) {
65
- const entries = yield* CurrentChat.use((chat) => chat.entries);
66
- const states = fromEntries$1(entries);
67
- const waiting = ids.filter((id) => entries.some(({ event }) => isLibraryEvent(event) && Predicate.isTagged(event, "AssistantMessage") && event.id === id && event.block?.kind === "decision" && states.get(id)?.open === true));
68
- if (waiting.length > 0) return yield* fail(`${waiting.join(", ")} asks for a decision that still waits for the user: only their answer in the block closes it. Send the message again without ${waiting.length === 1 ? "that id" : "those ids"} in closes.`, { reason: "DecisionWaiting" });
69
- });
70
56
  const blockTools = Effect.fnUntraced(function* (kit) {
71
57
  const catalog = kit.blocks.map((block) => `- ${block.kind}: ${block.description}`).join("\n");
72
58
  const kinds = kit.blocks.map((block) => block.kind);
@@ -82,7 +68,7 @@ ${catalog}`,
82
68
  kind: Schema.Literals(kinds),
83
69
  props: Schema.Union(kit.blocks.map((block) => block.props))
84
70
  })),
85
- closes: Schema.optional(Schema.Array(Schema.String)).annotate({ description: "Ids of your earlier messages whose block the user just answered by typing instead of using it. Those blocks close. Leave it out otherwise: a block stays open when the user talks about something else. A decision block never closes this way: only the user's answer in it decides." })
71
+ closes: Schema.optional(Schema.Array(Schema.String)).annotate({ description: "Ids of your earlier messages whose block the user just answered by typing instead of using it. Those blocks close. Leave it out otherwise: a block stays open when the user talks about something else." })
86
72
  }),
87
73
  success: Schema.String,
88
74
  failure: ToolFailure,
@@ -95,7 +81,6 @@ ${catalog}`,
95
81
  if (text.trim() === "") return yield* fail("The message has no text: the user sees only what you send here, and a block alone is an empty bubble. Send it again with the words they should read (a short lead-in for the block).", { reason: "EmptyMessage" });
96
82
  const id = yield* messageId;
97
83
  const closed = closes === void 0 || closes.length === 0 ? {} : { closes };
98
- if (closes !== void 0 && closes.length > 0) yield* checkCloses(closes);
99
84
  if (block === void 0) {
100
85
  yield* append(AssistantMessage.make({
101
86
  id,
@@ -106,10 +91,6 @@ ${catalog}`,
106
91
  }
107
92
  const props = kit.byKind.get(block.kind)?.props;
108
93
  if (props === void 0 || Option.isNone(Schema.decodeUnknownOption(props)(block.props))) return yield* fail(`Those props don't fit a ${block.kind} block.`);
109
- if (block.kind === "decision") yield* checkDecisions(Option.match(decodeDecisionProps(block.props), {
110
- onNone: () => [],
111
- onSome: (decoded) => decoded.decisionIds
112
- }));
113
94
  yield* append(AssistantMessage.make({
114
95
  id,
115
96
  text,
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":["Uuid.fromKey","AssistantEvent.isLibraryEvent","ToolFailure.ToolFailure","Decision.Props","Decision.fromEntries","ToolFailure.fail","BlockKit.fromEntries","Toolkits.fromWithHandler"],"sources":["../../src/internal/tools.ts"],"sourcesContent":["import * as Tool from \"effect/ai/Tool\"\nimport * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport { AssistantToolCall } from \"../AssistantToolCall.ts\"\nimport * as BlockKit from \"../BlockKit.ts\"\nimport { CurrentChat } from \"../CurrentChat.ts\"\nimport * as Decision from \"../Decision.ts\"\nimport * as ToolFailure from \"../ToolFailure.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const waitToolName = \"wait\"\n\n/** @internal */\nexport const sendUserMessageName = \"send_user_message\"\n\nconst Wait = Tool.make(waitToolName, {\n description:\n \"End your turn and wait for the next message or update, when you have nothing more to do right now and no message to send (otherwise set wait on send_user_message).\",\n success: Schema.String\n})\n\nconst description =\n \"Send the user a chat message. It's the only way they see anything you write: text outside it is private to you.\"\n\nconst WaitFlag = Schema.Boolean.annotate({\n description:\n \"true when this is your last message for now: your turn ends with it, as with the wait tool. false when you keep working after it.\"\n})\n\nconst endsWithMessage = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(true) }))\n\n/** @internal */\nexport const isTurnEnding = (call: AssistantEvent.ToolCallPart): boolean =>\n call.name === waitToolName || (call.name === sendUserMessageName && Option.isSome(endsWithMessage(call.params)))\n\n// From the call: a call cut off by a crash runs again with the same id, and finds its message already sent.\nconst messageId = AssistantToolCall.useSync((call) => Uuid.fromKey(`message:${call.callId}`))\n\nconst append = Effect.fnUntraced(function* (message: AssistantEvent.AssistantMessage) {\n const chat = yield* CurrentChat\n const entries = yield* chat.entries\n\n const sent = entries.some(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") && event.id === message.id\n )\n\n if (!sent) yield* chat.append(message)\n})\n\nconst PlainMessage = Tool.make(sendUserMessageName, {\n description,\n parameters: Schema.Struct({ text: Schema.String, wait: WaitFlag }),\n success: Schema.String,\n failure: ToolFailure.ToolFailure,\n dependencies: [CurrentChat, AssistantToolCall]\n})\n\nconst PlainTools = Toolkit.make(PlainMessage, Wait)\n\nconst plainHandlers = PlainTools.toHandlers({\n wait: () => Effect.succeed(\"waiting\"),\n send_user_message: Effect.fnUntraced(function* ({ text }) {\n yield* append(AssistantEvent.AssistantMessage.make({ id: yield* messageId, text }))\n\n return \"sent\"\n })\n})\n\nconst plainTools = Effect.gen(function* () {\n return yield* Effect.provideContext(PlainTools, yield* plainHandlers)\n})\n\nconst decodeDecisionProps = Schema.decodeUnknownOption(Decision.Props)\n\nconst checkDecisions = Effect.fnUntraced(function* (ids: ReadonlyArray<string>) {\n const states = Decision.fromEntries(yield* CurrentChat.use((chat) => chat.entries))\n const notWaiting = ids.filter((id) => states.get(id)?.outcome !== undefined || !states.has(id))\n\n if (notWaiting.length > 0) {\n return yield* ToolFailure.fail(\n `Not waiting for the user's decision: ${notWaiting.join(\", \")}. Use the ids of decisions that wait for one.`,\n { reason: \"NotWaitingForDecision\" }\n )\n }\n})\n\n// A decision block closes when the user decides on it, not because the model says so: the order it asks about would\n// otherwise never be approved.\nconst checkCloses = Effect.fnUntraced(function* (ids: ReadonlyArray<string>) {\n const entries = yield* CurrentChat.use((chat) => chat.entries)\n const states = BlockKit.fromEntries(entries)\n\n const waiting = ids.filter((id) =>\n entries.some(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"AssistantMessage\") &&\n event.id === id &&\n event.block?.kind === Decision.kind &&\n states.get(id)?.open === true\n )\n )\n\n if (waiting.length > 0) {\n return yield* ToolFailure.fail(\n `${waiting.join(\", \")} asks for a decision that still waits for the user: only their answer in the block closes it. Send the message again without ${waiting.length === 1 ? \"that id\" : \"those ids\"} in closes.`,\n { reason: \"DecisionWaiting\" }\n )\n }\n})\n\nconst blockTools = Effect.fnUntraced(function* (kit: BlockKit.BlockKit) {\n const catalog = kit.blocks.map((block) => `- ${block.kind}: ${block.description}`).join(\"\\n\")\n const kinds = kit.blocks.map((block) => block.kind)\n\n const BlockMessage = Tool.make(sendUserMessageName, {\n description: `${description}\nYou can add a block to show UI with the message, e.g. a few options to pick from or a yes/no, when that makes answering easier than typing. Plain text is fine too. Using it sends you an <answer>; the user may also just type their answer instead, and then you pass that message's id in closes.\nBlocks:\n${catalog}`,\n // Props are checked against their kind's schema by the handler; the model sees every kind's in the parameters.\n parameters: Schema.Struct({\n text: Schema.String,\n wait: WaitFlag,\n block: Schema.optional(\n Schema.Struct({\n kind: Schema.Literals(kinds),\n props: Schema.Union(kit.blocks.map((block) => block.props))\n })\n ),\n closes: Schema.optional(Schema.Array(Schema.String)).annotate({\n description:\n \"Ids of your earlier messages whose block the user just answered by typing instead of using it. Those blocks close. Leave it out otherwise: a block stays open when the user talks about something else. A decision block never closes this way: only the user's answer in it decides.\"\n })\n }),\n success: Schema.String,\n failure: ToolFailure.ToolFailure,\n dependencies: [CurrentChat, AssistantToolCall]\n })\n\n const BlockTools = Toolkit.make(BlockMessage, Wait)\n\n const handlers = yield* BlockTools.toHandlers({\n wait: () => Effect.succeed(\"waiting\"),\n send_user_message: Effect.fnUntraced(function* ({ text, block, closes }) {\n if (text.trim() === \"\") {\n return yield* ToolFailure.fail(\n \"The message has no text: the user sees only what you send here, and a block alone is an empty bubble. Send it again with the words they should read (a short lead-in for the block).\",\n { reason: \"EmptyMessage\" }\n )\n }\n\n const id = yield* messageId\n const closed = closes === undefined || closes.length === 0 ? {} : { closes }\n\n if (closes !== undefined && closes.length > 0) yield* checkCloses(closes)\n\n if (block === undefined) {\n yield* append(AssistantEvent.AssistantMessage.make({ id, text, ...closed }))\n\n return \"sent\"\n }\n\n const props = kit.byKind.get(block.kind)?.props\n\n if (props === undefined || Option.isNone(Schema.decodeUnknownOption(props)(block.props))) {\n return yield* ToolFailure.fail(`Those props don't fit a ${block.kind} block.`)\n }\n\n if (block.kind === Decision.kind) {\n yield* checkDecisions(\n Option.match(decodeDecisionProps(block.props), {\n onNone: () => [],\n onSome: (decoded) => decoded.decisionIds\n })\n )\n }\n\n yield* append(\n AssistantEvent.AssistantMessage.make({\n id,\n text,\n block: AssistantEvent.MessageBlock.make(block),\n ...closed\n })\n )\n\n return `sent as message ${id}`\n })\n })\n\n return yield* Effect.provideContext(BlockTools, handlers)\n})\n\n/** @internal */\nexport const makeMessaging: (kit: BlockKit.BlockKit | undefined) => Effect.Effect<Toolkits.Tools<CurrentChat>> =\n Effect.fnUntraced(function* (kit) {\n if (kit === undefined || kit.blocks.length === 0) {\n return Toolkits.fromWithHandler(yield* plainTools)\n }\n\n return Toolkits.fromWithHandler(yield* blockTools(kit))\n })\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAa,eAAe;;AAG5B,MAAa,sBAAsB;AAEnC,MAAM,OAAO,KAAK,KAAK,cAAc;CACnC,aACE;CACF,SAAS,OAAO;AAClB,CAAC;AAED,MAAM,cACJ;AAEF,MAAM,WAAW,OAAO,QAAQ,SAAS,EACvC,aACE,oIACJ,CAAC;AAED,MAAM,kBAAkB,OAAO,oBAAoB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,IAAI,EAAE,CAAC,CAAC;;AAGhG,MAAa,gBAAgB,SAC3B,KAAK,SAAA,UAA0B,KAAK,SAAA,uBAAgC,OAAO,OAAO,gBAAgB,KAAK,MAAM,CAAC;AAGhH,MAAM,YAAY,kBAAkB,SAAS,SAASA,QAAa,WAAW,KAAK,QAAQ,CAAC;AAE5F,MAAM,SAAS,OAAO,WAAW,WAAW,SAA0C;CACpF,MAAM,OAAO,OAAO;CAQpB,IAAI,EALS,OAFU,KAAK,QAAA,CAEP,MAClB,EAAE,YACDC,eAA8B,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,KAAK,MAAM,OAAO,QAAQ,EAG1G,GAAG,OAAO,KAAK,OAAO,OAAO;AACvC,CAAC;AAED,MAAM,eAAe,KAAK,KAAK,qBAAqB;CAClD;CACA,YAAY,OAAO,OAAO;EAAE,MAAM,OAAO;EAAQ,MAAM;CAAS,CAAC;CACjE,SAAS,OAAO;CAChB,SAASC;CACT,cAAc,CAAC,aAAa,iBAAiB;AAC/C,CAAC;AAED,MAAM,aAAa,QAAQ,KAAK,cAAc,IAAI;AAElD,MAAM,gBAAgB,WAAW,WAAW;CAC1C,YAAY,OAAO,QAAQ,SAAS;CAC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,OAAO,oBAAoB,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,GACrF,OAAO,OAAOA,KAAiB,2BAA2B,MAAM,KAAK,QAAQ;GAG/E,IAAI,MAAM,SAAS,YACjB,OAAO,eACL,OAAO,MAAM,oBAAoB,MAAM,KAAK,GAAG;IAC7C,cAAc,CAAC;IACf,SAAS,YAAY,QAAQ;GAC/B,CAAC,CACH;GAGF,OAAO,OAAA,iBAC2B,KAAK;IACnC;IACA;IACA,OAAA,aAAmC,KAAK,KAAK;IAC7C,GAAG;GACL,CAAC,CACH;GAEA,OAAO,mBAAmB;EAC5B,CAAC;CACH,CAAC;CAED,OAAO,OAAO,OAAO,eAAe,YAAY,QAAQ;AAC1D,CAAC;;AAGD,MAAa,gBACX,OAAO,WAAW,WAAW,KAAK;CAChC,IAAI,QAAQ,KAAA,KAAa,IAAI,OAAO,WAAW,GAC7C,OAAOE,gBAAyB,OAAO,UAAU;CAGnD,OAAOA,gBAAyB,OAAO,WAAW,GAAG,CAAC;AACxD,CAAC"}
1
+ {"version":3,"file":"tools.js","names":["Uuid.fromKey","AssistantEvent.isLibraryEvent","ToolFailure.ToolFailure","ToolFailure.fail","Toolkits.fromWithHandler"],"sources":["../../src/internal/tools.ts"],"sourcesContent":["import * as Tool from \"effect/ai/Tool\"\nimport * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport { AssistantToolCall } from \"../AssistantToolCall.ts\"\nimport type * as BlockKit from \"../BlockKit.ts\"\nimport { CurrentChat } from \"../CurrentChat.ts\"\nimport * as ToolFailure from \"../ToolFailure.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const waitToolName = \"wait\"\n\n/** @internal */\nexport const sendUserMessageName = \"send_user_message\"\n\nconst Wait = Tool.make(waitToolName, {\n description:\n \"End your turn and wait for the next message or update, when you have nothing more to do right now and no message to send (otherwise set wait on send_user_message).\",\n success: Schema.String\n})\n\nconst description =\n \"Send the user a chat message. It's the only way they see anything you write: text outside it is private to you.\"\n\nconst WaitFlag = Schema.Boolean.annotate({\n description:\n \"true when this is your last message for now: your turn ends with it, as with the wait tool. false when you keep working after it.\"\n})\n\nconst endsWithMessage = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(true) }))\n\n/** @internal */\nexport const isTurnEnding = (call: AssistantEvent.ToolCallPart): boolean =>\n call.name === waitToolName || (call.name === sendUserMessageName && Option.isSome(endsWithMessage(call.params)))\n\n// From the call: a call cut off by a crash runs again with the same id, and finds its message already sent.\nconst messageId = AssistantToolCall.useSync((call) => Uuid.fromKey(`message:${call.callId}`))\n\nconst append = Effect.fnUntraced(function* (message: AssistantEvent.AssistantMessage) {\n const chat = yield* CurrentChat\n const entries = yield* chat.entries\n\n const sent = entries.some(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") && event.id === message.id\n )\n\n if (!sent) yield* chat.append(message)\n})\n\nconst PlainMessage = Tool.make(sendUserMessageName, {\n description,\n parameters: Schema.Struct({ text: Schema.String, wait: WaitFlag }),\n success: Schema.String,\n failure: ToolFailure.ToolFailure,\n dependencies: [CurrentChat, AssistantToolCall]\n})\n\nconst PlainTools = Toolkit.make(PlainMessage, Wait)\n\nconst plainHandlers = PlainTools.toHandlers({\n wait: () => Effect.succeed(\"waiting\"),\n send_user_message: Effect.fnUntraced(function* ({ text }) {\n yield* append(AssistantEvent.AssistantMessage.make({ id: yield* messageId, text }))\n\n return \"sent\"\n })\n})\n\nconst plainTools = Effect.gen(function* () {\n return yield* Effect.provideContext(PlainTools, yield* plainHandlers)\n})\n\nconst blockTools = Effect.fnUntraced(function* (kit: BlockKit.BlockKit) {\n const catalog = kit.blocks.map((block) => `- ${block.kind}: ${block.description}`).join(\"\\n\")\n const kinds = kit.blocks.map((block) => block.kind)\n\n const BlockMessage = Tool.make(sendUserMessageName, {\n description: `${description}\nYou can add a block to show UI with the message, e.g. a few options to pick from or a yes/no, when that makes answering easier than typing. Plain text is fine too. Using it sends you an <answer>; the user may also just type their answer instead, and then you pass that message's id in closes.\nBlocks:\n${catalog}`,\n // Props are checked against their kind's schema by the handler; the model sees every kind's in the parameters.\n parameters: Schema.Struct({\n text: Schema.String,\n wait: WaitFlag,\n block: Schema.optional(\n Schema.Struct({\n kind: Schema.Literals(kinds),\n props: Schema.Union(kit.blocks.map((block) => block.props))\n })\n ),\n closes: Schema.optional(Schema.Array(Schema.String)).annotate({\n description:\n \"Ids of your earlier messages whose block the user just answered by typing instead of using it. Those blocks close. Leave it out otherwise: a block stays open when the user talks about something else.\"\n })\n }),\n success: Schema.String,\n failure: ToolFailure.ToolFailure,\n dependencies: [CurrentChat, AssistantToolCall]\n })\n\n const BlockTools = Toolkit.make(BlockMessage, Wait)\n\n const handlers = yield* BlockTools.toHandlers({\n wait: () => Effect.succeed(\"waiting\"),\n send_user_message: Effect.fnUntraced(function* ({ text, block, closes }) {\n if (text.trim() === \"\") {\n return yield* ToolFailure.fail(\n \"The message has no text: the user sees only what you send here, and a block alone is an empty bubble. Send it again with the words they should read (a short lead-in for the block).\",\n { reason: \"EmptyMessage\" }\n )\n }\n\n const id = yield* messageId\n const closed = closes === undefined || closes.length === 0 ? {} : { closes }\n\n if (block === undefined) {\n yield* append(AssistantEvent.AssistantMessage.make({ id, text, ...closed }))\n\n return \"sent\"\n }\n\n const props = kit.byKind.get(block.kind)?.props\n\n if (props === undefined || Option.isNone(Schema.decodeUnknownOption(props)(block.props))) {\n return yield* ToolFailure.fail(`Those props don't fit a ${block.kind} block.`)\n }\n\n yield* append(\n AssistantEvent.AssistantMessage.make({\n id,\n text,\n block: AssistantEvent.MessageBlock.make(block),\n ...closed\n })\n )\n\n return `sent as message ${id}`\n })\n })\n\n return yield* Effect.provideContext(BlockTools, handlers)\n})\n\n/** @internal */\nexport const makeMessaging: (kit: BlockKit.BlockKit | undefined) => Effect.Effect<Toolkits.Tools<CurrentChat>> =\n Effect.fnUntraced(function* (kit) {\n if (kit === undefined || kit.blocks.length === 0) {\n return Toolkits.fromWithHandler(yield* plainTools)\n }\n\n return Toolkits.fromWithHandler(yield* blockTools(kit))\n })\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,eAAe;;AAG5B,MAAa,sBAAsB;AAEnC,MAAM,OAAO,KAAK,KAAK,cAAc;CACnC,aACE;CACF,SAAS,OAAO;AAClB,CAAC;AAED,MAAM,cACJ;AAEF,MAAM,WAAW,OAAO,QAAQ,SAAS,EACvC,aACE,oIACJ,CAAC;AAED,MAAM,kBAAkB,OAAO,oBAAoB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,IAAI,EAAE,CAAC,CAAC;;AAGhG,MAAa,gBAAgB,SAC3B,KAAK,SAAA,UAA0B,KAAK,SAAA,uBAAgC,OAAO,OAAO,gBAAgB,KAAK,MAAM,CAAC;AAGhH,MAAM,YAAY,kBAAkB,SAAS,SAASA,QAAa,WAAW,KAAK,QAAQ,CAAC;AAE5F,MAAM,SAAS,OAAO,WAAW,WAAW,SAA0C;CACpF,MAAM,OAAO,OAAO;CAQpB,IAAI,EALS,OAFU,KAAK,QAAA,CAEP,MAClB,EAAE,YACDC,eAA8B,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,KAAK,MAAM,OAAO,QAAQ,EAG1G,GAAG,OAAO,KAAK,OAAO,OAAO;AACvC,CAAC;AAED,MAAM,eAAe,KAAK,KAAK,qBAAqB;CAClD;CACA,YAAY,OAAO,OAAO;EAAE,MAAM,OAAO;EAAQ,MAAM;CAAS,CAAC;CACjE,SAAS,OAAO;CAChB,SAASC;CACT,cAAc,CAAC,aAAa,iBAAiB;AAC/C,CAAC;AAED,MAAM,aAAa,QAAQ,KAAK,cAAc,IAAI;AAElD,MAAM,gBAAgB,WAAW,WAAW;CAC1C,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,MAAe;;;qBAIvB,WAAQ,YAAA,YAAA;WAEO,MAAA;MAuC1B,OAAA,OAAA,qBAAA,cAAA;;qBA8OW,MAAG;WAEW,cAAA;WACL,SAAA;WACH,MAAA;WACI,UAAA,QAAQ,QAAQ,eAAyB,cAAc;WAEtD,WAAA,OAAO;MA2D9B,OAAA"}
1
+ {"version":3,"file":"turns.d.ts","names":[],"sources":["../../src/internal/turns.ts"],"mappings":";;;;;;;;;;;;;;;;;;qBAmCa;;qBAGA;;qBAIA;;iBAII;WACN;WACA,QAAQ;WACR,aAAa,cAAc;WAC3B,KAAK;;;YAKJ,eACV,MAAM,cACH,OAAO,OAAO,gBAA8B,eAAyB,cAAc;;iBAKvE;WACN,QAAQ;WACR,SAAS,OAAO,OAAO;WACvB,QAAQ;;;iBAIF;WACN,YAAY;WACZ,OAAO,QAAQ,QAAQ,cAAc;WACrC,OAAO,MAAM,cAAc,OAAO,OAAO,oBAAoB,MAAM,QAAQ;WAC3E,aAAa;aACX,YAAY;aACZ,OAAO;;WAET,UAAU,MAAe;;;qBAIvB,WAAQ,YAAA,YAAA;WAEO,MAAA;MAiC1B,OAAA,OAAA,qBAAA,cAAA;;qBAmOW,MAAG;WAEW,cAAA;WACL,SAAA;WACH,MAAA;WACI,UAAA,QAAQ,QAAQ,eAAyB,cAAc;WAEtD,WAAA,OAAO;MA2D9B,OAAA"}
@@ -1,6 +1,4 @@
1
1
  import { ToolResult, TurnCompleted, TurnFailed, TurnStarted, isLibraryEvent } from "../AssistantEvent.js";
2
- import { block, kind } from "../Decision.js";
3
- import { approvedCalls } from "./decisions.js";
4
2
  import { toJsonText } from "./schema.js";
5
3
  import { decodeEntries, read } from "./events.js";
6
4
  import { fromEntries, mayHaveRunOutput, notRunOutput, owesDelivery, owesReply, unansweredCalls, unhandledInputs, unreadAfter, userText } from "./history.js";
@@ -32,8 +30,6 @@ const deliveryNudge = "You told the user you're on it, but stopped without givin
32
30
  /** @internal */
33
31
  const register = Effect.fnUntraced(function* (definition, options) {
34
32
  const model = yield* Effect.context();
35
- const decisionBlock = definition.blocks?.byKind.get(kind);
36
- if (decisionBlock !== void 0 && decisionBlock !== block) return yield* Effect.die(`The ${kind} block kind is the library's: use Decision.block.`);
37
33
  const specialists = yield* Effect.forEach(definition.specialists, Effect.fnUntraced(function* (specialist) {
38
34
  const built = yield* Effect.serviceOption(specialist.Handler);
39
35
  if (Option.isNone(built)) return yield* Effect.die(`No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`);
@@ -79,9 +75,7 @@ const isEntry = (item) => Predicate.hasProperty(item, "seq");
79
75
  const closeOpenCalls = Effect.fnUntraced(function* (chat, startSeq) {
80
76
  const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq);
81
77
  const started = new Set(entries.flatMap(({ event }) => Predicate.isTagged(event, "ToolStarted") ? [event.callId] : []));
82
- const all = yield* chat.entries;
83
- const approved = approvedCalls(all).filter((call) => started.has(call.id));
84
- const open = [...unansweredCalls(fromEntries(entries, () => void 0)), ...approved];
78
+ const open = unansweredCalls(fromEntries(entries, () => void 0));
85
79
  if (open.length === 0) return;
86
80
  yield* chat.append(open.map((call) => ToolResult.make({
87
81
  callId: call.id,
@@ -169,8 +163,7 @@ const makeTurnApi = (registration, chat, startSeq, checkOpen) => {
169
163
  loop: (options) => {
170
164
  const { system, toolkit, view } = prepare(options);
171
165
  const twice = duplicateNames(toolkit);
172
- const deciding = toolkit.definitions.filter((tool) => tool.needsApproval !== void 0 && tool.needsApproval !== false);
173
- const loop = twice.length > 0 ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(", ")}`) : deciding.length > 0 && definition.blocks?.byKind.get("decision") === void 0 ? Stream.die(`${deciding.map((tool) => tool.name).join(", ")} can wait for the user's decision: add Decision.block to the assistant's blocks.`) : run$1({
166
+ const loop = twice.length > 0 ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(", ")}`) : run$1({
174
167
  instructions: system,
175
168
  toolkit,
176
169
  history: history(view),
@@ -1 +1 @@
1
- {"version":3,"file":"turns.js","names":["Decision.kind","Decision.block","Toolkits.merge","Tools.makeMessaging","Specialists.toolkit","History.fromEntries","AppEvents.read","Decisions.approvedCalls","History.unansweredCalls","History.mayHaveRunOutput","History.notRunOutput","AssistantEvent.isLibraryEvent","History.owesReply","History.unreadAfter","AppEvents.decodeEntries","Instructions.protocol","History.owesDelivery","Loop.run","Toolkits.runOnly","Tools.sendUserMessageName","Tools.waitToolName","History.userText","Skill.withCatalog","Skills.toTools","Toolkits.fromToolkitOrEmpty","Toolkits.duplicateNames","Telemetry.agentInput","History.unhandledInputs","Telemetry.currentTraceId","Loop.TurnTools","Toolkits.provide","Telemetry.agentOutput","Telemetry.agentSpan"],"sources":["../../src/internal/turns.ts"],"sourcesContent":["import type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"../Assistant.ts\"\nimport type { ChatId } from \"../ChatId.ts\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as AssistantLoop from \"../AssistantLoop.ts\"\nimport * as Loop from \"./loop.ts\"\nimport type * as BlockKit from \"../BlockKit.ts\"\nimport type { CurrentChat } from \"../CurrentChat.ts\"\nimport * as Decision from \"../Decision.ts\"\nimport * as Instructions from \"../Instructions.ts\"\nimport * as Skill from \"../Skill.ts\"\nimport * as Skills from \"./skills.ts\"\nimport type * as Specialist from \"../Specialist.ts\"\nimport * as Decisions from \"./decisions.ts\"\nimport * as AppEvents from \"./events.ts\"\nimport * as History from \"./history.ts\"\nimport { mapText } from \"./instructions.ts\"\nimport { toJsonText } from \"./schema.ts\"\nimport * as Specialists from \"./specialists.ts\"\nimport * as Telemetry from \"./telemetry.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport type { Writer } from \"./writer.ts\"\nimport * as Tools from \"./tools.ts\"\n\n/** @internal */\nexport const silentTurnMessage = \"I finished without sending a reply.\"\n\n/** @internal */\nexport const defaultReplyNudge =\n \"You haven't replied to the user's latest message yet. Reply now with send_user_message.\"\n\n/** @internal */\nexport const deliveryNudge =\n \"You told the user you're on it, but stopped without giving them the result. Send it now with send_user_message; if part of it is still running, say what and that you'll report back. If they already have everything, call wait.\"\n\n/** @internal */\nexport interface Definition {\n readonly name: string\n readonly blocks: BlockKit.BlockKit | undefined\n readonly specialists: ReadonlyArray<Specialist.Any>\n readonly app: AppEvents.AppEvents\n}\n\n// Once its build ran the layer's services are provided, so its streams need only what a turn provides.\n/** @internal */\nexport type TurnHandler = (\n turn: Assistant.Turn<any>\n) => Stream.Stream<AssistantLoop.Event, unknown, Assistant.TurnServices | LanguageModel.LanguageModel>\n\n// The chat `CurrentChat` gives, with its entries typed as the assistant's decode returns them: the assistant's typed\n// chat is this one, so it needs no check of its own.\n/** @internal */\nexport interface TypedChat {\n readonly chatId: ChatId\n readonly entries: Effect.Effect<AppEvents.DecodedEntries>\n readonly append: CurrentChat[\"Service\"][\"append\"]\n}\n\n/** @internal */\nexport interface Registration {\n readonly definition: Definition\n readonly model: Context.Context<LanguageModel.LanguageModel>\n readonly open: (chat: TypedChat) => Effect.Effect<TurnHandler, never, Scope.Scope | CurrentChat>\n readonly specialists: ReadonlyArray<{\n readonly specialist: Specialist.Any\n readonly built: Specialist.Built\n }>\n readonly builtins: Toolkits.Tools<Assistant.TurnServices>\n}\n\n/** @internal */\nexport const register = Effect.fnUntraced(function* (\n definition: Definition,\n options: { readonly open: Registration[\"open\"] }\n) {\n const model = yield* Effect.context<LanguageModel.LanguageModel>()\n\n const decisionBlock = definition.blocks?.byKind.get(Decision.kind)\n\n if (decisionBlock !== undefined && decisionBlock !== Decision.block) {\n return yield* Effect.die(`The ${Decision.kind} block kind is the library's: use Decision.block.`)\n }\n\n const specialists = yield* Effect.forEach(\n definition.specialists,\n Effect.fnUntraced(function* (specialist) {\n const built = yield* Effect.serviceOption(specialist.Handler)\n\n if (Option.isNone(built)) {\n return yield* Effect.die(\n `No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`\n )\n }\n\n return { specialist, built: built.value }\n })\n )\n\n const builtins = Toolkits.merge(\n yield* Tools.makeMessaging(definition.blocks),\n yield* Specialists.toolkit(definition.specialists)\n )\n\n const registration: Registration = {\n definition,\n model,\n open: options.open,\n specialists,\n builtins\n }\n\n return registration\n})\n\nconst ProviderError = Schema.Struct({ _tag: Schema.optional(Schema.String), raw: Schema.Unknown })\n\n// Provider errors keep their response body.\nconst failureMessage = (cause: Cause.Cause<unknown>): string =>\n Option.match(Schema.decodeUnknownOption(ProviderError)(Cause.squash(cause)), {\n onNone: () => Cause.pretty(cause),\n onSome: ({ _tag, raw }) => `${_tag ?? \"Error\"}: ${Predicate.isString(raw) ? raw : toJsonText(raw)}`\n })\n\nconst lastSeq = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, otherwise: number) => entries.at(-1)?.seq ?? otherwise\n\nconst toHistory = (\n viewed: ReadonlyArray<Assistant.Entry<any> | Prompt.Message>,\n app: AppEvents.AppEvents\n): ReadonlyArray<Prompt.Message> => {\n const out: Array<Prompt.Message> = []\n let run: Array<AssistantEvent.AnyEntry> = []\n\n const flush = () => {\n out.push(...History.fromEntries(run, (event) => AppEvents.read(app, event)))\n run = []\n }\n\n for (const item of viewed) {\n if (isEntry(item)) run.push(item)\n else {\n flush()\n out.push(item)\n }\n }\n\n flush()\n\n return out\n}\n\nconst isEntry = (item: Assistant.Entry<any> | Prompt.Message): item is Assistant.Entry<any> =>\n Predicate.hasProperty(item, \"seq\")\n\n// The handler's stream can end between a step's output and its tools, or while they run. An interrupted turn (a\n// shutdown) leaves its calls open instead: the next turn runs them again.\nconst closeOpenCalls = Effect.fnUntraced(function* (chat: Writer, startSeq: number) {\n const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq)\n\n const started = new Set(\n entries.flatMap(({ event }) => (Predicate.isTagged(event, \"ToolStarted\") ? [event.callId] : []))\n )\n\n // Approved calls this turn started that have no result are cut off like any other; one not started yet waits.\n const all = yield* chat.entries\n const approved = Decisions.approvedCalls(all).filter((call) => started.has(call.id))\n const open = [...History.unansweredCalls(History.fromEntries(entries, () => undefined)), ...approved]\n\n if (open.length === 0) return\n\n yield* chat.append(\n open.map((call) =>\n AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n outcome: \"failure\",\n ...(started.has(call.id)\n ? { result: History.mayHaveRunOutput, reason: \"MayHaveRun\" }\n : { result: History.notRunOutput, reason: \"NotRun\" })\n })\n )\n )\n})\n\n// The inputs before the turn's `TurnStarted` (at `startSeq`) woke it; past that, what its model outputs record\n// reading.\nconst handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, startSeq: number) =>\n entries.reduce(\n (through, { seq, event }) =>\n seq > startSeq &&\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"ModelOutput\") &&\n event.seenThroughSeq !== undefined\n ? Math.max(through, event.seenThroughSeq)\n : through,\n startSeq\n )\n\n// Fails visibly when the user's latest input got no reply; an input that arrived after what its model read gets the\n// next turn, which replies.\nconst finishTurn = Effect.fnUntraced(function* (chat: Writer, read: number, wakes: ReadonlySet<string>) {\n const entries = yield* chat.entries\n\n const end =\n History.owesReply(entries, read) && !History.unreadAfter(entries, read, wakes)\n ? AssistantEvent.TurnFailed.make({ throughSeq: read, message: silentTurnMessage })\n : AssistantEvent.TurnCompleted.make({ throughSeq: read })\n\n yield* chat.append([end])\n})\n\n// Everything stored so far counts as read, so a failing input isn't retried forever.\nconst failTurn = Effect.fnUntraced(function* (chat: Writer, cause: Cause.Cause<unknown>) {\n yield* Effect.logError(\"assistant turn failed\", cause)\n\n const last = lastSeq(yield* chat.entries, 0)\n\n yield* chat.append([AssistantEvent.TurnFailed.make({ throughSeq: last, message: failureMessage(cause) })])\n})\n\nconst makeTurnApi = (\n registration: Registration,\n chat: Writer,\n startSeq: number,\n checkOpen: Effect.Effect<void>\n): Assistant.Turn<any> => {\n const { definition, builtins } = registration\n const { app } = definition\n\n // With how far into the chat it goes: the step records it on the model's output.\n // Read before every model call: a chat the app deleted meanwhile stops here.\n const history = Effect.fnUntraced(function* (view: Assistant.HistoryView<any> = identity) {\n yield* checkOpen\n\n const all = yield* chat.entries\n\n const read: AssistantLoop.ChatHistory = {\n messages: toHistory(view(AppEvents.decodeEntries(app, all)), app),\n throughSeq: lastSeq(all, startSeq)\n }\n\n return read\n })\n\n const instructions = (given: string | Instructions.Resolved) =>\n mapText(given, (text) => `${Instructions.protocol}\\n\\n${text}`)\n\n // The loop's own prompt and tools, so the prompt stays cached, with the nudge at the end.\n const replyPass = <R>(options: {\n readonly instructions: Instructions.Resolved\n readonly toolkit: Toolkits.Tools<R>\n readonly view: Assistant.HistoryView<any>\n readonly nudge: string | undefined\n }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const all = yield* chat.entries\n const through = handledThrough(all, startSeq)\n\n // Something arrived after what the loop's model read: the next turn reads it with the full loop, and replies.\n if (History.unreadAfter(all, through, app.wakes)) return Stream.empty\n\n const owed = History.owesReply(all, through)\n const undelivered = !owed && History.owesDelivery(all, through)\n\n if (!owed && !undelivered) return Stream.empty\n\n const nudge = undelivered ? deliveryNudge : (options.nudge ?? defaultReplyNudge)\n\n return Loop.run({\n instructions: options.instructions,\n // A reply that's owed can only be sent; a result it may have given may also be for nobody.\n toolkit: Toolkits.runOnly(\n options.toolkit,\n owed ? [Tools.sendUserMessageName] : [Tools.sendUserMessageName, Tools.waitToolName],\n \"Not now: reply to the user with send_user_message.\"\n ),\n history: Effect.gen(function* () {\n yield* checkOpen\n\n const entries = yield* chat.entries\n\n return {\n messages: [\n ...toHistory(options.view(AppEvents.decodeEntries(app, entries)), app),\n History.userText(nudge)\n ],\n throughSeq: lastSeq(entries, startSeq)\n }\n }),\n // A second step, for a reply after a call it was refused.\n maxSteps: 2\n })\n })\n )\n\n const replyIfOwed = (options: Assistant.ReplyOptions) =>\n replyPass({\n instructions: instructions(options.instructions),\n toolkit: builtins,\n view: identity,\n nudge: options.nudge\n })\n\n const prepare = <T extends Record<string, Tool.Any>, RS>(options: Assistant.LoopOptions<T, RS, any>) => {\n const skills = options.skills ?? []\n\n return {\n system: mapText(instructions(options.instructions), (text) => Skill.withCatalog(text, skills)),\n toolkit: Toolkits.merge(\n Toolkits.merge(builtins, Skills.toTools(skills)),\n Toolkits.fromToolkitOrEmpty(options.toolkit)\n ),\n view: options.history ?? identity\n }\n }\n\n return {\n chatId: chat.chatId,\n history,\n instructions,\n replyIfOwed,\n loop: (options) => {\n const { system, toolkit, view } = prepare(options)\n const twice = Toolkits.duplicateNames(toolkit)\n\n const deciding = toolkit.definitions.filter(\n (tool) => tool.needsApproval !== undefined && tool.needsApproval !== false\n )\n\n const loop =\n twice.length > 0\n ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(\", \")}`)\n : deciding.length > 0 && definition.blocks?.byKind.get(Decision.kind) === undefined\n ? Stream.die(\n `${deciding.map((tool) => tool.name).join(\", \")} can wait for the user's decision: add Decision.block to the assistant's blocks.`\n )\n : Loop.run({\n instructions: system,\n toolkit,\n history: history(view),\n maxSteps: options.maxSteps ?? 16\n })\n\n return Stream.concat(loop, replyPass({ instructions: system, toolkit, view, nudge: options.replyNudge }))\n }\n }\n}\n\n// Every event the handler's loop emits is recorded before the loop is pulled again.\n/** @internal */\nexport const run = Effect.fnUntraced(\n function* (options: {\n readonly registration: Registration\n readonly handler: TurnHandler\n readonly chat: Writer\n readonly services: Context.Context<Assistant.TurnServices | LanguageModel.LanguageModel>\n // A chat the app deleted is deleted here, and the turn stops.\n readonly checkOpen: Effect.Effect<void>\n }) {\n const { chat } = options\n const before = yield* chat.entries\n\n yield* Telemetry.agentInput(History.unhandledInputs(before, options.registration.definition.app.wakes))\n\n const assistant = options.registration.definition.name\n const traceId = yield* Telemetry.currentTraceId\n\n const started = yield* chat.append([\n AssistantEvent.TurnStarted.make(\n Option.match(traceId, {\n onNone: () => ({ assistant }),\n onSome: (id) => ({ assistant, traceId: id })\n })\n )\n ])\n\n const startSeq = lastSeq(started, 0)\n const turn = makeTurnApi(options.registration, chat, startSeq, options.checkOpen)\n\n const record = (event: AssistantLoop.Event) => chat.append([event])\n\n yield* options.handler(turn).pipe(\n Stream.runForEach(record),\n Effect.onExit((exit) => (Exit.hasInterrupts(exit) ? Effect.void : closeOpenCalls(chat, startSeq))),\n // A loop the app writes gets the assistant's own tools too, with this turn's services.\n Effect.provideService(\n Loop.TurnTools,\n Option.some(Toolkits.provide(options.registration.builtins, options.services))\n ),\n Effect.provideContext(options.services),\n Effect.matchCauseEffect({\n onSuccess: Effect.fnUntraced(function* () {\n const all = yield* chat.entries\n\n yield* finishTurn(chat, handledThrough(all, startSeq), options.registration.definition.app.wakes)\n }),\n onFailure: (cause) => failTurn(chat, cause)\n })\n )\n\n // The trace's output is what the user saw this turn, and a failure if any.\n const shown = (yield* chat.entries).flatMap(({ event, seq }) =>\n seq > startSeq && (Predicate.isTagged(event, \"AssistantMessage\") || Predicate.isTagged(event, \"TurnFailed\"))\n ? [event]\n : []\n )\n\n yield* Telemetry.agentOutput(shown)\n },\n (effect, options) =>\n effect.pipe(\n Telemetry.agentSpan(options.registration.definition.name, {\n chatId: options.chat.chatId,\n root: true\n })\n )\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;;AAGjC,MAAa,oBACX;;AAGF,MAAa,gBACX;;AAsCF,MAAa,WAAW,OAAO,WAAW,WACxC,YACA,SACA;CACA,MAAM,QAAQ,OAAO,OAAO,QAAqC;CAEjE,MAAM,gBAAgB,WAAW,QAAQ,OAAO,IAAIA,IAAa;CAE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C,CAAC,CACH;CAGA,MAAM,SAAS,OAAO,KAAK,QAAA,CAAS,SAAS,EAAE,OAAO,UACpD,MAAM,aAAa,UAAU,SAAS,OAAO,kBAAkB,KAAK,UAAU,SAAS,OAAO,YAAY,KACtG,CAAC,KAAK,IACN,CAAC,CACP;CAEA,OAAOC,YAAsB,KAAK;AACpC,IACC,QAAQ,YACP,OAAO,KACLC,UAAoB,QAAQ,aAAa,WAAW,MAAM;CACxD,QAAQ,QAAQ,KAAK;CACrB,MAAM;AACR,CAAC,CACH,CACJ"}
1
+ {"version":3,"file":"turns.js","names":["Toolkits.merge","Tools.makeMessaging","Specialists.toolkit","History.fromEntries","AppEvents.read","History.unansweredCalls","History.mayHaveRunOutput","History.notRunOutput","AssistantEvent.isLibraryEvent","History.owesReply","History.unreadAfter","AppEvents.decodeEntries","Instructions.protocol","History.owesDelivery","Loop.run","Toolkits.runOnly","Tools.sendUserMessageName","Tools.waitToolName","History.userText","Skill.withCatalog","Skills.toTools","Toolkits.fromToolkitOrEmpty","Toolkits.duplicateNames","Telemetry.agentInput","History.unhandledInputs","Telemetry.currentTraceId","Loop.TurnTools","Toolkits.provide","Telemetry.agentOutput","Telemetry.agentSpan"],"sources":["../../src/internal/turns.ts"],"sourcesContent":["import type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"../Assistant.ts\"\nimport type { ChatId } from \"../ChatId.ts\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as AssistantLoop from \"../AssistantLoop.ts\"\nimport * as Loop from \"./loop.ts\"\nimport type * as BlockKit from \"../BlockKit.ts\"\nimport type { CurrentChat } from \"../CurrentChat.ts\"\nimport * as Instructions from \"../Instructions.ts\"\nimport * as Skill from \"../Skill.ts\"\nimport * as Skills from \"./skills.ts\"\nimport type * as Specialist from \"../Specialist.ts\"\nimport * as AppEvents from \"./events.ts\"\nimport * as History from \"./history.ts\"\nimport { mapText } from \"./instructions.ts\"\nimport { toJsonText } from \"./schema.ts\"\nimport * as Specialists from \"./specialists.ts\"\nimport * as Telemetry from \"./telemetry.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport type { Writer } from \"./writer.ts\"\nimport * as Tools from \"./tools.ts\"\n\n/** @internal */\nexport const silentTurnMessage = \"I finished without sending a reply.\"\n\n/** @internal */\nexport const defaultReplyNudge =\n \"You haven't replied to the user's latest message yet. Reply now with send_user_message.\"\n\n/** @internal */\nexport const deliveryNudge =\n \"You told the user you're on it, but stopped without giving them the result. Send it now with send_user_message; if part of it is still running, say what and that you'll report back. If they already have everything, call wait.\"\n\n/** @internal */\nexport interface Definition {\n readonly name: string\n readonly blocks: BlockKit.BlockKit | undefined\n readonly specialists: ReadonlyArray<Specialist.Any>\n readonly app: AppEvents.AppEvents\n}\n\n// Once its build ran the layer's services are provided, so its streams need only what a turn provides.\n/** @internal */\nexport type TurnHandler = (\n turn: Assistant.Turn<any>\n) => Stream.Stream<AssistantLoop.Event, unknown, Assistant.TurnServices | LanguageModel.LanguageModel>\n\n// The chat `CurrentChat` gives, with its entries typed as the assistant's decode returns them: the assistant's typed\n// chat is this one, so it needs no check of its own.\n/** @internal */\nexport interface TypedChat {\n readonly chatId: ChatId\n readonly entries: Effect.Effect<AppEvents.DecodedEntries>\n readonly append: CurrentChat[\"Service\"][\"append\"]\n}\n\n/** @internal */\nexport interface Registration {\n readonly definition: Definition\n readonly model: Context.Context<LanguageModel.LanguageModel>\n readonly open: (chat: TypedChat) => Effect.Effect<TurnHandler, never, Scope.Scope | CurrentChat>\n readonly specialists: ReadonlyArray<{\n readonly specialist: Specialist.Any\n readonly built: Specialist.Built\n }>\n readonly builtins: Toolkits.Tools<Assistant.TurnServices>\n}\n\n/** @internal */\nexport const register = Effect.fnUntraced(function* (\n definition: Definition,\n options: { readonly open: Registration[\"open\"] }\n) {\n const model = yield* Effect.context<LanguageModel.LanguageModel>()\n\n const specialists = yield* Effect.forEach(\n definition.specialists,\n Effect.fnUntraced(function* (specialist) {\n const built = yield* Effect.serviceOption(specialist.Handler)\n\n if (Option.isNone(built)) {\n return yield* Effect.die(\n `No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`\n )\n }\n\n return { specialist, built: built.value }\n })\n )\n\n const builtins = Toolkits.merge(\n yield* Tools.makeMessaging(definition.blocks),\n yield* Specialists.toolkit(definition.specialists)\n )\n\n const registration: Registration = {\n definition,\n model,\n open: options.open,\n specialists,\n builtins\n }\n\n return registration\n})\n\nconst ProviderError = Schema.Struct({ _tag: Schema.optional(Schema.String), raw: Schema.Unknown })\n\n// Provider errors keep their response body.\nconst failureMessage = (cause: Cause.Cause<unknown>): string =>\n Option.match(Schema.decodeUnknownOption(ProviderError)(Cause.squash(cause)), {\n onNone: () => Cause.pretty(cause),\n onSome: ({ _tag, raw }) => `${_tag ?? \"Error\"}: ${Predicate.isString(raw) ? raw : toJsonText(raw)}`\n })\n\nconst lastSeq = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, otherwise: number) => entries.at(-1)?.seq ?? otherwise\n\nconst toHistory = (\n viewed: ReadonlyArray<Assistant.Entry<any> | Prompt.Message>,\n app: AppEvents.AppEvents\n): ReadonlyArray<Prompt.Message> => {\n const out: Array<Prompt.Message> = []\n let run: Array<AssistantEvent.AnyEntry> = []\n\n const flush = () => {\n out.push(...History.fromEntries(run, (event) => AppEvents.read(app, event)))\n run = []\n }\n\n for (const item of viewed) {\n if (isEntry(item)) run.push(item)\n else {\n flush()\n out.push(item)\n }\n }\n\n flush()\n\n return out\n}\n\nconst isEntry = (item: Assistant.Entry<any> | Prompt.Message): item is Assistant.Entry<any> =>\n Predicate.hasProperty(item, \"seq\")\n\n// The handler's stream can end between a step's output and its tools, or while they run. An interrupted turn (a\n// shutdown) leaves its calls open instead: the next turn runs them again.\nconst closeOpenCalls = Effect.fnUntraced(function* (chat: Writer, startSeq: number) {\n const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq)\n\n const started = new Set(\n entries.flatMap(({ event }) => (Predicate.isTagged(event, \"ToolStarted\") ? [event.callId] : []))\n )\n\n const open = History.unansweredCalls(History.fromEntries(entries, () => undefined))\n\n if (open.length === 0) return\n\n yield* chat.append(\n open.map((call) =>\n AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n outcome: \"failure\",\n ...(started.has(call.id)\n ? { result: History.mayHaveRunOutput, reason: \"MayHaveRun\" }\n : { result: History.notRunOutput, reason: \"NotRun\" })\n })\n )\n )\n})\n\n// The inputs before the turn's `TurnStarted` (at `startSeq`) woke it; past that, what its model outputs record\n// reading.\nconst handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, startSeq: number) =>\n entries.reduce(\n (through, { seq, event }) =>\n seq > startSeq &&\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"ModelOutput\") &&\n event.seenThroughSeq !== undefined\n ? Math.max(through, event.seenThroughSeq)\n : through,\n startSeq\n )\n\n// Fails visibly when the user's latest input got no reply; an input that arrived after what its model read gets the\n// next turn, which replies.\nconst finishTurn = Effect.fnUntraced(function* (chat: Writer, read: number, wakes: ReadonlySet<string>) {\n const entries = yield* chat.entries\n\n const end =\n History.owesReply(entries, read) && !History.unreadAfter(entries, read, wakes)\n ? AssistantEvent.TurnFailed.make({ throughSeq: read, message: silentTurnMessage })\n : AssistantEvent.TurnCompleted.make({ throughSeq: read })\n\n yield* chat.append([end])\n})\n\n// Everything stored so far counts as read, so a failing input isn't retried forever.\nconst failTurn = Effect.fnUntraced(function* (chat: Writer, cause: Cause.Cause<unknown>) {\n yield* Effect.logError(\"assistant turn failed\", cause)\n\n const last = lastSeq(yield* chat.entries, 0)\n\n yield* chat.append([AssistantEvent.TurnFailed.make({ throughSeq: last, message: failureMessage(cause) })])\n})\n\nconst makeTurnApi = (\n registration: Registration,\n chat: Writer,\n startSeq: number,\n checkOpen: Effect.Effect<void>\n): Assistant.Turn<any> => {\n const { definition, builtins } = registration\n const { app } = definition\n\n // With how far into the chat it goes: the step records it on the model's output.\n // Read before every model call: a chat the app deleted meanwhile stops here.\n const history = Effect.fnUntraced(function* (view: Assistant.HistoryView<any> = identity) {\n yield* checkOpen\n\n const all = yield* chat.entries\n\n const read: AssistantLoop.ChatHistory = {\n messages: toHistory(view(AppEvents.decodeEntries(app, all)), app),\n throughSeq: lastSeq(all, startSeq)\n }\n\n return read\n })\n\n const instructions = (given: string | Instructions.Resolved) =>\n mapText(given, (text) => `${Instructions.protocol}\\n\\n${text}`)\n\n // The loop's own prompt and tools, so the prompt stays cached, with the nudge at the end.\n const replyPass = <R>(options: {\n readonly instructions: Instructions.Resolved\n readonly toolkit: Toolkits.Tools<R>\n readonly view: Assistant.HistoryView<any>\n readonly nudge: string | undefined\n }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const all = yield* chat.entries\n const through = handledThrough(all, startSeq)\n\n // Something arrived after what the loop's model read: the next turn reads it with the full loop, and replies.\n if (History.unreadAfter(all, through, app.wakes)) return Stream.empty\n\n const owed = History.owesReply(all, through)\n const undelivered = !owed && History.owesDelivery(all, through)\n\n if (!owed && !undelivered) return Stream.empty\n\n const nudge = undelivered ? deliveryNudge : (options.nudge ?? defaultReplyNudge)\n\n return Loop.run({\n instructions: options.instructions,\n // A reply that's owed can only be sent; a result it may have given may also be for nobody.\n toolkit: Toolkits.runOnly(\n options.toolkit,\n owed ? [Tools.sendUserMessageName] : [Tools.sendUserMessageName, Tools.waitToolName],\n \"Not now: reply to the user with send_user_message.\"\n ),\n history: Effect.gen(function* () {\n yield* checkOpen\n\n const entries = yield* chat.entries\n\n return {\n messages: [\n ...toHistory(options.view(AppEvents.decodeEntries(app, entries)), app),\n History.userText(nudge)\n ],\n throughSeq: lastSeq(entries, startSeq)\n }\n }),\n // A second step, for a reply after a call it was refused.\n maxSteps: 2\n })\n })\n )\n\n const replyIfOwed = (options: Assistant.ReplyOptions) =>\n replyPass({\n instructions: instructions(options.instructions),\n toolkit: builtins,\n view: identity,\n nudge: options.nudge\n })\n\n const prepare = <T extends Record<string, Tool.Any>, RS>(options: Assistant.LoopOptions<T, RS, any>) => {\n const skills = options.skills ?? []\n\n return {\n system: mapText(instructions(options.instructions), (text) => Skill.withCatalog(text, skills)),\n toolkit: Toolkits.merge(\n Toolkits.merge(builtins, Skills.toTools(skills)),\n Toolkits.fromToolkitOrEmpty(options.toolkit)\n ),\n view: options.history ?? identity\n }\n }\n\n return {\n chatId: chat.chatId,\n history,\n instructions,\n replyIfOwed,\n loop: (options) => {\n const { system, toolkit, view } = prepare(options)\n const twice = Toolkits.duplicateNames(toolkit)\n\n const loop =\n twice.length > 0\n ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(\", \")}`)\n : Loop.run({\n instructions: system,\n toolkit,\n history: history(view),\n maxSteps: options.maxSteps ?? 16\n })\n\n return Stream.concat(loop, replyPass({ instructions: system, toolkit, view, nudge: options.replyNudge }))\n }\n }\n}\n\n// Every event the handler's loop emits is recorded before the loop is pulled again.\n/** @internal */\nexport const run = Effect.fnUntraced(\n function* (options: {\n readonly registration: Registration\n readonly handler: TurnHandler\n readonly chat: Writer\n readonly services: Context.Context<Assistant.TurnServices | LanguageModel.LanguageModel>\n // A chat the app deleted is deleted here, and the turn stops.\n readonly checkOpen: Effect.Effect<void>\n }) {\n const { chat } = options\n const before = yield* chat.entries\n\n yield* Telemetry.agentInput(History.unhandledInputs(before, options.registration.definition.app.wakes))\n\n const assistant = options.registration.definition.name\n const traceId = yield* Telemetry.currentTraceId\n\n const started = yield* chat.append([\n AssistantEvent.TurnStarted.make(\n Option.match(traceId, {\n onNone: () => ({ assistant }),\n onSome: (id) => ({ assistant, traceId: id })\n })\n )\n ])\n\n const startSeq = lastSeq(started, 0)\n const turn = makeTurnApi(options.registration, chat, startSeq, options.checkOpen)\n\n const record = (event: AssistantLoop.Event) => chat.append([event])\n\n yield* options.handler(turn).pipe(\n Stream.runForEach(record),\n Effect.onExit((exit) => (Exit.hasInterrupts(exit) ? Effect.void : closeOpenCalls(chat, startSeq))),\n // A loop the app writes gets the assistant's own tools too, with this turn's services.\n Effect.provideService(\n Loop.TurnTools,\n Option.some(Toolkits.provide(options.registration.builtins, options.services))\n ),\n Effect.provideContext(options.services),\n Effect.matchCauseEffect({\n onSuccess: Effect.fnUntraced(function* () {\n const all = yield* chat.entries\n\n yield* finishTurn(chat, handledThrough(all, startSeq), options.registration.definition.app.wakes)\n }),\n onFailure: (cause) => failTurn(chat, cause)\n })\n )\n\n // The trace's output is what the user saw this turn, and a failure if any.\n const shown = (yield* chat.entries).flatMap(({ event, seq }) =>\n seq > startSeq && (Predicate.isTagged(event, \"AssistantMessage\") || Predicate.isTagged(event, \"TurnFailed\"))\n ? [event]\n : []\n )\n\n yield* Telemetry.agentOutput(shown)\n },\n (effect, options) =>\n effect.pipe(\n Telemetry.agentSpan(options.registration.definition.name, {\n chatId: options.chat.chatId,\n root: true\n })\n )\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,oBAAoB;;AAGjC,MAAa,oBACX;;AAGF,MAAa,gBACX;;AAsCF,MAAa,WAAW,OAAO,WAAW,WACxC,YACA,SACA;CACA,MAAM,QAAQ,OAAO,OAAO,QAAqC;CAEjE,MAAM,cAAc,OAAO,OAAO,QAChC,WAAW,aACX,OAAO,WAAW,WAAW,YAAY;EACvC,MAAM,QAAQ,OAAO,OAAO,cAAc,WAAW,OAAO;EAE5D,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,OAAO,OAAO,IACnB,sBAAsB,WAAW,KAAK,uBAAuB,WAAW,KAAK,UAC/E;EAGF,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C,KAAK,CAAC;CAElE,OAAO,QAAQ,QAAQ,IAAI,CAAC,CAAC,KAC3B,OAAO,WAAW,MAAM,GACxB,OAAO,QAAQ,SAAU,KAAK,cAAc,IAAI,IAAI,OAAO,OAAO,eAAe,MAAM,QAAQ,CAAE,GAEjG,OAAO,eACLC,WACA,OAAO,KAAKC,QAAiB,QAAQ,aAAa,UAAU,QAAQ,QAAQ,CAAC,CAC/E,GACA,OAAO,eAAe,QAAQ,QAAQ,GACtC,OAAO,iBAAiB;EACtB,WAAW,OAAO,WAAW,aAAa;GACxC,MAAM,MAAM,OAAO,KAAK;GAExB,OAAO,WAAW,MAAM,eAAe,KAAK,QAAQ,GAAG,QAAQ,aAAa,WAAW,IAAI,KAAK;EAClG,CAAC;EACD,YAAY,UAAU,SAAS,MAAM,KAAK;CAC5C,CAAC,CACH;CAGA,MAAM,SAAS,OAAO,KAAK,QAAA,CAAS,SAAS,EAAE,OAAO,UACpD,MAAM,aAAa,UAAU,SAAS,OAAO,kBAAkB,KAAK,UAAU,SAAS,OAAO,YAAY,KACtG,CAAC,KAAK,IACN,CAAC,CACP;CAEA,OAAOC,YAAsB,KAAK;AACpC,IACC,QAAQ,YACP,OAAO,KACLC,UAAoB,QAAQ,aAAa,WAAW,MAAM;CACxD,QAAQ,QAAQ,KAAK;CACrB,MAAM;AACR,CAAC,CACH,CACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-assistant",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A colleague assistant on Effect: an append-only event log per chat, an interruptible agent loop, specialists, skills, and UI blocks",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -50,5 +50,6 @@
50
50
  "build": "vp pack",
51
51
  "test": "vp test run --exclude test/contract.test.ts",
52
52
  "test:contract": "vp test run test/contract.test.ts"
53
- }
53
+ },
54
+ "types": "./dist/index.d.ts"
54
55
  }
@@ -12,7 +12,6 @@ import * as Response from "effect/ai/Response"
12
12
  import * as Predicate from "effect/Predicate"
13
13
  import * as Schema from "effect/Schema"
14
14
  import { ChatId } from "./ChatId.ts"
15
- import { DecisionId } from "./DecisionId.ts"
16
15
  import { InputId, make as makeInputId } from "./InputId.ts"
17
16
  import { RunId } from "./RunId.ts"
18
17
 
@@ -139,69 +138,6 @@ export class SpecialistFinished extends Schema.TaggedClass<SpecialistFinished>()
139
138
  error: Schema.optional(Schema.String)
140
139
  }) {}
141
140
 
142
- /**
143
- * Schema for how the user decided, either `"approved"` or `"declined"`.
144
- *
145
- * @category schemas
146
- * @since 0.1.0
147
- */
148
- export const DecisionOutcome = Schema.Literals(["approved", "declined"])
149
-
150
- /**
151
- * Represents how the user decided.
152
- *
153
- * @category models
154
- * @since 0.1.0
155
- */
156
- export type DecisionOutcome = typeof DecisionOutcome.Type
157
-
158
- /**
159
- * Schema for the origin of a decision that a tool call waits for.
160
- *
161
- * It holds the call as the model wrote it. Approving the decision runs exactly this call.
162
- *
163
- * @category schemas
164
- * @since 0.1.0
165
- */
166
- export const CallOrigin = Schema.TaggedStruct("Call", {
167
- callId: Schema.String,
168
- tool: Schema.String,
169
- params: Schema.Json
170
- })
171
-
172
- /**
173
- * Represents the origin of a decision that a tool call waits for.
174
- *
175
- * @category models
176
- * @since 0.1.0
177
- */
178
- export type CallOrigin = typeof CallOrigin.Type
179
-
180
- /**
181
- * Represents a request for the user to decide something, by approving or declining it.
182
- *
183
- * @category schemas
184
- * @since 0.1.0
185
- */
186
- export class DecisionRequested extends Schema.TaggedClass<DecisionRequested>()("DecisionRequested", {
187
- id: DecisionId,
188
- origin: CallOrigin
189
- }) {}
190
-
191
- /**
192
- * Represents a decision the user made by answering a decision block for it.
193
- *
194
- * `answer` is the id of that `BlockAnswer`. An approved call runs at the turn's next step.
195
- *
196
- * @category schemas
197
- * @since 0.1.0
198
- */
199
- export class DecisionResolved extends Schema.TaggedClass<DecisionResolved>()("DecisionResolved", {
200
- id: DecisionId,
201
- outcome: DecisionOutcome,
202
- answer: InputId
203
- }) {}
204
-
205
141
  /**
206
142
  * Schema for every input `Assistant.submit` accepts.
207
143
  *
@@ -481,8 +417,6 @@ export const AssistantEvent = Schema.Union([
481
417
  SpecialistStarted,
482
418
  SpecialistFinished,
483
419
  BlocksClosed,
484
- DecisionRequested,
485
- DecisionResolved,
486
420
  ChatDeleted
487
421
  ])
488
422
 
@@ -27,8 +27,7 @@ import * as Toolkits from "./internal/toolkit.ts"
27
27
  * Represents what the loop emits.
28
28
  *
29
29
  * For each model call, the loop emits the call's output. Then, for each of its tool calls, it
30
- * emits a `ToolStarted` before the call runs and the call's result, or a `DecisionRequested` for
31
- * a call that waits for the user's decision.
30
+ * emits a `ToolStarted` before the call runs and the call's result.
32
31
  *
33
32
  * @category models
34
33
  * @since 0.1.0
@@ -158,9 +157,12 @@ const toolsOf = <T extends Record<string, Tool.Any>>(toolkit: Toolkit.Toolkit<T>
158
157
  * **Details**
159
158
  *
160
159
  * The step calls the model with the current history and emits its `ModelOutput`. It then runs
161
- * the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each, or a
162
- * `DecisionRequested` for a call that waits for the user's decision. `then` receives the step's
163
- * result and decides what comes next, with `AssistantLoop.next(state)` or `AssistantLoop.stop()`.
160
+ * the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each. `then` receives
161
+ * the step's result and decides what comes next, with `AssistantLoop.next(state)` or
162
+ * `AssistantLoop.stop()`.
163
+ *
164
+ * A tool with Effect's `needsApproval` set fails the loop before the model is called: the
165
+ * library doesn't run calls that wait for approval (see the guide on involving the user).
164
166
  *
165
167
  * @category constructors
166
168
  * @since 0.1.0
package/src/Block.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Defines UI blocks that an assistant can put in a message.
3
3
  *
4
4
  * A block is a bit of UI for when a structured answer is easier than typing, such as options to
5
- * pick from, approve and deny buttons, or a small input. The assistant fills in its `props`, and
5
+ * pick from, a yes or no, or a small input. The assistant fills in its `props`, and
6
6
  * using the block sends back a value typed by its `answer` schema.
7
7
  *
8
8
  * @since 0.1.0
package/src/BlockKit.ts CHANGED
@@ -16,7 +16,6 @@ import * as AssistantEvent from "./AssistantEvent.ts"
16
16
  import type * as Block from "./Block.ts"
17
17
  import type * as ChatView from "./ChatView.ts"
18
18
  import { CurrentChat } from "./CurrentChat.ts"
19
- import * as Decision from "./Decision.ts"
20
19
  import * as InputId from "./InputId.ts"
21
20
 
22
21
  /**
@@ -118,8 +117,7 @@ export const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Re
118
117
  *
119
118
  * **Details**
120
119
  *
121
- * These are the blocks {@link closeStale} closes. Decision blocks never go stale, since work waits
122
- * on them and closing one would leave it waiting.
120
+ * These are the blocks {@link closeStale} closes.
123
121
  *
124
122
  * @category utils
125
123
  * @since 0.1.0
@@ -136,15 +134,7 @@ export const staleBlocks = (
136
134
  AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, "AssistantMessage") && event.id === id
137
135
  )
138
136
 
139
- const message = entries[shown]?.event
140
-
141
- if (
142
- message === undefined ||
143
- (AssistantEvent.isLibraryEvent(message) &&
144
- Predicate.isTagged(message, "AssistantMessage") &&
145
- message.block?.kind === Decision.kind)
146
- )
147
- return false
137
+ if (shown === -1) return false
148
138
 
149
139
  const typed = entries.slice(shown + 1).filter(({ event }) => Predicate.isTagged(event, "UserMessage")).length
150
140
 
@@ -180,6 +170,11 @@ export const closeStale = Effect.fn(function* (options: { readonly messages: num
180
170
  * @since 0.1.0
181
171
  */
182
172
  export interface RenderArgs<B> {
173
+ /**
174
+ * The id of the message the block is on. A block whose button calls your API can key the work
175
+ * on it, with the chat's id, so the work runs once per block.
176
+ */
177
+ readonly messageId: string
183
178
  readonly text: string
184
179
  readonly props: PropsOf<B>
185
180
  /**
@@ -189,11 +184,6 @@ export interface RenderArgs<B> {
189
184
  readonly open: boolean
190
185
  /** The user's answer, if they used the block. */
191
186
  readonly answer: AnswerOf<B> | undefined
192
- /**
193
- * For the decision block, the call each decision is for (its tool and params) and how it was
194
- * decided. Empty for other blocks.
195
- */
196
- readonly decisions: ReadonlyArray<ChatView.PendingDecision>
197
187
  /** Sends an answer. Only call it while `open`. */
198
188
  readonly respond: (answer: AnswerOf<B>) => void
199
189
  }
@@ -235,10 +225,10 @@ export interface RenderOptions {
235
225
  * **Example** (Rendering blocks with React)
236
226
  *
237
227
  * ```tsx
238
- * import { BlockKit, Decision } from "effect-assistant"
228
+ * import { BlockKit } from "effect-assistant"
239
229
  * import type { ReactNode } from "react"
240
230
  *
241
- * const Blocks = BlockKit.make([PickOne, Decision.block])
231
+ * const Blocks = BlockKit.make([PickOne, OrderDraft])
242
232
  *
243
233
  * const renderBlock = BlockKit.toClient<typeof Blocks, ReactNode>(Blocks, {
244
234
  * pick_one: ({ props, open, respond }) =>
@@ -247,11 +237,8 @@ export interface RenderOptions {
247
237
  * {option}
248
238
  * </button>
249
239
  * )),
250
- * decision: ({ props, open, respond }) => (
251
- * <button disabled={!open} onClick={() => respond(Decision.answerAll(props, "approved"))}>
252
- * {props.approveLabel ?? "Approve"}
253
- * </button>
254
- * )
240
+ * // No answer schema: the button calls the app's own API with the props the user sees.
241
+ * order_draft: ({ props }) => <button onClick={() => placeOrder(props)}>Place order</button>
255
242
  * })
256
243
  *
257
244
  * // For each AssistantMessage in the chat's view:
@@ -291,11 +278,11 @@ export function toClient<Out>(
291
278
  given === undefined || answerCodec === undefined ? Option.none() : Schema.decodeUnknownOption(answerCodec)(given)
292
279
 
293
280
  return render({
281
+ messageId: message.id,
294
282
  text: message.text,
295
283
  props: props.value,
296
284
  open: message.block.status === "open",
297
285
  answer: Option.getOrUndefined(answer),
298
- decisions: message.block.decisions ?? [],
299
286
  respond: (value) =>
300
287
  options.respond(
301
288
  AssistantEvent.BlockAnswer.make({