effect-assistant 0.13.2 → 0.15.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 (47) hide show
  1. package/dist/Assistant.d.ts +5 -4
  2. package/dist/Assistant.d.ts.map +1 -1
  3. package/dist/Assistant.js +2 -2
  4. package/dist/Assistant.js.map +1 -1
  5. package/dist/AssistantActivity.d.ts +5 -4
  6. package/dist/AssistantActivity.d.ts.map +1 -1
  7. package/dist/AssistantActivity.js +0 -11
  8. package/dist/AssistantActivity.js.map +1 -1
  9. package/dist/AssistantEngine.d.ts +2 -2
  10. package/dist/AssistantEngine.d.ts.map +1 -1
  11. package/dist/AssistantEngine.js +8 -8
  12. package/dist/AssistantEngine.js.map +1 -1
  13. package/dist/AssistantEvent.d.ts +5 -4
  14. package/dist/AssistantEvent.d.ts.map +1 -1
  15. package/dist/AssistantEvent.js +3 -3
  16. package/dist/AssistantEvent.js.map +1 -1
  17. package/dist/ChatLog.js +4 -4
  18. package/dist/ChatLog.js.map +1 -1
  19. package/dist/ChatSignal.js +1 -1
  20. package/dist/ChatSignal.js.map +1 -1
  21. package/dist/Memory.d.ts +1 -1
  22. package/dist/Memory.js +2 -2
  23. package/dist/StatusSummary.d.ts +1 -1
  24. package/dist/StatusSummary.js +1 -1
  25. package/dist/Timeline.d.ts +21 -18
  26. package/dist/Timeline.d.ts.map +1 -1
  27. package/dist/Timeline.js +17 -15
  28. package/dist/Timeline.js.map +1 -1
  29. package/dist/ToolApproval.d.ts +3 -2
  30. package/dist/ToolApproval.d.ts.map +1 -1
  31. package/dist/ToolApproval.js +0 -13
  32. package/dist/ToolApproval.js.map +1 -1
  33. package/dist/internal/history.js +5 -3
  34. package/dist/internal/history.js.map +1 -1
  35. package/dist/internal/live.js +1 -1
  36. package/dist/internal/loop.js +1 -1
  37. package/dist/internal/summary.js +1 -1
  38. package/package.json +1 -1
  39. package/src/Assistant.ts +13 -9
  40. package/src/AssistantActivity.ts +5 -4
  41. package/src/AssistantEngine.ts +10 -10
  42. package/src/AssistantEvent.ts +5 -4
  43. package/src/ChatLog.ts +4 -4
  44. package/src/ChatSignal.ts +1 -1
  45. package/src/Timeline.ts +29 -21
  46. package/src/ToolApproval.ts +3 -2
  47. package/src/internal/history.ts +5 -3
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantEvent.js","names":["makeInputId"],"sources":["../src/AssistantEvent.ts"],"sourcesContent":["/**\n * Defines the events that can happen in a chat.\n *\n * A chat is an append-only log of these events, and the log is the source of truth. A chat client\n * receives the part of the log its user sees (its `Timeline`), and the model's history is rebuilt\n * from the log before every model call. Besides the library's events ({@link AssistantEvent}), a\n * log holds the application's own events ({@link StoredAppEvent}).\n *\n * @since 0.1.0\n */\nimport * as Response from \"effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as SchemaAST from \"effect/SchemaAST\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { InputId, make as makeInputId } from \"./InputId.ts\"\nimport { inputKey } from \"./internal/input.ts\"\nimport { RunId } from \"./RunId.ts\"\n\n/**\n * Schema for a file the user attached to a message, kept by reference.\n *\n * The file itself is stored elsewhere, so the log never holds its bytes.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Attachment = Schema.Struct({\n fileId: Schema.String.check(Schema.isMaxLength(64)),\n name: Schema.String.check(Schema.isMaxLength(255)),\n mediaType: Schema.String.check(Schema.isMaxLength(127)),\n /** In bytes. */\n size: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/**\n * The maximum number of files one message can carry.\n *\n * Each attached file is a line in every prompt after the message.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const maxAttachments = 10\n\n/**\n * Represents a file the user attached to a message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Attachment = typeof Attachment.Type\n\n/**\n * Formats a byte count for people and the model, such as `2.1 MB`.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const formatSize = (bytes: number): string =>\n bytes < 1024\n ? `${bytes} B`\n : bytes < 1024 * 1024\n ? `${(bytes / 1024).toFixed(1)} KB`\n : bytes < 1024 * 1024 * 1024\n ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n : `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n\n/**\n * Returns the line the model reads for an attachment.\n *\n * The line names the file and never holds its content.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const attachmentLine = (attachment: Attachment): string =>\n `[attached: ${attachment.name}, ${attachment.mediaType}, ${formatSize(attachment.size)}, id ${attachment.fileId}]`\n\n/**\n * Returns a message's text followed by a line for each attached file.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const textWithAttachments = (text: string, attachments: ReadonlyArray<Attachment> | undefined): string =>\n attachments === undefined || attachments.length === 0\n ? text\n : [text, ...attachments.map(attachmentLine)].filter((part) => part.length > 0).join(\"\\n\")\n\n/**\n * Represents text the user typed, and the files they attached.\n *\n * `id` defaults to a new one. Pass the client's own id so that a retried send stores the message\n * once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()(\"UserMessage\", {\n id: InputId.pipe(Schema.withConstructorDefault(makeInputId())),\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(Attachment).check(Schema.isMaxLength(maxAttachments)))\n}) {}\n\n/**\n * Represents the user's answer to a block.\n *\n * It holds the id of the message the block was on, and the value in the block's answer schema\n * (in its JSON form). A chat UI shows it inside the block rather than as a message.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlockAnswer extends Schema.TaggedClass<BlockAnswer>()(\"BlockAnswer\", {\n id: InputId,\n messageId: Schema.String,\n kind: Schema.String,\n value: Schema.Unknown\n}) {}\n\n/**\n * Represents a specialist run that finished working on a brief.\n *\n * Unless the assistant stopped the run, it is an input, and a turn reads its report and decides\n * what to tell the user. Its id is fixed per run and brief, so it is stored once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistFinished extends Schema.TaggedClass<SpecialistFinished>()(\"SpecialistFinished\", {\n id: InputId,\n runId: RunId,\n specialist: Schema.String,\n /** Which brief this answers: 1 for the first, then one more per follow-up. */\n brief: Schema.Int,\n goal: Schema.String,\n status: Schema.Literals([\"answered\", \"failed\", \"stopped\", \"cut_off\"]),\n report: Schema.optional(Schema.String),\n error: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the user's decision on a tool call that waits for their approval: `\"approved\"`, so\n * the call runs, or `\"rejected\"`, with an optional short reason the model reads.\n *\n * Its id is fixed per call (see `ToolApproval.approve`), so a decision is stored once. A decision on\n * a call that isn't waiting any more (decided, or expired) isn't stored.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalDecision extends Schema.TaggedClass<ApprovalDecision>()(\"ApprovalDecision\", {\n id: InputId,\n callId: Schema.String,\n decision: Schema.Literals([\"approved\", \"rejected\"]),\n reason: Schema.optional(Schema.String.check(Schema.isMaxLength(500)))\n}) {}\n\n/**\n * Schema for every input `Assistant.submit` accepts.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Input = Schema.Union([UserMessage, BlockAnswer, SpecialistFinished, ApprovalDecision])\n\n/**\n * Represents an input to an assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Input = typeof Input.Type\n\n/**\n * Schema for the inputs from the chat's user, which are messages, block answers, and decisions on\n * tool calls that wait for their approval.\n *\n * A turn owes each one a reply. It is also what a chat client usually may submit, since the app's\n * events come from the server.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserInput = Schema.Union([UserMessage, BlockAnswer, ApprovalDecision])\n\n/**\n * Represents an input from the chat's user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserInput = typeof UserInput.Type\n\n/**\n * Represents the UI shown with a message, as a block kind from the assistant's `BlockKit` and its\n * props.\n *\n * A block that shows a tool's result (`Block.fromToolResult`) has the tool's name as its kind and\n * the result's `resultId`.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class MessageBlock extends Schema.Class<MessageBlock>(\"effect-assistant/MessageBlock\")({\n kind: Schema.String,\n props: Schema.Unknown,\n resultId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a message the assistant sent the user with `send_user_message`, optionally with a\n * block.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class AssistantMessage extends Schema.TaggedClass<AssistantMessage>()(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n block: Schema.optional(MessageBlock),\n /** Earlier messages whose block the user answered by typing instead. Their blocks close. */\n closes: Schema.optional(Schema.Array(Schema.String))\n}) {}\n\n/**\n * Schema for a tool call the model made.\n *\n * It is `effect/ai`'s tool call part (`Response.ToolCallPart`) for any tool, with its params in\n * JSON, as the model wrote them.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolCallPart = Schema.Struct({\n ...Response.ToolCallPart(\"\", Schema.Json).fields,\n name: Schema.String\n}).annotate({ identifier: \"ToolCallPart\" })\n\n/**\n * Represents a tool call the model made.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolCallPart = typeof ToolCallPart.Type\n\n/**\n * Schema for what the log keeps of a model call.\n *\n * It uses `effect/ai`'s response parts for text, reasoning (with the provider's metadata, such as\n * a thinking block's signature), and tool calls.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ModelPart = Schema.Union([Response.TextPart, Response.ReasoningPart, ToolCallPart])\n\n/**\n * Represents a part of a model call's output.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ModelPart = typeof ModelPart.Type\n\n/**\n * Represents what one model call wrote, as response parts for text, reasoning, and tool calls.\n *\n * `Prompt.fromResponseParts` turns the parts into history.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ModelOutput extends Schema.TaggedClass<ModelOutput>()(\"ModelOutput\", {\n parts: Schema.Array(ModelPart),\n /**\n * The last entry the model had read when it wrote this. Inputs after it\n * arrived while the model was working. A turn has handled what its\n * outputs had read.\n */\n seenThroughSequence: Schema.optional(Schema.Int),\n /** The model that wrote it, as the provider's id for it or the name the context gave it. */\n model: Schema.optional(Schema.String),\n /** The provider's id for the response, when it gives one. */\n responseId: Schema.optional(Schema.String),\n /** The call's token usage, with input (including the cache's reads and writes) and output. */\n usage: Schema.optional(Response.Usage),\n /** How long the call took, in milliseconds. */\n durationMillis: Schema.optional(Schema.Finite)\n}) {}\n\n/**\n * Represents a tool call that is about to run.\n *\n * It is stored before the tool runs, so after a crash the log says which calls may have done\n * something. Those calls run again with the same call id (see `AssistantToolCall`).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolStarted extends Schema.TaggedClass<ToolStarted>()(\"ToolStarted\", {\n callId: Schema.String,\n tool: Schema.String\n}) {}\n\n/**\n * Schema for how a tool call went, either `\"success\"` or `\"failure\"`, which the model reads as an\n * error.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolOutcome = Schema.Literals([\"success\", \"failure\"])\n\n/**\n * Represents how a tool call went.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolOutcome = typeof ToolOutcome.Type\n\n/**\n * Represents the result of one tool call, as the model reads it.\n *\n * It holds the tool's success or failure in its encoded (JSON) form, and which of the two it is. A\n * failure includes its reason when it has one, which is a `ToolFailure`'s `reason` or the\n * failure's tag.\n *\n * When the model reads less than the whole success (a `ToolResult.modelView`, or the `resultId`\n * added for a tool the assistant's blocks show), `full` holds the whole success, encoded by the\n * tool's success schema.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolResult extends Schema.TaggedClass<ToolResult>()(\"ToolResult\", {\n callId: Schema.String,\n tool: Schema.String,\n outcome: ToolOutcome,\n result: Schema.Json,\n reason: Schema.optional(Schema.String),\n full: Schema.optional(Schema.Json),\n /** The id the model passes in a `tool_result` block to show this result. */\n resultId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the start of a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnStarted extends Schema.TaggedClass<TurnStarted>()(\"TurnStarted\", {\n /** The assistant that runs it. */\n assistant: Schema.String,\n /**\n * The id of the turn's trace, when a tracer records it (not Effect's own, which exports nothing).\n */\n traceId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a turn that finished.\n *\n * `throughSequence` is the last entry the turn read. Inputs after it still need a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnCompleted extends Schema.TaggedClass<TurnCompleted>()(\"TurnCompleted\", {\n throughSequence: Schema.Int\n}) {}\n\n/**\n * Represents a turn that failed.\n *\n * `throughSequence` covers everything stored when the turn failed, so a failing input isn't retried\n * forever.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnFailed extends Schema.TaggedClass<TurnFailed>()(\"TurnFailed\", {\n throughSequence: Schema.Int,\n message: Schema.String\n}) {}\n\n/**\n * Represents a specialist run that started working, either spawned or continued by a follow-up\n * message.\n *\n * The model doesn't see it, since the call that started the run says so, and the run's report\n * arrives as a {@link SpecialistFinished}.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistStarted extends Schema.TaggedClass<SpecialistStarted>()(\"SpecialistStarted\", {\n runId: RunId,\n specialist: Schema.String,\n /** The goal it's working on. */\n goal: Schema.String\n}) {}\n\n/**\n * Represents the deletion of a chat.\n *\n * The chat stores nothing after it, the work running in the chat stopped, and its subscribers'\n * streams end here. Its log stays.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ChatDeleted extends Schema.TaggedClass<ChatDeleted>()(\"ChatDeleted\", {}) {}\n\n/**\n * Represents blocks that closed without an answer, like the ones `BlockKit.closeStale` closes\n * from a turn once the user moved on.\n *\n * The model doesn't see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlocksClosed extends Schema.TaggedClass<BlocksClosed>()(\"BlocksClosed\", {\n messageIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Represents a tool call that waits for the user's approval instead of running: its tool needs\n * approval (Effect's `needsApproval`).\n *\n * **Details**\n *\n * It holds the call's id, the tool, and its params, in JSON, as the model wrote them. The model\n * reads it as the call's result, saying it waits for the user; the user's\n * {@link ApprovalDecision} decides it, and an approved call runs then, with the same id.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalRequested extends Schema.TaggedClass<ApprovalRequested>()(\"ApprovalRequested\", {\n callId: Schema.String,\n tool: Schema.String,\n params: Schema.Json\n}) {}\n\n/**\n * Represents tool calls that waited for the user's approval and won't run: the user moved on, like\n * the ones `ToolApproval.closeStale` expires. The model reads that they weren't approved.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalsExpired extends Schema.TaggedClass<ApprovalsExpired>()(\"ApprovalsExpired\", {\n callIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Schema for every event the library defines.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantEvent = Schema.Union([\n UserMessage,\n BlockAnswer,\n AssistantMessage,\n ModelOutput,\n ToolStarted,\n ToolResult,\n TurnStarted,\n TurnCompleted,\n TurnFailed,\n SpecialistStarted,\n SpecialistFinished,\n BlocksClosed,\n ApprovalRequested,\n ApprovalDecision,\n ApprovalsExpired,\n ChatDeleted\n])\n\n/**\n * Represents an event the library defines.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantEvent = typeof AssistantEvent.Type\n\nconst libraryTags: ReadonlySet<string> = new Set(\n AssistantEvent.members.map((member) => member.fields._tag.schema.literal)\n)\n\n/**\n * Schema for the tag of one of the application's own events.\n *\n * It accepts any tag but the library's, and it is branded, so narrowing an entry's event to one\n * of the library's events (`Predicate.isTagged(event, \"UserMessage\")`) never leaves an app event\n * in.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AppTag = Schema.String.pipe(Schema.brand(\"~effect-assistant/AppTag\"))\n\n/**\n * Represents the schema of one of the application's own events, as `Assistant.make`'s `events`\n * takes it.\n *\n * **Details**\n *\n * It is a tagged struct or class (`Schema.TaggedStruct`, `Schema.TaggedClass`) whose `_tag` is a\n * string literal other than the library's, and that needs no services. The log stores the event in\n * the schema's JSON form.\n *\n * @category models\n * @since 0.3.0\n */\nexport type AppEventSchema = Schema.Codec<{ readonly _tag: string }, { readonly _tag: string }> & {\n readonly fields: { readonly _tag: { readonly ast: SchemaAST.AST } }\n}\n\n/**\n * Schema for one of the application's own events as it is stored, with its `_tag` and its fields\n * in JSON.\n *\n * **Details**\n *\n * An assistant made with `events: [Summary]` decodes it to a `Summary` in `CurrentChat`'s\n * `entries` and in its `subscribe`.\n *\n * An event that came in through the assistant's `submit`, from outside a turn, is an input, and the\n * log marks it with a `\"~effect-assistant/input\": true` key (see {@link isAppInput}); one a turn\n * appended has none. Decoding drops the key, so the app's schemas never see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const StoredAppEvent = Schema.StructWithRest(\n Schema.Struct({ _tag: AppTag, [inputKey]: Schema.optionalKey(Schema.Literal(true)) }),\n [Schema.Record(Schema.String, Schema.Json)]\n).check(Schema.makeFilter((event) => !libraryTags.has(event._tag) || `${event._tag} is one of the library's events`))\n\n/**\n * Represents one of the application's own events, as it is stored.\n *\n * @category models\n * @since 0.1.0\n */\nexport type StoredAppEvent = typeof StoredAppEvent.Type\n\n/**\n * Returns whether an event is one of the library's, not one of the app's own.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isLibraryEvent = (event: { readonly _tag: string }): event is AssistantEvent => libraryTags.has(event._tag)\n\n/**\n * Returns whether one of the application's events, as the log stores it, is an input: it came in\n * through the assistant's `submit`, from outside a turn, so storing it woke a turn. An event a turn\n * appended (`CurrentChat`'s `append`) isn't, and neither is a decoded one, which no longer has the\n * mark.\n *\n * @category guards\n * @since 0.3.0\n */\nexport const isAppInput = (event: { readonly _tag: string }): boolean =>\n !isLibraryEvent(event) && Predicate.hasProperty(event, inputKey) && event[inputKey] === true\n\n/**\n * Represents a chat's entry with any event in it, either the library's or the application's own\n * (decoded or not).\n *\n * The folds over a chat take this type, so a client's typed entries fit too.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyEntry {\n readonly chatId: ChatId\n readonly sequence: number\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\n/**\n * Schema for a stored event with its position in the chat.\n *\n * `sequence` starts at 1 and has no gaps. `at` is the time the event was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Entry = Schema.Struct({\n chatId: ChatId,\n sequence: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent, StoredAppEvent])\n})\n\n/**\n * Represents a stored event with its position in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Entry = typeof Entry.Type\n\n/**\n * Returns whether an event is one of the library's inputs, which are a user message, a block\n * answer, a finished specialist run, or a decision on a tool call waiting for approval.\n *\n * The application's events that came in through the assistant's `submit` are inputs too (see\n * {@link isAppInput}).\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isInput = (event: { readonly _tag: string }): event is Input =>\n Predicate.isTagged(event, \"UserMessage\") ||\n Predicate.isTagged(event, \"BlockAnswer\") ||\n Predicate.isTagged(event, \"SpecialistFinished\") ||\n Predicate.isTagged(event, \"ApprovalDecision\")\n\n/**\n * Returns whether an input starts a turn, which every input does except a run the assistant\n * stopped itself.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isWaking = (input: Input): boolean =>\n !(Predicate.isTagged(input, \"SpecialistFinished\") && input.status === \"stopped\")\n\n/**\n * Returns whether an input came from the chat's user, and so is owed a reply.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isUserInput = (input: Input): input is UserInput =>\n Predicate.isTagged(input, \"UserMessage\") ||\n Predicate.isTagged(input, \"BlockAnswer\") ||\n Predicate.isTagged(input, \"ApprovalDecision\")\n\n/**\n * Returns whether an event ends a turn, and so says how far the assistant has read.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isTurnEnd = (event: { readonly _tag: string }): event is TurnCompleted | TurnFailed =>\n Predicate.isTagged(event, \"TurnCompleted\") || Predicate.isTagged(event, \"TurnFailed\")\n\n/**\n * Returns the text of every message the user was shown, in order.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const assistantTexts = (entries: ReadonlyArray<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BAAkB,YAC7B,QAAQ,SAAS,EAAE,YACjB,eAAe,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAC3F"}
1
+ {"version":3,"file":"AssistantEvent.js","names":["makeInputId"],"sources":["../src/AssistantEvent.ts"],"sourcesContent":["/**\n * Defines the events that can happen in a chat.\n *\n * A chat is an append-only log of these events, and the log is the source of truth. A chat client\n * receives the part of the log its user sees (its `Timeline`), and the model's history is rebuilt\n * from the log before every model call. Besides the library's events ({@link AssistantEvent}), a\n * log holds the application's own events ({@link StoredAppEvent}).\n *\n * @since 0.1.0\n */\nimport * as Response from \"effect/ai/Response\"\nimport type * as DateTime from \"effect/DateTime\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as SchemaAST from \"effect/SchemaAST\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { InputId, make as makeInputId } from \"./InputId.ts\"\nimport { inputKey } from \"./internal/input.ts\"\nimport { RunId } from \"./RunId.ts\"\n\n/**\n * Schema for a file the user attached to a message, kept by reference.\n *\n * The file itself is stored elsewhere, so the log never holds its bytes.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Attachment = Schema.Struct({\n fileId: Schema.String.check(Schema.isMaxLength(64)),\n name: Schema.String.check(Schema.isMaxLength(255)),\n mediaType: Schema.String.check(Schema.isMaxLength(127)),\n /** In bytes. */\n size: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/**\n * The maximum number of files one message can carry.\n *\n * Each attached file is a line in every prompt after the message.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const maxAttachments = 10\n\n/**\n * Represents a file the user attached to a message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Attachment = typeof Attachment.Type\n\n/**\n * Formats a byte count for people and the model, such as `2.1 MB`.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const formatSize = (bytes: number): string =>\n bytes < 1024\n ? `${bytes} B`\n : bytes < 1024 * 1024\n ? `${(bytes / 1024).toFixed(1)} KB`\n : bytes < 1024 * 1024 * 1024\n ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n : `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n\n/**\n * Returns the line the model reads for an attachment.\n *\n * The line names the file and never holds its content.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const attachmentLine = (attachment: Attachment): string =>\n `[attached: ${attachment.name}, ${attachment.mediaType}, ${formatSize(attachment.size)}, id ${attachment.fileId}]`\n\n/**\n * Returns a message's text followed by a line for each attached file.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const textWithAttachments = (text: string, attachments: ReadonlyArray<Attachment> | undefined): string =>\n attachments === undefined || attachments.length === 0\n ? text\n : [text, ...attachments.map(attachmentLine)].filter((part) => part.length > 0).join(\"\\n\")\n\n/**\n * Represents text the user typed, and the files they attached.\n *\n * `id` defaults to a new one. Pass the client's own id so that a retried send stores the message\n * once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()(\"UserMessage\", {\n id: InputId.pipe(Schema.withConstructorDefault(makeInputId())),\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(Attachment).check(Schema.isMaxLength(maxAttachments)))\n}) {}\n\n/**\n * Represents the user's answer to a block.\n *\n * It holds the id of the message the block was on, and the value in the block's answer schema\n * (in its JSON form). A chat UI shows it inside the block rather than as a message.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlockAnswer extends Schema.TaggedClass<BlockAnswer>()(\"BlockAnswer\", {\n id: InputId,\n messageId: Schema.String,\n kind: Schema.String,\n value: Schema.Unknown\n}) {}\n\n/**\n * Represents a specialist run that finished working on a brief.\n *\n * Unless the assistant stopped the run, it is an input, and a turn reads its report and decides\n * what to tell the user. Its id is fixed per run and brief, so it is stored once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistFinished extends Schema.TaggedClass<SpecialistFinished>()(\"SpecialistFinished\", {\n id: InputId,\n runId: RunId,\n specialist: Schema.String,\n /** Which brief this answers: 1 for the first, then one more per follow-up. */\n brief: Schema.Int,\n goal: Schema.String,\n status: Schema.Literals([\"answered\", \"failed\", \"stopped\", \"cut_off\"]),\n report: Schema.optional(Schema.String),\n error: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the user's decision on a tool call that waits for their approval: `\"approved\"`, so\n * the call runs, or `\"rejected\"`, with an optional short reason the model reads.\n *\n * Its id is fixed per call (see `ToolApproval.approve`), so a decision is stored once. A decision on\n * a call that isn't waiting any more (decided, or expired) isn't stored.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalDecision extends Schema.TaggedClass<ApprovalDecision>()(\"ApprovalDecision\", {\n id: InputId,\n callId: Schema.String,\n decision: Schema.Literals([\"approved\", \"rejected\"]),\n reason: Schema.optional(Schema.String.check(Schema.isMaxLength(500)))\n}) {}\n\n/**\n * Schema for every input `Assistant.submit` accepts.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Input = Schema.Union([UserMessage, BlockAnswer, SpecialistFinished, ApprovalDecision])\n\n/**\n * Represents an input to an assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Input = typeof Input.Type\n\n/**\n * Schema for the inputs from the chat's user, which are messages, block answers, and decisions on\n * tool calls that wait for their approval.\n *\n * A turn owes each one a reply. It is also what a chat client usually may submit, since the app's\n * events come from the server.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserInput = Schema.Union([UserMessage, BlockAnswer, ApprovalDecision])\n\n/**\n * Represents an input from the chat's user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserInput = typeof UserInput.Type\n\n/**\n * Represents the UI shown with a message, as a block kind from the assistant's `BlockKit` and its\n * props.\n *\n * A block that shows a tool's result (`Block.fromToolResult`) has the tool's name as its kind and\n * the result's `resultId`.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class MessageBlock extends Schema.Class<MessageBlock>(\"effect-assistant/MessageBlock\")({\n kind: Schema.String,\n props: Schema.Unknown,\n resultId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a message the assistant sent the user with `send_user_message`, optionally with a\n * block.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class AssistantMessage extends Schema.TaggedClass<AssistantMessage>()(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n block: Schema.optional(MessageBlock),\n /** Earlier messages whose block the user answered by typing instead. Their blocks close. */\n closes: Schema.optional(Schema.Array(Schema.String))\n}) {}\n\n/**\n * Schema for a tool call the model made.\n *\n * It is `effect/ai`'s tool call part (`Response.ToolCallPart`) for any tool, with its params in\n * JSON, as the model wrote them.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolCallPart = Schema.Struct({\n ...Response.ToolCallPart(\"\", Schema.Json).fields,\n name: Schema.String\n}).annotate({ identifier: \"ToolCallPart\" })\n\n/**\n * Represents a tool call the model made.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolCallPart = typeof ToolCallPart.Type\n\n/**\n * Schema for what the log keeps of a model call.\n *\n * It uses `effect/ai`'s response parts for text, reasoning (with the provider's metadata, such as\n * a thinking block's signature), and tool calls.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ModelPart = Schema.Union([Response.TextPart, Response.ReasoningPart, ToolCallPart])\n\n/**\n * Represents a part of a model call's output.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ModelPart = typeof ModelPart.Type\n\n/**\n * Represents what one model call wrote, as response parts for text, reasoning, and tool calls.\n *\n * `Prompt.fromResponseParts` turns the parts into history.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ModelOutput extends Schema.TaggedClass<ModelOutput>()(\"ModelOutput\", {\n parts: Schema.Array(ModelPart),\n /**\n * The last entry the model had read when it wrote this. Inputs after it\n * arrived while the model was working. A turn has handled what its\n * outputs had read.\n */\n seenThroughSequence: Schema.optional(Schema.Int),\n /** The model that wrote it, as the provider's id for it or the name the context gave it. */\n model: Schema.optional(Schema.String),\n /** The provider's id for the response, when it gives one. */\n responseId: Schema.optional(Schema.String),\n /** The call's token usage, with input (including the cache's reads and writes) and output. */\n usage: Schema.optional(Response.Usage),\n /** How long the call took, in milliseconds. */\n durationMillis: Schema.optional(Schema.Finite)\n}) {}\n\n/**\n * Represents a tool call that is about to run.\n *\n * It is stored before the tool runs, so after a crash the log says which calls may have done\n * something. Those calls run again with the same call id (see `AssistantToolCall`).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolStarted extends Schema.TaggedClass<ToolStarted>()(\"ToolStarted\", {\n callId: Schema.String,\n tool: Schema.String\n}) {}\n\n/**\n * Schema for how a tool call went, either `\"success\"` or `\"failure\"`, which the model reads as an\n * error.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolOutcome = Schema.Literals([\"success\", \"failure\"])\n\n/**\n * Represents how a tool call went.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolOutcome = typeof ToolOutcome.Type\n\n/**\n * Represents the result of one tool call, as the model reads it.\n *\n * It holds the tool's success or failure in its encoded (JSON) form, and which of the two it is. A\n * failure includes its reason when it has one, which is a `ToolFailure`'s `reason` or the\n * failure's tag.\n *\n * When the model reads less than the whole success (a `ToolResult.modelView`, or the `resultId`\n * added for a tool the assistant's blocks show), `full` holds the whole success, encoded by the\n * tool's success schema.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolResult extends Schema.TaggedClass<ToolResult>()(\"ToolResult\", {\n callId: Schema.String,\n tool: Schema.String,\n outcome: ToolOutcome,\n result: Schema.Json,\n reason: Schema.optional(Schema.String),\n full: Schema.optional(Schema.Json),\n /** The id the model passes in a `tool_result` block to show this result. */\n resultId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the start of a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnStarted extends Schema.TaggedClass<TurnStarted>()(\"TurnStarted\", {\n /** The assistant that runs it. */\n assistant: Schema.String,\n /**\n * The id of the turn's trace, when a tracer records it (not Effect's own, which exports nothing).\n */\n traceId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a turn that finished.\n *\n * `throughSequence` is the last entry the turn read. Inputs after it still need a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnCompleted extends Schema.TaggedClass<TurnCompleted>()(\"TurnCompleted\", {\n throughSequence: Schema.Int\n}) {}\n\n/**\n * Represents a turn that failed.\n *\n * `throughSequence` covers everything stored when the turn failed, so a failing input isn't retried\n * forever.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnFailed extends Schema.TaggedClass<TurnFailed>()(\"TurnFailed\", {\n throughSequence: Schema.Int,\n message: Schema.String\n}) {}\n\n/**\n * Represents a specialist run that started working, either spawned or continued by a follow-up\n * message.\n *\n * The model doesn't see it, since the call that started the run says so, and the run's report\n * arrives as a {@link SpecialistFinished}.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistStarted extends Schema.TaggedClass<SpecialistStarted>()(\"SpecialistStarted\", {\n runId: RunId,\n specialist: Schema.String,\n /** The goal it's working on. */\n goal: Schema.String\n}) {}\n\n/**\n * Represents the deletion of a chat.\n *\n * The chat stores nothing after it, the work running in the chat stopped, and its subscribers'\n * streams end here. Its log stays.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ChatDeleted extends Schema.TaggedClass<ChatDeleted>()(\"ChatDeleted\", {}) {}\n\n/**\n * Represents blocks that closed without an answer, like the ones `BlockKit.closeStale` closes\n * from a turn once the user moved on.\n *\n * The model doesn't see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlocksClosed extends Schema.TaggedClass<BlocksClosed>()(\"BlocksClosed\", {\n messageIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Represents a tool call that waits for the user's approval instead of running: its tool needs\n * approval (Effect's `needsApproval`).\n *\n * **Details**\n *\n * It holds the call's id, the tool, and its params, in JSON, as the model wrote them. The model\n * reads it as the call's result, saying it waits for the user; the user's\n * {@link ApprovalDecision} decides it, and an approved call runs then, with the same id.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalRequested extends Schema.TaggedClass<ApprovalRequested>()(\"ApprovalRequested\", {\n callId: Schema.String,\n tool: Schema.String,\n params: Schema.Json\n}) {}\n\n/**\n * Represents tool calls that waited for the user's approval and won't run: the user moved on, like\n * the ones `ToolApproval.closeStale` expires. The model reads that they weren't approved.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport class ApprovalsExpired extends Schema.TaggedClass<ApprovalsExpired>()(\"ApprovalsExpired\", {\n callIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Schema for every event the library defines.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantEvent = Schema.Union([\n UserMessage,\n BlockAnswer,\n AssistantMessage,\n ModelOutput,\n ToolStarted,\n ToolResult,\n TurnStarted,\n TurnCompleted,\n TurnFailed,\n SpecialistStarted,\n SpecialistFinished,\n BlocksClosed,\n ApprovalRequested,\n ApprovalDecision,\n ApprovalsExpired,\n ChatDeleted\n])\n\n/**\n * Represents an event the library defines.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantEvent = typeof AssistantEvent.Type\n\nconst libraryTags: ReadonlySet<string> = new Set(\n AssistantEvent.members.map((member) => member.fields._tag.schema.literal)\n)\n\n/**\n * Schema for the tag of one of the application's own events.\n *\n * It accepts any tag but the library's, and it is branded, so narrowing an entry's event to one\n * of the library's events (`Predicate.isTagged(event, \"UserMessage\")`) never leaves an app event\n * in.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AppTag = Schema.String.pipe(Schema.brand(\"~effect-assistant/AppTag\"))\n\n/**\n * Represents the schema of one of the application's own events, as `Assistant.make`'s `events`\n * takes it.\n *\n * **Details**\n *\n * It is a tagged struct or class (`Schema.TaggedStruct`, `Schema.TaggedClass`) whose `_tag` is a\n * string literal other than the library's, and that needs no services. The log stores the event in\n * the schema's JSON form.\n *\n * @category models\n * @since 0.3.0\n */\nexport type AppEventSchema = Schema.Codec<{ readonly _tag: string }, { readonly _tag: string }> & {\n readonly fields: { readonly _tag: { readonly ast: SchemaAST.AST } }\n}\n\n/**\n * Schema for one of the application's own events as it is stored, with its `_tag` and its fields\n * in JSON.\n *\n * **Details**\n *\n * An assistant made with `events: [Summary]` decodes it to a `Summary` in `CurrentChat`'s\n * `entries` and in its `subscribe`.\n *\n * An event that came in through the assistant's `submit`, from outside a turn, is an input, and the\n * log marks it with a `\"~effect-assistant/input\": true` key (see {@link isAppInput}); one a turn\n * appended has none. Decoding drops the key, so the app's schemas never see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const StoredAppEvent = Schema.StructWithRest(\n Schema.Struct({ _tag: AppTag, [inputKey]: Schema.optionalKey(Schema.Literal(true)) }),\n [Schema.Record(Schema.String, Schema.Json)]\n).check(Schema.makeFilter((event) => !libraryTags.has(event._tag) || `${event._tag} is one of the library's events`))\n\n/**\n * Represents one of the application's own events, as it is stored.\n *\n * @category models\n * @since 0.1.0\n */\nexport type StoredAppEvent = typeof StoredAppEvent.Type\n\n/**\n * Returns whether an event is one of the library's, not one of the app's own.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isLibraryEvent = (event: { readonly _tag: string }): event is AssistantEvent => libraryTags.has(event._tag)\n\n/**\n * Returns whether one of the application's events, as the log stores it, is an input: it came in\n * through the assistant's `submit`, from outside a turn, so storing it woke a turn. An event a turn\n * appended (`CurrentChat`'s `append`) isn't, and neither is a decoded one, which no longer has the\n * mark.\n *\n * @category guards\n * @since 0.3.0\n */\nexport const isAppInput = (event: { readonly _tag: string }): boolean =>\n !isLibraryEvent(event) && Predicate.hasProperty(event, inputKey) && event[inputKey] === true\n\n/**\n * Represents a chat's entry with any event in it, either the library's or the application's own\n * (decoded or not).\n *\n * The folds over a chat take this type, so a client's typed entries fit too.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyEntry {\n readonly chatId: ChatId\n readonly sequence: number\n readonly at: DateTime.Utc\n readonly event: { readonly _tag: string }\n}\n\n/**\n * Schema for a stored event with its position in the chat.\n *\n * `sequence` starts at 1 and has no gaps. `at` is the time the event was stored, a UTC\n * `DateTime` that encodes as epoch milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Entry = Schema.Struct({\n chatId: ChatId,\n sequence: Schema.Int,\n at: Schema.DateTimeUtcFromMillis,\n event: Schema.Union([AssistantEvent, StoredAppEvent])\n})\n\n/**\n * Represents a stored event with its position in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Entry = typeof Entry.Type\n\n/**\n * Returns whether an event is one of the library's inputs, which are a user message, a block\n * answer, a finished specialist run, or a decision on a tool call waiting for approval.\n *\n * The application's events that came in through the assistant's `submit` are inputs too (see\n * {@link isAppInput}).\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isInput = (event: { readonly _tag: string }): event is Input =>\n Predicate.isTagged(event, \"UserMessage\") ||\n Predicate.isTagged(event, \"BlockAnswer\") ||\n Predicate.isTagged(event, \"SpecialistFinished\") ||\n Predicate.isTagged(event, \"ApprovalDecision\")\n\n/**\n * Returns whether an input starts a turn, which every input does except a run the assistant\n * stopped itself.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isWaking = (input: Input): boolean =>\n !(Predicate.isTagged(input, \"SpecialistFinished\") && input.status === \"stopped\")\n\n/**\n * Returns whether an input came from the chat's user, and so is owed a reply.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isUserInput = (input: Input): input is UserInput =>\n Predicate.isTagged(input, \"UserMessage\") ||\n Predicate.isTagged(input, \"BlockAnswer\") ||\n Predicate.isTagged(input, \"ApprovalDecision\")\n\n/**\n * Returns whether an event ends a turn, and so says how far the assistant has read.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isTurnEnd = (event: { readonly _tag: string }): event is TurnCompleted | TurnFailed =>\n Predicate.isTagged(event, \"TurnCompleted\") || Predicate.isTagged(event, \"TurnFailed\")\n\n/**\n * Returns the text of every message the user was shown, in order.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const assistantTexts = (entries: ReadonlyArray<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BAAkB,YAC7B,QAAQ,SAAS,EAAE,YACjB,eAAe,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAC3F"}
package/dist/ChatLog.js CHANGED
@@ -6,7 +6,7 @@ import * as Effect from "effect/Effect";
6
6
  import * as Layer from "effect/Layer";
7
7
  import * as Predicate from "effect/Predicate";
8
8
  import * as Schema from "effect/Schema";
9
- import * as Clock from "effect/Clock";
9
+ import * as DateTime from "effect/DateTime";
10
10
  import * as Ref from "effect/Ref";
11
11
  import * as SqlClient from "effect/sql/SqlClient";
12
12
  //#region src/ChatLog.ts
@@ -46,7 +46,7 @@ const make = (storage) => ChatLog.of({
46
46
  append: Effect.fn("ChatLog.append")(function* (chatId, events) {
47
47
  if (events.length === 0) return [];
48
48
  const sequence = yield* storage.lastSequence(chatId);
49
- const at = yield* Clock.currentTimeMillis;
49
+ const at = yield* DateTime.now;
50
50
  const entries = events.map((event, n) => Entry.make({
51
51
  chatId,
52
52
  sequence: sequence + n + 1,
@@ -145,7 +145,7 @@ const layerSql = (options) => Layer.effect(ChatLog, Effect.gen(function* () {
145
145
  return (yield* Schema.decodeUnknownEffect(Schema.Array(Row))(rows)).map((row) => Entry.make({
146
146
  chatId: row.chat_id,
147
147
  sequence: row.sequence,
148
- at: row.at,
148
+ at: DateTime.makeUnsafe(row.at),
149
149
  event: row.event
150
150
  }));
151
151
  });
@@ -169,7 +169,7 @@ const layerSql = (options) => Layer.effect(ChatLog, Effect.gen(function* () {
169
169
  return {
170
170
  chat_id: chatId,
171
171
  sequence: entry.sequence,
172
- at: entry.at,
172
+ at: DateTime.toEpochMillis(entry.at),
173
173
  event
174
174
  };
175
175
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"ChatLog.js","names":["AssistantEvent.isTurnEnd","AssistantEvent.AssistantEvent","AssistantEvent.StoredAppEvent"],"sources":["../src/ChatLog.ts"],"sourcesContent":["/**\n * This module provides the `ChatLog` service, which stores each chat as an append-only list of\n * `AssistantEvent`s.\n *\n * A log is built on a {@link Storage}. {@link layerMemory} keeps every chat in memory, for tests\n * and local runs, and {@link layerSql} stores chats in a SQL table so they survive restarts. To\n * use another store, implement a `Storage` and pass it to {@link make}.\n *\n * @since 0.1.0\n */\nimport * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { ChatId } from \"./ChatId.ts\"\n\n/**\n * Service that stores each chat's events as an ordered list of entries.\n *\n * @category services\n * @since 0.1.0\n */\nexport class ChatLog extends Context.Service<\n ChatLog,\n {\n /** Appends events to a chat and returns them as stored entries. */\n readonly append: (\n chatId: ChatId,\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n /** Reads a chat's stored entries in order, either all of them or only those after a `sequence`. */\n readonly read: (chatId: ChatId, options?: ReadOptions) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n /**\n * Returns the chats whose last entry ends neither a turn nor the chat. After a restart, these\n * are the chats that may still owe a turn.\n */\n readonly unfinished: Effect.Effect<ReadonlyArray<ChatId>>\n }\n>()(\"effect-assistant/ChatLog\") {}\n\n/**\n * Represents the options that select which of a chat's entries to read.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ReadOptions {\n /** Reads only the entries after this `sequence`. */\n readonly after?: number | undefined\n}\n\n/**\n * Represents the storage that a `ChatLog` is built on.\n *\n * A storage reads a chat's entries, finds a chat's last `sequence`, writes new entries, and finds every\n * chat's last entry. Entries are never removed, so a deleted chat keeps its log, which ends in\n * `ChatDeleted`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Storage {\n readonly read: (chatId: ChatId, options?: ReadOptions) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n readonly lastSequence: (chatId: ChatId) => Effect.Effect<number>\n readonly write: (chatId: ChatId, entries: ReadonlyArray<AssistantEvent.Entry>) => Effect.Effect<void>\n /** Returns the last entry of every chat. */\n readonly lastEntries: Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n}\n\n/**\n * Creates a `ChatLog` from a {@link Storage}. `append` numbers new entries after the chat's last\n * `sequence` and stamps them with the current time.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (storage: Storage): ChatLog[\"Service\"] =>\n ChatLog.of({\n read: storage.read,\n append: Effect.fn(\"ChatLog.append\")(function* (\n chatId: ChatId,\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n if (events.length === 0) return []\n\n const sequence = yield* storage.lastSequence(chatId)\n const at = yield* Clock.currentTimeMillis\n\n const entries = events.map((event, n) =>\n AssistantEvent.Entry.make({ chatId, sequence: sequence + n + 1, at, event })\n )\n\n yield* storage.write(chatId, entries)\n\n return entries\n }),\n unfinished: Effect.gen(function* () {\n const last = yield* storage.lastEntries\n\n // A deleted chat owes nothing.\n return last.flatMap((entry) =>\n AssistantEvent.isTurnEnd(entry.event) || Predicate.isTagged(entry.event, \"ChatDeleted\") ? [] : [entry.chatId]\n )\n })\n })\n\n/**\n * Layer that keeps every chat in memory. The log is lost when the process stops.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerMemory: Layer.Layer<ChatLog> = Layer.effect(\n ChatLog,\n Effect.gen(function* () {\n const chats = yield* Ref.make(new Map<ChatId, ReadonlyArray<AssistantEvent.Entry>>())\n\n return make({\n read: Effect.fnUntraced(function* (chatId: ChatId, options?: ReadOptions) {\n const all = yield* Ref.get(chats)\n\n return (all.get(chatId) ?? []).filter((entry) => entry.sequence > (options?.after ?? 0))\n }),\n lastSequence: Effect.fnUntraced(function* (chatId: ChatId) {\n const all = yield* Ref.get(chats)\n\n return all.get(chatId)?.at(-1)?.sequence ?? 0\n }),\n write: (chatId, entries) =>\n Ref.update(chats, (all) => new Map(all).set(chatId, [...(all.get(chatId) ?? []), ...entries])),\n lastEntries: Effect.gen(function* () {\n const all = yield* Ref.get(chats)\n\n return [...all.values()].flatMap((entries) => entries.slice(-1))\n })\n })\n })\n)\n\n/**\n * Schema for an event as the log stores it: JSON text.\n *\n * **Details**\n *\n * `layerSql` stores events with it. A storage of your own, for `make`, can use it to store the\n * same text.\n *\n * @category schemas\n * @since 0.8.0\n */\nexport const EventJson = Schema.fromJsonString(\n Schema.Union([AssistantEvent.AssistantEvent, AssistantEvent.StoredAppEvent])\n)\n\n/**\n * Represents the options accepted by `layerSql`.\n *\n * @category models\n * @since 0.8.0\n */\nexport interface SqlOptions {\n /** The table's name. Defaults to `chat_log`. */\n readonly table?: string | undefined\n}\n\n// Postgres returns BIGINT and DOUBLE PRECISION columns as strings; other databases as numbers.\nconst SqlNumber = Schema.Union([Schema.Finite, Schema.FiniteFromString])\n\nconst Row = Schema.Struct({ chat_id: ChatId, sequence: SqlNumber, at: SqlNumber, event: EventJson })\n\nconst decodeLastSequence = Schema.decodeUnknownEffect(\n Schema.Array(Schema.Struct({ sequence: Schema.NullOr(SqlNumber) }))\n)\n\n/**\n * Layer that stores chats in a SQL table, `chat_log` unless `table` names another.\n *\n * **Details**\n *\n * The table must already exist. It has the columns `chat_id`, `sequence`, `at`, and `event`, with the\n * primary key `(chat_id, sequence)`. The layer requires a `SqlClient`. In MySQL, `event` needs\n * `LONGTEXT`, since a tool's result can be larger than `TEXT` holds.\n *\n * **Example** (Storing chats in Postgres)\n *\n * ```ts\n * import * as PgClient from \"@effect/sql-pg/PgClient\"\n * import { ChatLog } from \"effect-assistant\"\n * import * as Config from \"effect/Config\"\n * import * as Layer from \"effect/Layer\"\n *\n * const ChatLogLive = ChatLog.layerSql().pipe(\n * Layer.provide(PgClient.layerConfig({ url: Config.Redacted(\"DATABASE_URL\") }))\n * )\n * ```\n *\n * The table, in Postgres:\n *\n * ```sql\n * CREATE TABLE chat_log (\n * chat_id TEXT NOT NULL,\n * sequence INTEGER NOT NULL,\n * at DOUBLE PRECISION NOT NULL,\n * event TEXT NOT NULL,\n * PRIMARY KEY (chat_id, sequence)\n * );\n * ```\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerSql = (options?: SqlOptions): Layer.Layer<ChatLog, never, SqlClient.SqlClient> =>\n Layer.effect(\n ChatLog,\n Effect.gen(function* () {\n const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n const table = sql(options?.table ?? \"chat_log\")\n\n const toEntries = Effect.fnUntraced(function* (rows: ReadonlyArray<unknown>) {\n const decoded = yield* Schema.decodeUnknownEffect(Schema.Array(Row))(rows)\n\n return decoded.map((row) =>\n AssistantEvent.Entry.make({\n chatId: row.chat_id,\n sequence: row.sequence,\n at: row.at,\n event: row.event\n })\n )\n })\n\n const encodeEvent = Schema.encodeEffect(EventJson)\n\n return make({\n read: Effect.fnUntraced(function* (chatId: ChatId, options?: ReadOptions) {\n const rows = yield* sql`\n SELECT chat_id, sequence, at, event FROM ${table} WHERE chat_id = ${chatId} AND sequence > ${options?.after ?? 0} ORDER BY sequence\n `\n\n return yield* toEntries(rows)\n }, Effect.orDie),\n lastSequence: Effect.fnUntraced(function* (chatId: ChatId) {\n const result = yield* sql`\n SELECT MAX(sequence) AS sequence FROM ${table} WHERE chat_id = ${chatId}\n `\n\n const rows = yield* decodeLastSequence(result)\n\n return rows[0]?.sequence ?? 0\n }, Effect.orDie),\n write: Effect.fnUntraced(function* (chatId: ChatId, entries: ReadonlyArray<AssistantEvent.Entry>) {\n const rows = yield* Effect.forEach(\n entries,\n Effect.fnUntraced(function* (entry: AssistantEvent.Entry) {\n const event = yield* encodeEvent(entry.event)\n\n return { chat_id: chatId, sequence: entry.sequence, at: entry.at, event }\n })\n )\n\n yield* sql`INSERT INTO ${table} ${sql.insert(rows)}`\n }, Effect.orDie),\n lastEntries: Effect.gen(function* () {\n const rows = yield* sql`\n SELECT e.chat_id, e.sequence, e.at, e.event FROM ${table} e\n JOIN (SELECT chat_id, MAX(sequence) AS sequence FROM ${table} GROUP BY chat_id) last\n ON last.chat_id = e.chat_id AND last.sequence = e.sequence\n `\n\n return yield* toEntries(rows)\n }).pipe(Effect.orDie)\n })\n })\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAa,UAAb,cAA6B,QAAQ,QAgBnC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC;;;;;;;;AAsCjC,MAAa,QAAQ,YACnB,QAAQ,GAAG;CACT,MAAM,QAAQ;CACd,QAAQ,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAClC,QACA,QACA;EACA,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;EAEjC,MAAM,WAAW,OAAO,QAAQ,aAAa,MAAM;EACnD,MAAM,KAAK,OAAO,MAAM;EAExB,MAAM,UAAU,OAAO,KAAK,OAAO,MAAA,MACZ,KAAK;GAAE;GAAQ,UAAU,WAAW,IAAI;GAAG;GAAI;EAAM,CAAC,CAC7E;EAEA,OAAO,QAAQ,MAAM,QAAQ,OAAO;EAEpC,OAAO;CACT,CAAC;CACD,YAAY,OAAO,IAAI,aAAa;EAIlC,QAAO,OAHa,QAAQ,YAAA,CAGhB,SAAS,UACnBA,UAAyB,MAAM,KAAK,KAAK,UAAU,SAAS,MAAM,OAAO,aAAa,IAAI,CAAC,IAAI,CAAC,MAAM,MAAM,CAC9G;CACF,CAAC;AACH,CAAC;;;;;;;AAQH,MAAa,cAAoC,MAAM,OACrD,SACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,IAAI,qBAAK,IAAI,IAAiD,CAAC;CAEpF,OAAO,KAAK;EACV,MAAM,OAAO,WAAW,WAAW,QAAgB,SAAuB;GAGxE,SAAQ,OAFW,IAAI,IAAI,KAAK,EAAA,CAEpB,IAAI,MAAM,KAAK,CAAC,EAAA,CAAG,Q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,CAAC,CAAC,CAAC,IAAI,EAAA,CAE1D,KAAK,QAAA,MACG,KAAK;GACxB,QAAQ,IAAI;GACZ,UAAU,IAAI;GACd,IAAI,IAAI;GACR,OAAO,IAAI;EACb,CAAC,CACH;CACF,CAAC;CAED,MAAM,cAAc,OAAO,aAAa,SAAS;CAEjD,OAAO,KAAK;EACV,MAAM,OAAO,WAAW,WAAW,QAAgB,SAAuB;GACxE,MAAM,OAAO,OAAO,GAAG;qDACoB,MAAM,mBAAmB,OAAO,kBAAkB,SAAS,SAAS,EAAE;;GAGjH,OAAO,OAAO,UAAU,IAAI;EAC9B,GAAG,OAAO,KAAK;EACf,cAAc,OAAO,WAAW,WAAW,QAAgB;GACzD,MAAM,SAAS,OAAO,GAAG;kDACe,MAAM,mBAAmB,OAAO;;GAKxE,QAAO,OAFa,mBAAmB,MAAM,EAAA,CAEjC,EAAE,EAAE,YAAY;EAC9B,GAAG,OAAO,KAAK;EACf,OAAO,OAAO,WAAW,WAAW,QAAgB,SAA8C;GAChG,MAAM,OAAO,OAAO,OAAO,QACzB,SACA,OAAO,WAAW,WAAW,OAA6B;IACxD,MAAM,QAAQ,OAAO,YAAY,MAAM,KAAK;IAE5C,OAAO;KAAE,SAAS;KAAQ,UAAU,MAAM;KAAU,IAAI,MAAM;KAAI;IAAM;GAC1E,CAAC,CACH;GAEA,OAAO,GAAG,eAAe,MAAM,GAAG,IAAI,OAAO,IAAI;EACnD,GAAG,OAAO,KAAK;EACf,aAAa,OAAO,IAAI,aAAa;GACnC,MAAM,OAAO,OAAO,GAAG;6DAC4B,MAAM;iEACF,MAAM;;;GAI7D,OAAO,OAAO,UAAU,IAAI;EAC9B,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;CACtB,CAAC;AACH,CAAC,CACH"}
1
+ {"version":3,"file":"ChatLog.js","names":["AssistantEvent.isTurnEnd","AssistantEvent.AssistantEvent","AssistantEvent.StoredAppEvent"],"sources":["../src/ChatLog.ts"],"sourcesContent":["/**\n * This module provides the `ChatLog` service, which stores each chat as an append-only list of\n * `AssistantEvent`s.\n *\n * A log is built on a {@link Storage}. {@link layerMemory} keeps every chat in memory, for tests\n * and local runs, and {@link layerSql} stores chats in a SQL table so they survive restarts. To\n * use another store, implement a `Storage` and pass it to {@link make}.\n *\n * @since 0.1.0\n */\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { ChatId } from \"./ChatId.ts\"\n\n/**\n * Service that stores each chat's events as an ordered list of entries.\n *\n * @category services\n * @since 0.1.0\n */\nexport class ChatLog extends Context.Service<\n ChatLog,\n {\n /** Appends events to a chat and returns them as stored entries. */\n readonly append: (\n chatId: ChatId,\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n /** Reads a chat's stored entries in order, either all of them or only those after a `sequence`. */\n readonly read: (chatId: ChatId, options?: ReadOptions) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n /**\n * Returns the chats whose last entry ends neither a turn nor the chat. After a restart, these\n * are the chats that may still owe a turn.\n */\n readonly unfinished: Effect.Effect<ReadonlyArray<ChatId>>\n }\n>()(\"effect-assistant/ChatLog\") {}\n\n/**\n * Represents the options that select which of a chat's entries to read.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ReadOptions {\n /** Reads only the entries after this `sequence`. */\n readonly after?: number | undefined\n}\n\n/**\n * Represents the storage that a `ChatLog` is built on.\n *\n * A storage reads a chat's entries, finds a chat's last `sequence`, writes new entries, and finds every\n * chat's last entry. Entries are never removed, so a deleted chat keeps its log, which ends in\n * `ChatDeleted`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Storage {\n readonly read: (chatId: ChatId, options?: ReadOptions) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n readonly lastSequence: (chatId: ChatId) => Effect.Effect<number>\n readonly write: (chatId: ChatId, entries: ReadonlyArray<AssistantEvent.Entry>) => Effect.Effect<void>\n /** Returns the last entry of every chat. */\n readonly lastEntries: Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>\n}\n\n/**\n * Creates a `ChatLog` from a {@link Storage}. `append` numbers new entries after the chat's last\n * `sequence` and stamps them with the current time.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (storage: Storage): ChatLog[\"Service\"] =>\n ChatLog.of({\n read: storage.read,\n append: Effect.fn(\"ChatLog.append\")(function* (\n chatId: ChatId,\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n if (events.length === 0) return []\n\n const sequence = yield* storage.lastSequence(chatId)\n const at = yield* DateTime.now\n\n const entries = events.map((event, n) =>\n AssistantEvent.Entry.make({ chatId, sequence: sequence + n + 1, at, event })\n )\n\n yield* storage.write(chatId, entries)\n\n return entries\n }),\n unfinished: Effect.gen(function* () {\n const last = yield* storage.lastEntries\n\n // A deleted chat owes nothing.\n return last.flatMap((entry) =>\n AssistantEvent.isTurnEnd(entry.event) || Predicate.isTagged(entry.event, \"ChatDeleted\") ? [] : [entry.chatId]\n )\n })\n })\n\n/**\n * Layer that keeps every chat in memory. The log is lost when the process stops.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerMemory: Layer.Layer<ChatLog> = Layer.effect(\n ChatLog,\n Effect.gen(function* () {\n const chats = yield* Ref.make(new Map<ChatId, ReadonlyArray<AssistantEvent.Entry>>())\n\n return make({\n read: Effect.fnUntraced(function* (chatId: ChatId, options?: ReadOptions) {\n const all = yield* Ref.get(chats)\n\n return (all.get(chatId) ?? []).filter((entry) => entry.sequence > (options?.after ?? 0))\n }),\n lastSequence: Effect.fnUntraced(function* (chatId: ChatId) {\n const all = yield* Ref.get(chats)\n\n return all.get(chatId)?.at(-1)?.sequence ?? 0\n }),\n write: (chatId, entries) =>\n Ref.update(chats, (all) => new Map(all).set(chatId, [...(all.get(chatId) ?? []), ...entries])),\n lastEntries: Effect.gen(function* () {\n const all = yield* Ref.get(chats)\n\n return [...all.values()].flatMap((entries) => entries.slice(-1))\n })\n })\n })\n)\n\n/**\n * Schema for an event as the log stores it: JSON text.\n *\n * **Details**\n *\n * `layerSql` stores events with it. A storage of your own, for `make`, can use it to store the\n * same text.\n *\n * @category schemas\n * @since 0.8.0\n */\nexport const EventJson = Schema.fromJsonString(\n Schema.Union([AssistantEvent.AssistantEvent, AssistantEvent.StoredAppEvent])\n)\n\n/**\n * Represents the options accepted by `layerSql`.\n *\n * @category models\n * @since 0.8.0\n */\nexport interface SqlOptions {\n /** The table's name. Defaults to `chat_log`. */\n readonly table?: string | undefined\n}\n\n// Postgres returns BIGINT and DOUBLE PRECISION columns as strings; other databases as numbers.\nconst SqlNumber = Schema.Union([Schema.Finite, Schema.FiniteFromString])\n\nconst Row = Schema.Struct({ chat_id: ChatId, sequence: SqlNumber, at: SqlNumber, event: EventJson })\n\nconst decodeLastSequence = Schema.decodeUnknownEffect(\n Schema.Array(Schema.Struct({ sequence: Schema.NullOr(SqlNumber) }))\n)\n\n/**\n * Layer that stores chats in a SQL table, `chat_log` unless `table` names another.\n *\n * **Details**\n *\n * The table must already exist. It has the columns `chat_id`, `sequence`, `at`, and `event`, with the\n * primary key `(chat_id, sequence)`. The layer requires a `SqlClient`. In MySQL, `event` needs\n * `LONGTEXT`, since a tool's result can be larger than `TEXT` holds.\n *\n * **Example** (Storing chats in Postgres)\n *\n * ```ts\n * import * as PgClient from \"@effect/sql-pg/PgClient\"\n * import { ChatLog } from \"effect-assistant\"\n * import * as Config from \"effect/Config\"\n * import * as Layer from \"effect/Layer\"\n *\n * const ChatLogLive = ChatLog.layerSql().pipe(\n * Layer.provide(PgClient.layerConfig({ url: Config.Redacted(\"DATABASE_URL\") }))\n * )\n * ```\n *\n * The table, in Postgres:\n *\n * ```sql\n * CREATE TABLE chat_log (\n * chat_id TEXT NOT NULL,\n * sequence INTEGER NOT NULL,\n * at DOUBLE PRECISION NOT NULL,\n * event TEXT NOT NULL,\n * PRIMARY KEY (chat_id, sequence)\n * );\n * ```\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerSql = (options?: SqlOptions): Layer.Layer<ChatLog, never, SqlClient.SqlClient> =>\n Layer.effect(\n ChatLog,\n Effect.gen(function* () {\n const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n const table = sql(options?.table ?? \"chat_log\")\n\n const toEntries = Effect.fnUntraced(function* (rows: ReadonlyArray<unknown>) {\n const decoded = yield* Schema.decodeUnknownEffect(Schema.Array(Row))(rows)\n\n return decoded.map((row) =>\n AssistantEvent.Entry.make({\n chatId: row.chat_id,\n sequence: row.sequence,\n at: DateTime.makeUnsafe(row.at),\n event: row.event\n })\n )\n })\n\n const encodeEvent = Schema.encodeEffect(EventJson)\n\n return make({\n read: Effect.fnUntraced(function* (chatId: ChatId, options?: ReadOptions) {\n const rows = yield* sql`\n SELECT chat_id, sequence, at, event FROM ${table} WHERE chat_id = ${chatId} AND sequence > ${options?.after ?? 0} ORDER BY sequence\n `\n\n return yield* toEntries(rows)\n }, Effect.orDie),\n lastSequence: Effect.fnUntraced(function* (chatId: ChatId) {\n const result = yield* sql`\n SELECT MAX(sequence) AS sequence FROM ${table} WHERE chat_id = ${chatId}\n `\n\n const rows = yield* decodeLastSequence(result)\n\n return rows[0]?.sequence ?? 0\n }, Effect.orDie),\n write: Effect.fnUntraced(function* (chatId: ChatId, entries: ReadonlyArray<AssistantEvent.Entry>) {\n const rows = yield* Effect.forEach(\n entries,\n Effect.fnUntraced(function* (entry: AssistantEvent.Entry) {\n const event = yield* encodeEvent(entry.event)\n\n return { chat_id: chatId, sequence: entry.sequence, at: DateTime.toEpochMillis(entry.at), event }\n })\n )\n\n yield* sql`INSERT INTO ${table} ${sql.insert(rows)}`\n }, Effect.orDie),\n lastEntries: Effect.gen(function* () {\n const rows = yield* sql`\n SELECT e.chat_id, e.sequence, e.at, e.event FROM ${table} e\n JOIN (SELECT chat_id, MAX(sequence) AS sequence FROM ${table} GROUP BY chat_id) last\n ON last.chat_id = e.chat_id AND last.sequence = e.sequence\n `\n\n return yield* toEntries(rows)\n }).pipe(Effect.orDie)\n })\n })\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAa,UAAb,cAA6B,QAAQ,QAgBnC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC;;;;;;;;AAsCjC,MAAa,QAAQ,YACnB,QAAQ,GAAG;CACT,MAAM,QAAQ;CACd,QAAQ,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAClC,QACA,QACA;EACA,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;EAEjC,MAAM,WAAW,OAAO,QAAQ,aAAa,MAAM;EACnD,MAAM,KAAK,OAAO,SAAS;EAE3B,MAAM,UAAU,OAAO,KAAK,OAAO,MAAA,MACZ,KAAK;GAAE;GAAQ,UAAU,WAAW,IAAI;GAAG;GAAI;EAAM,CAAC,CAC7E;EAEA,OAAO,QAAQ,MAAM,QAAQ,OAAO;EAEpC,OAAO;CACT,CAAC;CACD,YAAY,OAAO,IAAI,aAAa;EAIlC,QAAO,OAHa,QAAQ,YAAA,CAGhB,SAAS,UACnBA,UAAyB,MAAM,KAAK,KAAK,UAAU,SAAS,MAAM,OAAO,aAAa,IAAI,CAAC,IAAI,CAAC,MAAM,MAAM,CAC9G;CACF,CAAC;AACH,CAAC;;;;;;;AAQH,MAAa,cAAoC,MAAM,OACrD,SACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,IAAI,qBAAK,IAAI,IAAiD,CAAC;CAEpF,OAAO,KAAK;EACV,MAAM,OAAO,WAAW,WAAW,QAAgB,SAAuB;GAGxE,SAAQ,OAFW,IAAI,IAAI,KAAK,E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of what the assistant is doing, and whether it is writing a message to the user.
7
7
  *
8
8
  * Signals are never stored. They reach only the subscribers that are listening when they are sent
9
- * (`assistant.subscribe(chatId, { live: true })`), between the chat's entries and in order with
9
+ * (`assistant.subscribe(chatId, { signals: true })`), between the chat's entries and in order with
10
10
  * them. A turn's model never reads them, compaction never sees them, and a client that loads the
11
11
  * chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its
12
12
  * `TurnCompleted` or `TurnFailed`.
@@ -1 +1 @@
1
- {"version":3,"file":"ChatSignal.js","names":[],"sources":["../src/ChatSignal.ts"],"sourcesContent":["/**\n * This module provides the signals a chat sends its live subscribers while a turn works: a short\n * status of what the assistant is doing, and whether it is writing a message to the user.\n *\n * Signals are never stored. They reach only the subscribers that are listening when they are sent\n * (`assistant.subscribe(chatId, { live: true })`), between the chat's entries and in order with\n * them. A turn's model never reads them, compaction never sees them, and a client that loads the\n * chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its\n * `TurnCompleted` or `TurnFailed`.\n *\n * There is no signal that clears a status: the next one replaces it, typing hides it, and the\n * turn's end clears it. Typing stops before the turn ends, also when it fails, so neither\n * outlives its turn.\n *\n * @since 0.13.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Represents the line the chat shows next to the assistant while a turn works, like \"Checking\n * last summer's campaign budget\". The latest one shows until the next, until the model starts\n * writing to the user, or until the turn ends.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class Status extends Schema.TaggedClass<Status>()(\"Status\", {\n text: Schema.String\n}) {}\n\n/**\n * Represents the model starting to write a message to the user. The status line goes: the user\n * sees the message coming instead.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStarted extends Schema.TaggedClass<TypingStarted>()(\"TypingStarted\", {}) {}\n\n/**\n * Represents the end of the typing: the message is in the chat's log, or the model wrote none.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStopped extends Schema.TaggedClass<TypingStopped>()(\"TypingStopped\", {}) {}\n\n/**\n * Schema for any of a chat's signals.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport const ChatSignal = Schema.Union([Status, TypingStarted, TypingStopped])\n\n/**\n * Represents any of a chat's signals.\n *\n * @category models\n * @since 0.13.0\n */\nexport type ChatSignal = typeof ChatSignal.Type\n\n/**\n * Returns whether a value is one of a chat's signals, such as an item of a live subscription that\n * isn't an entry.\n *\n * @category guards\n * @since 0.13.0\n */\nexport const isChatSignal: (u: unknown) => u is ChatSignal = Schema.is(ChatSignal)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,SAAb,cAA4B,OAAO,YAAoB,CAAC,CAAC,UAAU,EACjE,MAAM,OAAO,OACf,CAAC,CAAC,CAAC,CAAC;;;;;;;;AASJ,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,MAAa,aAAa,OAAO,MAAM;CAAC;CAAQ;CAAe;AAAa,CAAC;;;;;;;;AAiB7E,MAAa,eAAgD,OAAO,GAAG,UAAU"}
1
+ {"version":3,"file":"ChatSignal.js","names":[],"sources":["../src/ChatSignal.ts"],"sourcesContent":["/**\n * This module provides the signals a chat sends its live subscribers while a turn works: a short\n * status of what the assistant is doing, and whether it is writing a message to the user.\n *\n * Signals are never stored. They reach only the subscribers that are listening when they are sent\n * (`assistant.subscribe(chatId, { signals: true })`), between the chat's entries and in order with\n * them. A turn's model never reads them, compaction never sees them, and a client that loads the\n * chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its\n * `TurnCompleted` or `TurnFailed`.\n *\n * There is no signal that clears a status: the next one replaces it, typing hides it, and the\n * turn's end clears it. Typing stops before the turn ends, also when it fails, so neither\n * outlives its turn.\n *\n * @since 0.13.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Represents the line the chat shows next to the assistant while a turn works, like \"Checking\n * last summer's campaign budget\". The latest one shows until the next, until the model starts\n * writing to the user, or until the turn ends.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class Status extends Schema.TaggedClass<Status>()(\"Status\", {\n text: Schema.String\n}) {}\n\n/**\n * Represents the model starting to write a message to the user. The status line goes: the user\n * sees the message coming instead.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStarted extends Schema.TaggedClass<TypingStarted>()(\"TypingStarted\", {}) {}\n\n/**\n * Represents the end of the typing: the message is in the chat's log, or the model wrote none.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStopped extends Schema.TaggedClass<TypingStopped>()(\"TypingStopped\", {}) {}\n\n/**\n * Schema for any of a chat's signals.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport const ChatSignal = Schema.Union([Status, TypingStarted, TypingStopped])\n\n/**\n * Represents any of a chat's signals.\n *\n * @category models\n * @since 0.13.0\n */\nexport type ChatSignal = typeof ChatSignal.Type\n\n/**\n * Returns whether a value is one of a chat's signals, such as an item of a live subscription that\n * isn't an entry.\n *\n * @category guards\n * @since 0.13.0\n */\nexport const isChatSignal: (u: unknown) => u is ChatSignal = Schema.is(ChatSignal)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,SAAb,cAA4B,OAAO,YAAoB,CAAC,CAAC,UAAU,EACjE,MAAM,OAAO,OACf,CAAC,CAAC,CAAC,CAAC;;;;;;;;AASJ,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,MAAa,aAAa,OAAO,MAAM;CAAC;CAAQ;CAAe;AAAa,CAAC;;;;;;;;AAiB7E,MAAa,eAAgD,OAAO,GAAG,UAAU"}
package/dist/Memory.d.ts CHANGED
@@ -5,9 +5,9 @@ import * as Context from "effect/Context";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Layer from "effect/Layer";
7
7
  import * as Schema from "effect/Schema";
8
+ import * as DateTime from "effect/DateTime";
8
9
  import * as Tool from "effect/ai/Tool";
9
10
  import * as Toolkit from "effect/ai/Toolkit";
10
- import * as DateTime from "effect/DateTime";
11
11
  declare namespace Memory_d_exports {
12
12
  export { Fact, MemoryStore, NewFact, Tools, layerMemory, layerTools, render };
13
13
  }
package/dist/Memory.js CHANGED
@@ -7,11 +7,11 @@ import * as Effect from "effect/Effect";
7
7
  import * as Layer from "effect/Layer";
8
8
  import * as Option from "effect/Option";
9
9
  import * as Schema from "effect/Schema";
10
- import * as Clock from "effect/Clock";
10
+ import * as DateTime from "effect/DateTime";
11
11
  import * as Ref from "effect/Ref";
12
12
  import * as Tool from "effect/ai/Tool";
13
13
  import * as Toolkit from "effect/ai/Toolkit";
14
- import * as DateTime from "effect/DateTime";
14
+ import * as Clock from "effect/Clock";
15
15
  //#region src/Memory.ts
16
16
  /**
17
17
  * Keeps facts an assistant remembers across chats.
@@ -2,8 +2,8 @@ import * as Context from "effect/Context";
2
2
  import * as Effect from "effect/Effect";
3
3
  import * as Layer from "effect/Layer";
4
4
  import * as Option from "effect/Option";
5
- import * as LanguageModel from "effect/ai/LanguageModel";
6
5
  import * as Duration from "effect/Duration";
6
+ import * as LanguageModel from "effect/ai/LanguageModel";
7
7
  declare namespace StatusSummary_d_exports {
8
8
  export { Options, StatusSummary, defaultInstructions, layer };
9
9
  }
@@ -4,8 +4,8 @@ import * as Effect from "effect/Effect";
4
4
  import * as Layer from "effect/Layer";
5
5
  import * as Option from "effect/Option";
6
6
  import * as Prompt from "effect/ai/Prompt";
7
- import * as LanguageModel from "effect/ai/LanguageModel";
8
7
  import * as Duration from "effect/Duration";
8
+ import * as LanguageModel from "effect/ai/LanguageModel";
9
9
  //#region src/StatusSummary.ts
10
10
  /**
11
11
  * This module provides the status a turn shows when nothing else says what it is doing: when the
@@ -3,6 +3,7 @@ import { ChatSignal, ChatSignal_d_exports } from "./ChatSignal.js";
3
3
  import { Assistant_d_exports, Entry } from "./Assistant.js";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as Stream from "effect/Stream";
6
+ import * as DateTime from "effect/DateTime";
6
7
  declare namespace Timeline_d_exports {
7
8
  export { Activity, ApprovalItem, AssistantMessage, Block, BlockStatus, Change, ChangesOptions, Definition, EventItem, Item, ShowOptions, Shown, SpecialistWorking, Timeline, UserMessage, apply, changes, empty, fold, fromEntries, isIdle, snapshot };
8
9
  }
@@ -35,8 +36,8 @@ export declare const Block: Schema.Struct<{
35
36
  readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
36
37
  readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
37
38
  readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
38
- /** When the user answered, in epoch milliseconds, once the block is answered. */
39
- readonly answeredAt: Schema.optional<Schema.Finite>;
39
+ /** When the user answered, once the block is answered. Encodes as epoch milliseconds. */
40
+ readonly answeredAt: Schema.optional<Schema.DateTimeUtcFromMillis>;
40
41
  /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
41
42
  readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
42
43
  }>;
@@ -48,8 +49,8 @@ export declare const Block: Schema.Struct<{
48
49
  */
49
50
  export type Block = typeof Block.Type;
50
51
  /**
51
- * Schema for a message the user sent. `at` is when it was stored, in epoch
52
- * milliseconds.
52
+ * Schema for a message the user sent. `at` is when it was stored, a UTC `DateTime` that encodes
53
+ * as epoch milliseconds.
53
54
  *
54
55
  * @category schemas
55
56
  * @since 0.1.0
@@ -63,7 +64,7 @@ export declare const UserMessage: Schema.TaggedStruct<"UserMessage", {
63
64
  readonly mediaType: Schema.String;
64
65
  readonly size: Schema.Finite;
65
66
  }>>>;
66
- readonly at: Schema.Finite;
67
+ readonly at: Schema.DateTimeUtcFromMillis;
67
68
  }>;
68
69
  /**
69
70
  * Represents a message the user sent.
@@ -73,7 +74,8 @@ export declare const UserMessage: Schema.TaggedStruct<"UserMessage", {
73
74
  */
74
75
  export type UserMessage = typeof UserMessage.Type;
75
76
  /**
76
- * Schema for a message the assistant sent the user, including its block if it has one.
77
+ * Schema for a message the assistant sent the user, including its block if it has one. `at` is
78
+ * when it was stored, a UTC `DateTime` that encodes as epoch milliseconds.
77
79
  *
78
80
  * @category schemas
79
81
  * @since 0.1.0
@@ -81,14 +83,14 @@ export type UserMessage = typeof UserMessage.Type;
81
83
  export declare const AssistantMessage: Schema.TaggedStruct<"AssistantMessage", {
82
84
  readonly id: Schema.String;
83
85
  readonly text: Schema.String;
84
- readonly at: Schema.Finite;
86
+ readonly at: Schema.DateTimeUtcFromMillis;
85
87
  readonly block: Schema.optional<Schema.Struct<{
86
88
  readonly kind: Schema.String;
87
89
  readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
88
90
  readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
89
91
  readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
90
- /** When the user answered, in epoch milliseconds, once the block is answered. */
91
- readonly answeredAt: Schema.optional<Schema.Finite>;
92
+ /** When the user answered, once the block is answered. Encodes as epoch milliseconds. */
93
+ readonly answeredAt: Schema.optional<Schema.DateTimeUtcFromMillis>;
92
94
  /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
93
95
  readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
94
96
  }>>;
@@ -110,7 +112,8 @@ export type AssistantMessage = typeof AssistantMessage.Type;
110
112
  * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,
111
113
  * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or
112
114
  * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the
113
- * chat's log, and `at` is when the event was stored, in epoch milliseconds.
115
+ * chat's log, and `at` is when the event was stored, a UTC `DateTime` that encodes as epoch
116
+ * milliseconds.
114
117
  *
115
118
  * @category models
116
119
  * @since 0.3.0
@@ -120,7 +123,7 @@ export type EventItem<E> = E extends {
120
123
  } ? {
121
124
  readonly _tag: Tag;
122
125
  readonly id: string;
123
- readonly at: number;
126
+ readonly at: DateTime.Utc;
124
127
  readonly event: E;
125
128
  } : never;
126
129
  /**
@@ -133,8 +136,8 @@ export type EventItem<E> = E extends {
133
136
  * approve, so the item carries no params. `id` is the call's id, which the decision is for (see
134
137
  * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands
135
138
  * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how
136
- * the approved call went, once it ran. `at` is when the call started waiting, in epoch
137
- * milliseconds. A change updates the item in place as the call is decided and run.
139
+ * the approved call went, once it ran. `at` is when the call started waiting, a UTC `DateTime` that
140
+ * encodes as epoch milliseconds. A change updates the item in place as the call is decided and run.
138
141
  *
139
142
  * @category schemas
140
143
  * @since 0.4.0
@@ -145,7 +148,7 @@ export declare const ApprovalItem: Schema.TaggedStruct<"ToolApproval", {
145
148
  readonly status: Schema.Literals<readonly ["pending", "approved", "rejected", "expired"]>;
146
149
  readonly reason: Schema.optional<Schema.String>;
147
150
  readonly outcome: Schema.optional<Schema.Literals<readonly ["success", "failure"]>>;
148
- readonly at: Schema.Finite;
151
+ readonly at: Schema.DateTimeUtcFromMillis;
149
152
  }>;
150
153
  /**
151
154
  * Represents a tool call that waits, or waited, for the user's approval, as an item on the
@@ -183,14 +186,14 @@ export type ApprovalItem = typeof ApprovalItem.Type;
183
186
  export type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Events> | ApprovalItem;
184
187
  /**
185
188
  * Schema for a specialist that is working for the assistant. It holds the specialist's name and
186
- * when it started, in epoch milliseconds.
189
+ * when it started, a UTC `DateTime` that encodes as epoch milliseconds.
187
190
  *
188
191
  * @category schemas
189
192
  * @since 0.1.0
190
193
  */
191
194
  export declare const SpecialistWorking: Schema.Struct<{
192
195
  readonly specialist: Schema.String;
193
- readonly since: Schema.Finite;
196
+ readonly since: Schema.DateTimeUtcFromMillis;
194
197
  }>;
195
198
  /**
196
199
  * Represents a specialist that is working for the assistant.
@@ -206,7 +209,7 @@ export type SpecialistWorking = typeof SpecialistWorking.Type;
206
209
  * something that arrived. `specialists` lists the specialists that are working. When the chat is
207
210
  * idle, nothing is working, even if a workflow is waiting on a timer or on the user.
208
211
  *
209
- * On a live subscription (`subscribe(chatId, { live: true })`), `status` is a short line about what
212
+ * On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what
210
213
  * the running turn is doing, and `typing` is true while the model writes a message to the user. Both
211
214
  * come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline
212
215
  * folded from the log alone has neither.
@@ -218,7 +221,7 @@ export declare const Activity: Schema.Struct<{
218
221
  readonly working: Schema.Boolean;
219
222
  readonly specialists: Schema.$Array<Schema.Struct<{
220
223
  readonly specialist: Schema.String;
221
- readonly since: Schema.Finite;
224
+ readonly since: Schema.DateTimeUtcFromMillis;
222
225
  }>>;
223
226
  readonly status: Schema.optional<Schema.String>;
224
227
  readonly typing: Schema.Boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"Timeline.d.ts","names":[],"sources":["../src/Timeline.ts"],"mappings":";;;;;;;;;;;;;;;;qBA6Ca,aAAW,OAAA;;;;;;;YAQZ,qBAAqB,YAAY;;;;;;;;;qBAUhC,OAAK,OAAA;;;;;;;;;;;;;;;;YAiBN,eAAe,MAAM;;;;;;;;qBASpB,aAAW,OAAA;;;;;;;;;;;;;;;;;YAaZ,qBAAqB,YAAY;;;;;;;qBAQhC,kBAAgB,OAAA;;;;;;;;;;;;;;;;;;;;;YAajB,0BAA0B,iBAAiB;;;;;;;;;;;;;;;;YAiB3C,UAAU,KAAK;WAAqB,YAAY;;WAC7C,MAAM;WAAc;WAAq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ACnB,YAAY;;;;;WAKX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkFE;GACV,cAAc,aAAa,MAAM,uBAChC,YAAY,WAAW,SACvB,UAAU,eAAe,SACvB,GAAG,GACL,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,OACxE,OAAO,OAAO,OAAO,uBAAuB,GAAG;GACnD,GAAG,GAAG,cAAc,aAAa,MAAM,uBACtC,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,IAC3E,YAAY,WAAW,SACvB,UAAU,eAAe,QACxB,OAAO,OAAO,OAAO,uBAAuB,GAAG"}
package/dist/Timeline.js CHANGED
@@ -11,6 +11,7 @@ import * as Option from "effect/Option";
11
11
  import * as Predicate from "effect/Predicate";
12
12
  import * as Schema from "effect/Schema";
13
13
  import * as Stream from "effect/Stream";
14
+ import * as DateTime from "effect/DateTime";
14
15
  import { dual } from "effect/Function";
15
16
  import * as Match from "effect/Match";
16
17
  import * as SchemaTransformation from "effect/SchemaTransformation";
@@ -78,14 +79,14 @@ const Block = Schema.Struct({
78
79
  props: Schema.Json,
79
80
  status: BlockStatus,
80
81
  answer: Schema.optional(Schema.Json),
81
- /** When the user answered, in epoch milliseconds, once the block is answered. */
82
- answeredAt: Schema.optional(Schema.Finite),
82
+ /** When the user answered, once the block is answered. Encodes as epoch milliseconds. */
83
+ answeredAt: Schema.optional(Schema.DateTimeUtcFromMillis),
83
84
  /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
84
85
  result: Schema.optional(Schema.Json)
85
86
  });
86
87
  /**
87
- * Schema for a message the user sent. `at` is when it was stored, in epoch
88
- * milliseconds.
88
+ * Schema for a message the user sent. `at` is when it was stored, a UTC `DateTime` that encodes
89
+ * as epoch milliseconds.
89
90
  *
90
91
  * @category schemas
91
92
  * @since 0.1.0
@@ -94,10 +95,11 @@ const UserMessage = Schema.TaggedStruct("UserMessage", {
94
95
  id: InputId,
95
96
  text: Schema.String,
96
97
  attachments: Schema.optional(Schema.Array(Attachment)),
97
- at: Schema.Finite
98
+ at: Schema.DateTimeUtcFromMillis
98
99
  });
99
100
  /**
100
- * Schema for a message the assistant sent the user, including its block if it has one.
101
+ * Schema for a message the assistant sent the user, including its block if it has one. `at` is
102
+ * when it was stored, a UTC `DateTime` that encodes as epoch milliseconds.
101
103
  *
102
104
  * @category schemas
103
105
  * @since 0.1.0
@@ -105,7 +107,7 @@ const UserMessage = Schema.TaggedStruct("UserMessage", {
105
107
  const AssistantMessage = Schema.TaggedStruct("AssistantMessage", {
106
108
  id: Schema.String,
107
109
  text: Schema.String,
108
- at: Schema.Finite,
110
+ at: Schema.DateTimeUtcFromMillis,
109
111
  block: Schema.optional(Block)
110
112
  });
111
113
  /**
@@ -118,8 +120,8 @@ const AssistantMessage = Schema.TaggedStruct("AssistantMessage", {
118
120
  * approve, so the item carries no params. `id` is the call's id, which the decision is for (see
119
121
  * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands
120
122
  * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how
121
- * the approved call went, once it ran. `at` is when the call started waiting, in epoch
122
- * milliseconds. A change updates the item in place as the call is decided and run.
123
+ * the approved call went, once it ran. `at` is when the call started waiting, a UTC `DateTime` that
124
+ * encodes as epoch milliseconds. A change updates the item in place as the call is decided and run.
123
125
  *
124
126
  * @category schemas
125
127
  * @since 0.4.0
@@ -135,18 +137,18 @@ const ApprovalItem = Schema.TaggedStruct("ToolApproval", {
135
137
  ]),
136
138
  reason: Schema.optional(Schema.String),
137
139
  outcome: Schema.optional(ToolOutcome),
138
- at: Schema.Finite
140
+ at: Schema.DateTimeUtcFromMillis
139
141
  });
140
142
  /**
141
143
  * Schema for a specialist that is working for the assistant. It holds the specialist's name and
142
- * when it started, in epoch milliseconds.
144
+ * when it started, a UTC `DateTime` that encodes as epoch milliseconds.
143
145
  *
144
146
  * @category schemas
145
147
  * @since 0.1.0
146
148
  */
147
149
  const SpecialistWorking = Schema.Struct({
148
150
  specialist: Schema.String,
149
- since: Schema.Finite
151
+ since: Schema.DateTimeUtcFromMillis
150
152
  });
151
153
  /**
152
154
  * Schema for what is working in the chat.
@@ -155,7 +157,7 @@ const SpecialistWorking = Schema.Struct({
155
157
  * something that arrived. `specialists` lists the specialists that are working. When the chat is
156
158
  * idle, nothing is working, even if a workflow is waiting on a timer or on the user.
157
159
  *
158
- * On a live subscription (`subscribe(chatId, { live: true })`), `status` is a short line about what
160
+ * On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what
159
161
  * the running turn is doing, and `typing` is true while the model writes a message to the user. Both
160
162
  * come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline
161
163
  * folded from the log alone has neither.
@@ -172,7 +174,7 @@ const Activity = Schema.Struct({
172
174
  const eventItem = (schema) => Schema.Struct({
173
175
  _tag: Schema.Literal(tagOf(schema)),
174
176
  id: Schema.String,
175
- at: Schema.Finite,
177
+ at: Schema.DateTimeUtcFromMillis,
176
178
  event: schema
177
179
  });
178
180
  function makeChange(events = []) {
@@ -415,7 +417,7 @@ const activityOf = (activity, live) => {
415
417
  };
416
418
  const sameActivity = (a, b) => a.working === b.working && a.status === b.status && a.typing === b.typing && a.specialists.length === b.specialists.length && a.specialists.every((run, i) => {
417
419
  const other = b.specialists[i];
418
- return other !== void 0 && run.specialist === other.specialist && run.since === other.since;
420
+ return other !== void 0 && run.specialist === other.specialist && DateTime.Equivalence(run.since, other.since);
419
421
  });
420
422
  const folding = (show) => {
421
423
  const shown = new Map(show.map((schema) => [tagOf(schema), schema]));