effect-assistant 0.14.0 → 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.
@@ -5,7 +5,9 @@ import * as Option from "effect/Option";
5
5
  import * as Predicate from "effect/Predicate";
6
6
  import * as Schema from "effect/Schema";
7
7
  import * as Response from "effect/ai/Response";
8
+ import * as DateTime from "effect/DateTime";
8
9
  import * as Prompt from "effect/ai/Prompt";
10
+ import * as Duration from "effect/Duration";
9
11
  import * as Match from "effect/Match";
10
12
  //#region src/internal/history.ts
11
13
  /** @internal */
@@ -33,8 +35,8 @@ const unansweredCalls = (history) => {
33
35
  const notRunOutput = "Not run: the turn ended before this call ran.";
34
36
  /** @internal */
35
37
  const mayHaveRunOutput = "Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.";
36
- const ago = (millis) => {
37
- const seconds = Math.max(0, Math.round(millis / 1e3));
38
+ const ago = (duration) => {
39
+ const seconds = Math.max(0, Math.round(Duration.toSeconds(duration)));
38
40
  return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`;
39
41
  };
40
42
  const finishedText = (entries, index, finished) => {
@@ -45,7 +47,7 @@ const finishedText = (entries, index, finished) => {
45
47
  const wrote = (started === void 0 ? [] : entries.slice(from + 1, index)).some(({ event }) => Predicate.isTagged(event, "UserMessage"));
46
48
  const lines = [
47
49
  "A report from a specialist you started. The user hasn't seen it.",
48
- started === void 0 ? `You started it for: ${finished.goal}` : `You started it ${ago(at.at - started.at)} ago for: ${finished.goal}`,
50
+ started === void 0 ? `You started it for: ${finished.goal}` : `You started it ${ago(DateTime.distance(started.at, at.at))} ago for: ${finished.goal}`,
49
51
  wrote ? "The user has written since you started it." : "The user hasn't written since you started it.",
50
52
  Match.value(finished.status).pipe(Match.when("answered", () => `Report:\n${finished.report ?? ""}`), Match.when("failed", () => `It failed: ${finished.error ?? ""}`), Match.when("cut_off", () => "A restart cut it off before it finished. Spawn it again if it's still needed."), Match.when("stopped", () => "You stopped it."), Match.exhaustive)
51
53
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.textWithAttachments","AssistantEvent.isInput","AssistantEvent.isAppInput","AssistantEvent.isTurnEnd","AssistantEvent.isWaking","AssistantEvent.isUserInput","Uuid.fromKey"],"sources":["../../src/internal/history.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\"\nimport * as Response from \"effect/ai/Response\"\nimport * as Match from \"effect/Match\"\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 { toJson, toJsonText } from \"./schema.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const userText = (text: string): Prompt.UserMessage =>\n Prompt.userMessage({ content: [Prompt.textPart({ text })] })\n\n/** @internal */\nexport const toolMessage = (result: AssistantEvent.ToolResult): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: result.callId,\n name: result.tool,\n isFailure: result.outcome === \"failure\",\n result: result.result,\n providerExecuted: false\n })\n ]\n })\n\n// A call with no result is one a crash cut off.\n/** @internal */\nexport const unansweredCalls = (history: ReadonlyArray<Prompt.Message>): ReadonlyArray<AssistantEvent.ToolCallPart> => {\n const answered = new Set(\n history.flatMap((message) =>\n message.role === \"tool\" ? message.content.flatMap((part) => (part.type === \"tool-result\" ? [part.id] : [])) : []\n )\n )\n\n return history.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.flatMap((part) =>\n part.type === \"tool-call\" && !part.providerExecuted && !answered.has(part.id)\n ? [\n Response.makePart(\"tool-call\", {\n id: part.id,\n name: part.name,\n params: toJson(part.params),\n providerExecuted: false,\n metadata: part.options\n })\n ]\n : []\n )\n : []\n )\n}\n\n/** @internal */\nexport const notRunOutput = \"Not run: the turn ended before this call ran.\"\n\n/** @internal */\nexport const mayHaveRunOutput =\n \"Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.\"\n\nconst ago = (millis: number) => {\n const seconds = Math.max(0, Math.round(millis / 1000))\n\n return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`\n}\n\nconst finishedText = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n index: number,\n finished: AssistantEvent.SpecialistFinished\n) => {\n const at = entries[index]!\n\n const isStart = ({ event }: AssistantEvent.AnyEntry) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"SpecialistStarted\") &&\n event.runId === finished.runId\n\n const from = entries.slice(0, index).findLastIndex(isStart)\n const started = from === -1 ? undefined : entries[from]\n const since = started === undefined ? [] : entries.slice(from + 1, index)\n const wrote = since.some(({ event }) => Predicate.isTagged(event, \"UserMessage\"))\n\n const lines = [\n \"A report from a specialist you started. The user hasn't seen it.\",\n started === undefined\n ? `You started it for: ${finished.goal}`\n : `You started it ${ago(at.at - started.at)} ago for: ${finished.goal}`,\n wrote ? \"The user has written since you started it.\" : \"The user hasn't written since you started it.\",\n Match.value(finished.status).pipe(\n Match.when(\"answered\", () => `Report:\\n${finished.report ?? \"\"}`),\n Match.when(\"failed\", () => `It failed: ${finished.error ?? \"\"}`),\n Match.when(\"cut_off\", () => \"A restart cut it off before it finished. Spawn it again if it's still needed.\"),\n Match.when(\"stopped\", () => \"You stopped it.\"),\n Match.exhaustive\n )\n ]\n\n return `<specialist name=\"${finished.specialist}\" run=\"${finished.runId}\" status=\"${finished.status}\">\\n${lines.join(\n \"\\n\"\n )}\\n</specialist>`\n}\n\nconst answerText = (answer: AssistantEvent.BlockAnswer) =>\n `<answer message=\"${answer.messageId}\" kind=\"${answer.kind}\">\\nThe user answered with the block on your message ${answer.messageId}.\\n${toJsonText(answer.value)}\\n</answer>`\n\nconst resultText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe result of a call from earlier in this chat.\\n${toJsonText(result.result)}\\n</result>`\n\n/** @internal */\nexport const awaitingApprovalOutput =\n \"Waiting for the user's approval: they see this call and approve or reject it. Its outcome arrives later in this chat; don't call it again meanwhile.\"\n\nconst awaitingText = (request: AssistantEvent.ApprovalRequested) =>\n `<approval tool=\"${request.tool}\" call=\"${request.callId}\" status=\"pending\">\\nYour call to ${request.tool} from earlier in this chat waits for the user's approval.\\n${toJsonText(request.params)}\\n</approval>`\n\nconst approvedText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe user approved your call to ${result.tool} from earlier in this chat, and it ran.\\n${toJsonText(result.result)}\\n</result>`\n\nconst rejectedText = (decision: AssistantEvent.ApprovalDecision, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${decision.callId}\" decision=\"rejected\">\\nThe user rejected your call to ${tool}; it didn't run.${decision.reason === undefined ? \"\" : `\\nTheir reason: ${decision.reason}`}\\n</approval>`\n\nconst expiredText = (callId: string, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${callId}\" status=\"expired\">\\nThe user moved on without approving your call to ${tool}; it didn't run.\\n</approval>`\n\nconst awaitingMessage = (request: AssistantEvent.ApprovalRequested): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: request.callId,\n name: request.tool,\n isFailure: false,\n result: awaitingApprovalOutput,\n providerExecuted: false\n })\n ]\n })\n\nconst isEntry = (item: AssistantEvent.AnyEntry | Prompt.Message): item is AssistantEvent.AnyEntry =>\n Predicate.hasProperty(item, \"sequence\")\n\n// In the order the model saw the entries, not the order they were stored. A message a history view put in stands\n// where it is, right after the entry before it, and waits like an input for a call's result or for the model's next\n// read; the app's own events reach the model only as such messages.\n/** @internal */\nexport const fromEntries = (\n items: ReadonlyArray<AssistantEvent.AnyEntry | Prompt.Message>\n): ReadonlyArray<Prompt.Message> => {\n const entries = items.filter(isEntry)\n const history: Array<Prompt.Message> = []\n const held: Array<Prompt.Message> = []\n const open = new Set<string>()\n const called = new Set<string>()\n // Calls that waited for approval: the placeholder answered them, so what came of them later is an input.\n const requests = new Map<string, AssistantEvent.ApprovalRequested>()\n const toolOf = (callId: string) => requests.get(callId)?.tool ?? \"a tool\"\n\n const flushIfClosed = () => {\n if (open.size === 0) history.push(...held.splice(0))\n }\n\n const nextSeen = (from: number) => {\n const next = entries.slice(from + 1).find(({ event }) => Predicate.isTagged(event, \"ModelOutput\"))?.event\n\n return next !== undefined && AssistantEvent.isLibraryEvent(next) && Predicate.isTagged(next, \"ModelOutput\")\n ? next.seenThroughSequence\n : undefined\n }\n\n // `index` is the last entry at or before the item, and `sequence` where the item stands.\n const input = (index: number, sequence: number, item: Prompt.Message) => {\n const seen = nextSeen(index)\n\n if (open.size > 0 || (seen !== undefined && seen < sequence)) held.push(item)\n else history.push(item)\n }\n\n let index = -1\n\n for (const item of items) {\n if (!isEntry(item)) {\n input(index, (entries[index]?.sequence ?? 0) + 0.5, item)\n\n continue\n }\n\n index += 1\n\n const { event, sequence } = item\n const at = index\n\n if (!AssistantEvent.isLibraryEvent(event)) continue\n\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) =>\n input(at, sequence, userText(AssistantEvent.textWithAttachments(message.text, message.attachments))),\n BlockAnswer: (answer) => input(at, sequence, userText(answerText(answer))),\n ModelOutput: (output) => {\n history.push(...Prompt.fromResponseParts(output.parts).content)\n\n for (const part of output.parts) {\n if (part.type === \"tool-call\") {\n open.add(part.id)\n called.add(part.id)\n }\n }\n\n flushIfClosed()\n },\n ToolResult: (result) => {\n if (requests.has(result.callId)) return input(at, sequence, userText(approvedText(result)))\n\n // A view that starts after the call (since a summary, say) keeps its result as text: a tool result needs its\n // call right before it.\n if (!called.has(result.callId)) return input(at, sequence, userText(resultText(result)))\n\n history.push(toolMessage(result))\n open.delete(result.callId)\n flushIfClosed()\n },\n AssistantMessage: () => undefined,\n ToolStarted: () => undefined,\n TurnStarted: () => undefined,\n TurnCompleted: () => undefined,\n TurnFailed: () => undefined,\n SpecialistFinished: (finished) => input(at, sequence, userText(finishedText(entries, at, finished))),\n // Every run starts in a call of the model's own (a spawn or a follow-up), whose result says so.\n SpecialistStarted: () => undefined,\n BlocksClosed: () => undefined,\n // The call's result, for the provider's pairing; what the user decides comes later.\n ApprovalRequested: (request) => {\n requests.set(request.callId, request)\n\n if (!called.has(request.callId)) return input(at, sequence, userText(awaitingText(request)))\n\n history.push(awaitingMessage(request))\n open.delete(request.callId)\n flushIfClosed()\n },\n // An approved call's result says so.\n ApprovalDecision: (decision) =>\n decision.decision === \"rejected\"\n ? input(at, sequence, userText(rejectedText(decision, toolOf(decision.callId))))\n : undefined,\n ApprovalsExpired: (expired) =>\n expired.callIds.forEach((callId) => input(at, sequence, userText(expiredText(callId, toolOf(callId))))),\n ChatDeleted: () => undefined\n })\n )\n }\n\n return [...history, ...held]\n}\n\n/** @internal */\nexport const isInput = (event: { readonly _tag: string }): boolean =>\n AssistantEvent.isInput(event) || AssistantEvent.isAppInput(event)\n\n/** @internal */\nexport const handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): number => {\n const last = entries.findLast(({ event }) => AssistantEvent.isTurnEnd(event))?.event\n\n return last !== undefined && AssistantEvent.isTurnEnd(last) ? last.throughSequence : 0\n}\n\n// A run the assistant stopped isn't an input here: it wakes nothing.\n/** @internal */\nexport const unhandledInputs = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>\n): ReadonlyArray<{ readonly _tag: string }> => {\n const seen = handledThrough(entries)\n\n return entries.flatMap(({ event, sequence }) =>\n sequence > seen && isInput(event) && !(AssistantEvent.isInput(event) && !AssistantEvent.isWaking(event))\n ? [event]\n : []\n )\n}\n\n/** @internal */\nexport const needsTurn = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): boolean =>\n unhandledInputs(entries).length > 0\n\n// A failure the user was shown counts as a reply, and so does a call they're asked to approve.\n/** @internal */\nexport const owesReply = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n return (\n latest !== undefined &&\n !entries.some(\n ({ event, sequence }) =>\n sequence > latest.sequence &&\n (Predicate.isTagged(event, \"AssistantMessage\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ApprovalRequested\"))\n )\n )\n}\n\nconst sentToWaitOn = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(false) }))\n\n// Messages sent with `wait: false` are progress while the model kept working, like \"On it\".\nconst progressMessages = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlySet<string> =>\n new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"ModelOutput\")\n ? event.parts.flatMap((part) =>\n part.type === \"tool-call\" && part.name === \"send_user_message\" && Option.isSome(sentToWaitOn(part.params))\n ? [Uuid.fromKey(`message:${part.id}`)]\n : []\n )\n : []\n )\n )\n\n// The model said it was on it and stopped without the result: its last message since the user's latest input was\n// progress. An earlier message may have answered something else, such as an input that came before. A specialist still\n// working doesn't count, since its report is what comes next.\n/** @internal */\nexport const owesDelivery = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n if (latest === undefined) return false\n\n const after = entries.flatMap(({ sequence, event }) =>\n sequence > latest.sequence && AssistantEvent.isLibraryEvent(event) ? [event] : []\n )\n\n const last = after.findLast((event) => Predicate.isTagged(event, \"AssistantMessage\"))\n const progress = progressMessages(entries)\n const started = after.flatMap((event) => (Predicate.isTagged(event, \"SpecialistStarted\") ? [event.runId] : []))\n\n const finished = new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"SpecialistFinished\") ? [event.runId] : []\n )\n )\n\n // A call waiting for the user's approval is what comes next, like a specialist's report.\n return (\n last !== undefined &&\n last.block === undefined &&\n progress.has(last.id) &&\n !after.some((event) => Predicate.isTagged(event, \"TurnFailed\") || Predicate.isTagged(event, \"ApprovalRequested\")) &&\n started.every((runId) => finished.has(runId))\n )\n}\n\n/** @internal */\nexport const unreadAfter = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean =>\n entries.some(({ event, sequence }) => sequence > throughSequence && isInput(event))\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,YAAY,SACvB,OAAO,YAAY,EAAE,SAAS,CAAC,OAAO,SAAS,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;;AAG7D,MAAa,eAAe,WAC1B,OAAO,YAAY,EACjB,SAAS,CACP,OAAO,eAAe;CACpB,IAAI,OAAO;CACX,MAAM,OAAO;CACb,WAAW,OAAO,YAAY;CAC9B,QAAQ,OAAO;CACf,kBAAkB;AACpB,CAAC,CACH,EACF,CAAC;;AAIH,MAAa,mBAAmB,YAAuF;CACrH,MAAM,WAAW,IAAI,IACnB,QAAQ,SAAS,YACf,QAAQ,SAAS,SAAS,QAAQ,QAAQ,SAAS,SAAU,KAAK,SAAS,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAE,IAAI,CAAC,CACjH,CACF;CAEA,OAAO,QAAQ,SAAS,YACtB,QAAQ,SAAS,cACb,QAAQ,QAAQ,SAAS,SACvB,KAAK,SAAS,eAAe,CAAC,KAAK,oBAAoB,CAAC,SAAS,IAAI,KAAK,EAAE,IACxE,CACE,SAAS,SAAS,aAAa;EAC7B,IAAI,KAAK;EACT,MAAM,KAAK;EACX,QAAQ,OAAO,KAAK,MAAM;EAC1B,kBAAkB;EAClB,UAAU,KAAK;CACjB,CAAC,CACH,IACA,CAAC,CACP,IACA,CAAC,CACP;AACF;;AAGA,MAAa,eAAe;;AAG5B,MAAa,mBACX;AAEF,MAAM,OAAO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,CAClF;CAEA,MAAM,OAAO,MAAM,UAAU,UAAU,UAAU,SAAS,OAAO,kBAAkB,CAAC;CACpF,MAAM,WAAW,iBAAiB,OAAO;CACzC,MAAM,UAAU,MAAM,SAAS,UAAW,UAAU,SAAS,OAAO,mBAAmB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAE;CAE9G,MAAM,WAAW,IAAI,IACnB,QAAQ,SAAS,EAAE,YACjBA,eAA8B,KAAK,KAAK,UAAU,SAAS,OAAO,oBAAoB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAC7G,CACF;CAGA,OACE,SAAS,KAAA,KACT,KAAK,UAAU,KAAA,KACf,SAAS,IAAI,KAAK,EAAE,KACpB,CAAC,MAAM,MAAM,UAAU,UAAU,SAAS,OAAO,YAAY,KAAK,UAAU,SAAS,OAAO,mBAAmB,CAAC,KAChH,QAAQ,OAAO,UAAU,SAAS,IAAI,KAAK,CAAC;AAEhD;;AAGA,MAAa,eAAe,SAAiD,oBAC3E,QAAQ,MAAM,EAAE,OAAO,eAAe,WAAW,mBAAmB,QAAQ,KAAK,CAAC"}
1
+ {"version":3,"file":"history.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.textWithAttachments","AssistantEvent.isInput","AssistantEvent.isAppInput","AssistantEvent.isTurnEnd","AssistantEvent.isWaking","AssistantEvent.isUserInput","Uuid.fromKey"],"sources":["../../src/internal/history.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\"\nimport * as Response from \"effect/ai/Response\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Duration from \"effect/Duration\"\nimport * as Match from \"effect/Match\"\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 { toJson, toJsonText } from \"./schema.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const userText = (text: string): Prompt.UserMessage =>\n Prompt.userMessage({ content: [Prompt.textPart({ text })] })\n\n/** @internal */\nexport const toolMessage = (result: AssistantEvent.ToolResult): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: result.callId,\n name: result.tool,\n isFailure: result.outcome === \"failure\",\n result: result.result,\n providerExecuted: false\n })\n ]\n })\n\n// A call with no result is one a crash cut off.\n/** @internal */\nexport const unansweredCalls = (history: ReadonlyArray<Prompt.Message>): ReadonlyArray<AssistantEvent.ToolCallPart> => {\n const answered = new Set(\n history.flatMap((message) =>\n message.role === \"tool\" ? message.content.flatMap((part) => (part.type === \"tool-result\" ? [part.id] : [])) : []\n )\n )\n\n return history.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.flatMap((part) =>\n part.type === \"tool-call\" && !part.providerExecuted && !answered.has(part.id)\n ? [\n Response.makePart(\"tool-call\", {\n id: part.id,\n name: part.name,\n params: toJson(part.params),\n providerExecuted: false,\n metadata: part.options\n })\n ]\n : []\n )\n : []\n )\n}\n\n/** @internal */\nexport const notRunOutput = \"Not run: the turn ended before this call ran.\"\n\n/** @internal */\nexport const mayHaveRunOutput =\n \"Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.\"\n\nconst ago = (duration: Duration.Duration) => {\n const seconds = Math.max(0, Math.round(Duration.toSeconds(duration)))\n\n return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`\n}\n\nconst finishedText = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n index: number,\n finished: AssistantEvent.SpecialistFinished\n) => {\n const at = entries[index]!\n\n const isStart = ({ event }: AssistantEvent.AnyEntry) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"SpecialistStarted\") &&\n event.runId === finished.runId\n\n const from = entries.slice(0, index).findLastIndex(isStart)\n const started = from === -1 ? undefined : entries[from]\n const since = started === undefined ? [] : entries.slice(from + 1, index)\n const wrote = since.some(({ event }) => Predicate.isTagged(event, \"UserMessage\"))\n\n const lines = [\n \"A report from a specialist you started. The user hasn't seen it.\",\n started === undefined\n ? `You started it for: ${finished.goal}`\n : `You started it ${ago(DateTime.distance(started.at, at.at))} ago for: ${finished.goal}`,\n wrote ? \"The user has written since you started it.\" : \"The user hasn't written since you started it.\",\n Match.value(finished.status).pipe(\n Match.when(\"answered\", () => `Report:\\n${finished.report ?? \"\"}`),\n Match.when(\"failed\", () => `It failed: ${finished.error ?? \"\"}`),\n Match.when(\"cut_off\", () => \"A restart cut it off before it finished. Spawn it again if it's still needed.\"),\n Match.when(\"stopped\", () => \"You stopped it.\"),\n Match.exhaustive\n )\n ]\n\n return `<specialist name=\"${finished.specialist}\" run=\"${finished.runId}\" status=\"${finished.status}\">\\n${lines.join(\n \"\\n\"\n )}\\n</specialist>`\n}\n\nconst answerText = (answer: AssistantEvent.BlockAnswer) =>\n `<answer message=\"${answer.messageId}\" kind=\"${answer.kind}\">\\nThe user answered with the block on your message ${answer.messageId}.\\n${toJsonText(answer.value)}\\n</answer>`\n\nconst resultText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe result of a call from earlier in this chat.\\n${toJsonText(result.result)}\\n</result>`\n\n/** @internal */\nexport const awaitingApprovalOutput =\n \"Waiting for the user's approval: they see this call and approve or reject it. Its outcome arrives later in this chat; don't call it again meanwhile.\"\n\nconst awaitingText = (request: AssistantEvent.ApprovalRequested) =>\n `<approval tool=\"${request.tool}\" call=\"${request.callId}\" status=\"pending\">\\nYour call to ${request.tool} from earlier in this chat waits for the user's approval.\\n${toJsonText(request.params)}\\n</approval>`\n\nconst approvedText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe user approved your call to ${result.tool} from earlier in this chat, and it ran.\\n${toJsonText(result.result)}\\n</result>`\n\nconst rejectedText = (decision: AssistantEvent.ApprovalDecision, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${decision.callId}\" decision=\"rejected\">\\nThe user rejected your call to ${tool}; it didn't run.${decision.reason === undefined ? \"\" : `\\nTheir reason: ${decision.reason}`}\\n</approval>`\n\nconst expiredText = (callId: string, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${callId}\" status=\"expired\">\\nThe user moved on without approving your call to ${tool}; it didn't run.\\n</approval>`\n\nconst awaitingMessage = (request: AssistantEvent.ApprovalRequested): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: request.callId,\n name: request.tool,\n isFailure: false,\n result: awaitingApprovalOutput,\n providerExecuted: false\n })\n ]\n })\n\nconst isEntry = (item: AssistantEvent.AnyEntry | Prompt.Message): item is AssistantEvent.AnyEntry =>\n Predicate.hasProperty(item, \"sequence\")\n\n// In the order the model saw the entries, not the order they were stored. A message a history view put in stands\n// where it is, right after the entry before it, and waits like an input for a call's result or for the model's next\n// read; the app's own events reach the model only as such messages.\n/** @internal */\nexport const fromEntries = (\n items: ReadonlyArray<AssistantEvent.AnyEntry | Prompt.Message>\n): ReadonlyArray<Prompt.Message> => {\n const entries = items.filter(isEntry)\n const history: Array<Prompt.Message> = []\n const held: Array<Prompt.Message> = []\n const open = new Set<string>()\n const called = new Set<string>()\n // Calls that waited for approval: the placeholder answered them, so what came of them later is an input.\n const requests = new Map<string, AssistantEvent.ApprovalRequested>()\n const toolOf = (callId: string) => requests.get(callId)?.tool ?? \"a tool\"\n\n const flushIfClosed = () => {\n if (open.size === 0) history.push(...held.splice(0))\n }\n\n const nextSeen = (from: number) => {\n const next = entries.slice(from + 1).find(({ event }) => Predicate.isTagged(event, \"ModelOutput\"))?.event\n\n return next !== undefined && AssistantEvent.isLibraryEvent(next) && Predicate.isTagged(next, \"ModelOutput\")\n ? next.seenThroughSequence\n : undefined\n }\n\n // `index` is the last entry at or before the item, and `sequence` where the item stands.\n const input = (index: number, sequence: number, item: Prompt.Message) => {\n const seen = nextSeen(index)\n\n if (open.size > 0 || (seen !== undefined && seen < sequence)) held.push(item)\n else history.push(item)\n }\n\n let index = -1\n\n for (const item of items) {\n if (!isEntry(item)) {\n input(index, (entries[index]?.sequence ?? 0) + 0.5, item)\n\n continue\n }\n\n index += 1\n\n const { event, sequence } = item\n const at = index\n\n if (!AssistantEvent.isLibraryEvent(event)) continue\n\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) =>\n input(at, sequence, userText(AssistantEvent.textWithAttachments(message.text, message.attachments))),\n BlockAnswer: (answer) => input(at, sequence, userText(answerText(answer))),\n ModelOutput: (output) => {\n history.push(...Prompt.fromResponseParts(output.parts).content)\n\n for (const part of output.parts) {\n if (part.type === \"tool-call\") {\n open.add(part.id)\n called.add(part.id)\n }\n }\n\n flushIfClosed()\n },\n ToolResult: (result) => {\n if (requests.has(result.callId)) return input(at, sequence, userText(approvedText(result)))\n\n // A view that starts after the call (since a summary, say) keeps its result as text: a tool result needs its\n // call right before it.\n if (!called.has(result.callId)) return input(at, sequence, userText(resultText(result)))\n\n history.push(toolMessage(result))\n open.delete(result.callId)\n flushIfClosed()\n },\n AssistantMessage: () => undefined,\n ToolStarted: () => undefined,\n TurnStarted: () => undefined,\n TurnCompleted: () => undefined,\n TurnFailed: () => undefined,\n SpecialistFinished: (finished) => input(at, sequence, userText(finishedText(entries, at, finished))),\n // Every run starts in a call of the model's own (a spawn or a follow-up), whose result says so.\n SpecialistStarted: () => undefined,\n BlocksClosed: () => undefined,\n // The call's result, for the provider's pairing; what the user decides comes later.\n ApprovalRequested: (request) => {\n requests.set(request.callId, request)\n\n if (!called.has(request.callId)) return input(at, sequence, userText(awaitingText(request)))\n\n history.push(awaitingMessage(request))\n open.delete(request.callId)\n flushIfClosed()\n },\n // An approved call's result says so.\n ApprovalDecision: (decision) =>\n decision.decision === \"rejected\"\n ? input(at, sequence, userText(rejectedText(decision, toolOf(decision.callId))))\n : undefined,\n ApprovalsExpired: (expired) =>\n expired.callIds.forEach((callId) => input(at, sequence, userText(expiredText(callId, toolOf(callId))))),\n ChatDeleted: () => undefined\n })\n )\n }\n\n return [...history, ...held]\n}\n\n/** @internal */\nexport const isInput = (event: { readonly _tag: string }): boolean =>\n AssistantEvent.isInput(event) || AssistantEvent.isAppInput(event)\n\n/** @internal */\nexport const handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): number => {\n const last = entries.findLast(({ event }) => AssistantEvent.isTurnEnd(event))?.event\n\n return last !== undefined && AssistantEvent.isTurnEnd(last) ? last.throughSequence : 0\n}\n\n// A run the assistant stopped isn't an input here: it wakes nothing.\n/** @internal */\nexport const unhandledInputs = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>\n): ReadonlyArray<{ readonly _tag: string }> => {\n const seen = handledThrough(entries)\n\n return entries.flatMap(({ event, sequence }) =>\n sequence > seen && isInput(event) && !(AssistantEvent.isInput(event) && !AssistantEvent.isWaking(event))\n ? [event]\n : []\n )\n}\n\n/** @internal */\nexport const needsTurn = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): boolean =>\n unhandledInputs(entries).length > 0\n\n// A failure the user was shown counts as a reply, and so does a call they're asked to approve.\n/** @internal */\nexport const owesReply = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n return (\n latest !== undefined &&\n !entries.some(\n ({ event, sequence }) =>\n sequence > latest.sequence &&\n (Predicate.isTagged(event, \"AssistantMessage\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ApprovalRequested\"))\n )\n )\n}\n\nconst sentToWaitOn = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(false) }))\n\n// Messages sent with `wait: false` are progress while the model kept working, like \"On it\".\nconst progressMessages = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlySet<string> =>\n new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"ModelOutput\")\n ? event.parts.flatMap((part) =>\n part.type === \"tool-call\" && part.name === \"send_user_message\" && Option.isSome(sentToWaitOn(part.params))\n ? [Uuid.fromKey(`message:${part.id}`)]\n : []\n )\n : []\n )\n )\n\n// The model said it was on it and stopped without the result: its last message since the user's latest input was\n// progress. An earlier message may have answered something else, such as an input that came before. A specialist still\n// working doesn't count, since its report is what comes next.\n/** @internal */\nexport const owesDelivery = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n if (latest === undefined) return false\n\n const after = entries.flatMap(({ sequence, event }) =>\n sequence > latest.sequence && AssistantEvent.isLibraryEvent(event) ? [event] : []\n )\n\n const last = after.findLast((event) => Predicate.isTagged(event, \"AssistantMessage\"))\n const progress = progressMessages(entries)\n const started = after.flatMap((event) => (Predicate.isTagged(event, \"SpecialistStarted\") ? [event.runId] : []))\n\n const finished = new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"SpecialistFinished\") ? [event.runId] : []\n )\n )\n\n // A call waiting for the user's approval is what comes next, like a specialist's report.\n return (\n last !== undefined &&\n last.block === undefined &&\n progress.has(last.id) &&\n !after.some((event) => Predicate.isTagged(event, \"TurnFailed\") || Predicate.isTagged(event, \"ApprovalRequested\")) &&\n started.every((runId) => finished.has(runId))\n )\n}\n\n/** @internal */\nexport const unreadAfter = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean =>\n entries.some(({ event, sequence }) => sequence > throughSequence && isInput(event))\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,YAAY,SACvB,OAAO,YAAY,EAAE,SAAS,CAAC,OAAO,SAAS,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;;AAG7D,MAAa,eAAe,WAC1B,OAAO,YAAY,EACjB,SAAS,C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,OAAO,YAAY,KAAK,UAAU,SAAS,OAAO,mBAAmB,CAAC,KAChH,QAAQ,OAAO,UAAU,SAAS,IAAI,KAAK,CAAC;AAEhD;;AAGA,MAAa,eAAe,SAAiD,oBAC3E,QAAQ,MAAM,EAAE,OAAO,eAAe,WAAW,mBAAmB,QAAQ,KAAK,CAAC"}
@@ -2,8 +2,8 @@ import { Status, TypingStarted, TypingStopped } from "../ChatSignal.js";
2
2
  import * as Context from "effect/Context";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Option from "effect/Option";
5
- import * as Clock from "effect/Clock";
6
5
  import * as SynchronizedRef from "effect/SynchronizedRef";
6
+ import * as Clock from "effect/Clock";
7
7
  //#region src/internal/live.ts
8
8
  /** @internal */
9
9
  const TurnLive = Context.Reference("effect-assistant/TurnLive", { defaultValue: Option.none });
@@ -13,11 +13,11 @@ import * as Predicate from "effect/Predicate";
13
13
  import * as Schema from "effect/Schema";
14
14
  import * as Stream from "effect/Stream";
15
15
  import * as Data from "effect/Data";
16
- import * as Clock from "effect/Clock";
17
16
  import * as Model from "effect/ai/Model";
18
17
  import * as Prompt from "effect/ai/Prompt";
19
18
  import * as SchemaAST from "effect/SchemaAST";
20
19
  import * as LanguageModel from "effect/ai/LanguageModel";
20
+ import * as Clock from "effect/Clock";
21
21
  //#region src/internal/loop.ts
22
22
  /** @internal */
23
23
  const TurnApprovals = Context.Reference("effect-assistant/TurnApprovals", { defaultValue: Option.none });
@@ -4,9 +4,9 @@ import { fromEntries } from "./history.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Option from "effect/Option";
6
6
  import * as Predicate from "effect/Predicate";
7
- import * as Clock from "effect/Clock";
8
7
  import * as Ref from "effect/Ref";
9
8
  import * as Duration from "effect/Duration";
9
+ import * as Clock from "effect/Clock";
10
10
  import * as Schedule from "effect/Schedule";
11
11
  //#region src/internal/summary.ts
12
12
  const MAX_LINE = 300;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-assistant",
3
- "version": "0.14.0",
3
+ "version": "0.15.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": {
package/src/Assistant.ts CHANGED
@@ -17,6 +17,7 @@ import type * as Prompt from "effect/ai/Prompt"
17
17
  import type * as Tool from "effect/ai/Tool"
18
18
  import type * as Toolkit from "effect/ai/Toolkit"
19
19
  import * as Context from "effect/Context"
20
+ import type * as DateTime from "effect/DateTime"
20
21
  import * as Effect from "effect/Effect"
21
22
  import * as Filter from "effect/Filter"
22
23
  import * as Layer from "effect/Layer"
@@ -139,7 +140,7 @@ export type HistoryView<Events = never> = (
139
140
  export interface Entry<Events = never> {
140
141
  readonly chatId: ChatId
141
142
  readonly sequence: number
142
- readonly at: number
143
+ readonly at: DateTime.Utc
143
144
  readonly event: AssistantEvent.AssistantEvent | Events
144
145
  }
145
146
 
@@ -508,7 +509,7 @@ function entrySchema(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Sche
508
509
  Schema.Struct({
509
510
  chatId: ChatId,
510
511
  sequence: Schema.Int,
511
- at: Schema.Finite,
512
+ at: Schema.DateTimeUtcFromMillis,
512
513
  event: Schema.Union([AssistantEvent.AssistantEvent, ...events])
513
514
  })
514
515
  )
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * @since 0.1.0
11
11
  */
12
+ import type * as DateTime from "effect/DateTime"
12
13
  import * as Match from "effect/Match"
13
14
  import * as Predicate from "effect/Predicate"
14
15
  import * as AssistantEvent from "./AssistantEvent.ts"
@@ -25,8 +26,8 @@ export interface SpecialistRun {
25
26
  readonly specialist: string
26
27
  /** The goal the run is working on. */
27
28
  readonly goal: string
28
- /** When the run started, in epoch milliseconds. */
29
- readonly since: number
29
+ /** When the run started. */
30
+ readonly since: DateTime.Utc
30
31
  }
31
32
 
32
33
  /**
@@ -36,8 +37,8 @@ export interface SpecialistRun {
36
37
  * @since 0.1.0
37
38
  */
38
39
  export interface State {
39
- /** When the running turn started, in epoch milliseconds, or `undefined` when no turn runs. */
40
- readonly turnSince: number | undefined
40
+ /** When the running turn started, or `undefined` when no turn runs. */
41
+ readonly turnSince: DateTime.Utc | undefined
41
42
  /**
42
43
  * Whether an input arrived that no finished turn has read. When this is true, a turn is about
43
44
  * to start.
@@ -9,6 +9,7 @@
9
9
  * @since 0.1.0
10
10
  */
11
11
  import * as Response from "effect/ai/Response"
12
+ import type * as DateTime from "effect/DateTime"
12
13
  import * as Predicate from "effect/Predicate"
13
14
  import * as Schema from "effect/Schema"
14
15
  import type * as SchemaAST from "effect/SchemaAST"
@@ -586,15 +587,15 @@ export const isAppInput = (event: { readonly _tag: string }): boolean =>
586
587
  export interface AnyEntry {
587
588
  readonly chatId: ChatId
588
589
  readonly sequence: number
589
- readonly at: number
590
+ readonly at: DateTime.Utc
590
591
  readonly event: { readonly _tag: string }
591
592
  }
592
593
 
593
594
  /**
594
595
  * Schema for a stored event with its position in the chat.
595
596
  *
596
- * `sequence` starts at 1 and has no gaps. `at` is the time the event was stored, in epoch
597
- * milliseconds.
597
+ * `sequence` starts at 1 and has no gaps. `at` is the time the event was stored, a UTC
598
+ * `DateTime` that encodes as epoch milliseconds.
598
599
  *
599
600
  * @category schemas
600
601
  * @since 0.1.0
@@ -602,7 +603,7 @@ export interface AnyEntry {
602
603
  export const Entry = Schema.Struct({
603
604
  chatId: ChatId,
604
605
  sequence: Schema.Int,
605
- at: Schema.Finite,
606
+ at: Schema.DateTimeUtcFromMillis,
606
607
  event: Schema.Union([AssistantEvent, StoredAppEvent])
607
608
  })
608
609
 
package/src/ChatLog.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  *
9
9
  * @since 0.1.0
10
10
  */
11
- import * as Clock from "effect/Clock"
12
11
  import * as Context from "effect/Context"
12
+ import * as DateTime from "effect/DateTime"
13
13
  import * as Effect from "effect/Effect"
14
14
  import * as Layer from "effect/Layer"
15
15
  import * as Predicate from "effect/Predicate"
@@ -89,7 +89,7 @@ export const make = (storage: Storage): ChatLog["Service"] =>
89
89
  if (events.length === 0) return []
90
90
 
91
91
  const sequence = yield* storage.lastSequence(chatId)
92
- const at = yield* Clock.currentTimeMillis
92
+ const at = yield* DateTime.now
93
93
 
94
94
  const entries = events.map((event, n) =>
95
95
  AssistantEvent.Entry.make({ chatId, sequence: sequence + n + 1, at, event })
@@ -228,7 +228,7 @@ export const layerSql = (options?: SqlOptions): Layer.Layer<ChatLog, never, SqlC
228
228
  AssistantEvent.Entry.make({
229
229
  chatId: row.chat_id,
230
230
  sequence: row.sequence,
231
- at: row.at,
231
+ at: DateTime.makeUnsafe(row.at),
232
232
  event: row.event
233
233
  })
234
234
  )
@@ -259,7 +259,7 @@ export const layerSql = (options?: SqlOptions): Layer.Layer<ChatLog, never, SqlC
259
259
  Effect.fnUntraced(function* (entry: AssistantEvent.Entry) {
260
260
  const event = yield* encodeEvent(entry.event)
261
261
 
262
- return { chat_id: chatId, sequence: entry.sequence, at: entry.at, event }
262
+ return { chat_id: chatId, sequence: entry.sequence, at: DateTime.toEpochMillis(entry.at), event }
263
263
  })
264
264
  )
265
265
 
package/src/Timeline.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  *
19
19
  * @since 0.3.0
20
20
  */
21
+ import * as DateTime from "effect/DateTime"
21
22
  import { dual } from "effect/Function"
22
23
  import * as Match from "effect/Match"
23
24
  import * as Option from "effect/Option"
@@ -66,8 +67,8 @@ export const Block = Schema.Struct({
66
67
  props: Schema.Json,
67
68
  status: BlockStatus,
68
69
  answer: Schema.optional(Schema.Json),
69
- /** When the user answered, in epoch milliseconds, once the block is answered. */
70
- answeredAt: Schema.optional(Schema.Finite),
70
+ /** When the user answered, once the block is answered. Encodes as epoch milliseconds. */
71
+ answeredAt: Schema.optional(Schema.DateTimeUtcFromMillis),
71
72
  /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
72
73
  result: Schema.optional(Schema.Json)
73
74
  })
@@ -81,8 +82,8 @@ export const Block = Schema.Struct({
81
82
  export type Block = typeof Block.Type
82
83
 
83
84
  /**
84
- * Schema for a message the user sent. `at` is when it was stored, in epoch
85
- * milliseconds.
85
+ * Schema for a message the user sent. `at` is when it was stored, a UTC `DateTime` that encodes
86
+ * as epoch milliseconds.
86
87
  *
87
88
  * @category schemas
88
89
  * @since 0.1.0
@@ -91,7 +92,7 @@ export const UserMessage = Schema.TaggedStruct("UserMessage", {
91
92
  id: InputId,
92
93
  text: Schema.String,
93
94
  attachments: Schema.optional(Schema.Array(AssistantEvent.Attachment)),
94
- at: Schema.Finite
95
+ at: Schema.DateTimeUtcFromMillis
95
96
  })
96
97
 
97
98
  /**
@@ -103,7 +104,8 @@ export const UserMessage = Schema.TaggedStruct("UserMessage", {
103
104
  export type UserMessage = typeof UserMessage.Type
104
105
 
105
106
  /**
106
- * Schema for a message the assistant sent the user, including its block if it has one.
107
+ * Schema for a message the assistant sent the user, including its block if it has one. `at` is
108
+ * when it was stored, a UTC `DateTime` that encodes as epoch milliseconds.
107
109
  *
108
110
  * @category schemas
109
111
  * @since 0.1.0
@@ -111,7 +113,7 @@ export type UserMessage = typeof UserMessage.Type
111
113
  export const AssistantMessage = Schema.TaggedStruct("AssistantMessage", {
112
114
  id: Schema.String,
113
115
  text: Schema.String,
114
- at: Schema.Finite,
116
+ at: Schema.DateTimeUtcFromMillis,
115
117
  block: Schema.optional(Block)
116
118
  })
117
119
 
@@ -133,13 +135,14 @@ export type AssistantMessage = typeof AssistantMessage.Type
133
135
  * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,
134
136
  * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or
135
137
  * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the
136
- * chat's log, and `at` is when the event was stored, in epoch milliseconds.
138
+ * chat's log, and `at` is when the event was stored, a UTC `DateTime` that encodes as epoch
139
+ * milliseconds.
137
140
  *
138
141
  * @category models
139
142
  * @since 0.3.0
140
143
  */
141
144
  export type EventItem<E> = E extends { readonly _tag: infer Tag extends string }
142
- ? { readonly _tag: Tag; readonly id: string; readonly at: number; readonly event: E }
145
+ ? { readonly _tag: Tag; readonly id: string; readonly at: DateTime.Utc; readonly event: E }
143
146
  : never
144
147
 
145
148
  /**
@@ -152,8 +155,8 @@ export type EventItem<E> = E extends { readonly _tag: infer Tag extends string }
152
155
  * approve, so the item carries no params. `id` is the call's id, which the decision is for (see
153
156
  * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands
154
157
  * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how
155
- * the approved call went, once it ran. `at` is when the call started waiting, in epoch
156
- * milliseconds. A change updates the item in place as the call is decided and run.
158
+ * the approved call went, once it ran. `at` is when the call started waiting, a UTC `DateTime` that
159
+ * encodes as epoch milliseconds. A change updates the item in place as the call is decided and run.
157
160
  *
158
161
  * @category schemas
159
162
  * @since 0.4.0
@@ -164,7 +167,7 @@ export const ApprovalItem = Schema.TaggedStruct("ToolApproval", {
164
167
  status: Schema.Literals(["pending", "approved", "rejected", "expired"]),
165
168
  reason: Schema.optional(Schema.String),
166
169
  outcome: Schema.optional(AssistantEvent.ToolOutcome),
167
- at: Schema.Finite
170
+ at: Schema.DateTimeUtcFromMillis
168
171
  })
169
172
 
170
173
  /**
@@ -205,14 +208,14 @@ export type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Ev
205
208
 
206
209
  /**
207
210
  * Schema for a specialist that is working for the assistant. It holds the specialist's name and
208
- * when it started, in epoch milliseconds.
211
+ * when it started, a UTC `DateTime` that encodes as epoch milliseconds.
209
212
  *
210
213
  * @category schemas
211
214
  * @since 0.1.0
212
215
  */
213
216
  export const SpecialistWorking = Schema.Struct({
214
217
  specialist: Schema.String,
215
- since: Schema.Finite
218
+ since: Schema.DateTimeUtcFromMillis
216
219
  })
217
220
 
218
221
  /**
@@ -293,7 +296,12 @@ export interface Change<Events = never> {
293
296
  }
294
297
 
295
298
  const eventItem = (schema: AssistantEvent.AppEventSchema) =>
296
- Schema.Struct({ _tag: Schema.Literal(AppEvents.tagOf(schema)), id: Schema.String, at: Schema.Finite, event: schema })
299
+ Schema.Struct({
300
+ _tag: Schema.Literal(AppEvents.tagOf(schema)),
301
+ id: Schema.String,
302
+ at: Schema.DateTimeUtcFromMillis,
303
+ event: schema
304
+ })
297
305
 
298
306
  function makeChange<const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(
299
307
  events?: Events
@@ -467,7 +475,7 @@ export const isIdle = <Events>(timeline: Timeline<Events>): boolean =>
467
475
  interface AnyEventItem {
468
476
  readonly _tag: string
469
477
  readonly id: string
470
- readonly at: number
478
+ readonly at: DateTime.Utc
471
479
  readonly event: { readonly _tag: string }
472
480
  }
473
481
 
@@ -652,7 +660,7 @@ const sameActivity = (a: Activity, b: Activity) =>
652
660
  a.specialists.every((run, i) => {
653
661
  const other = b.specialists[i]
654
662
 
655
- return other !== undefined && run.specialist === other.specialist && run.since === other.since
663
+ return other !== undefined && run.specialist === other.specialist && DateTime.Equivalence(run.since, other.since)
656
664
  })
657
665
 
658
666
  const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding => {
@@ -664,7 +672,7 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
664
672
  let activity = AssistantActivity.empty
665
673
  let live = noLive
666
674
  let blocks: ReadonlyMap<string, BlockKit.State> = new Map()
667
- const answeredAt = new Map<string, number>()
675
+ const answeredAt = new Map<string, DateTime.Utc>()
668
676
  // The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.
669
677
  const items = new Map<string, AnyItem>()
670
678
  const sent = new Map<string, AssistantEvent.AssistantMessage>()
@@ -689,7 +697,7 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
689
697
  return at === undefined ? answered : { ...answered, answeredAt: at }
690
698
  }
691
699
 
692
- const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {
700
+ const itemOf = (message: AssistantEvent.AssistantMessage, at: DateTime.Utc): AssistantMessage => {
693
701
  const block = blockOf(message)
694
702
 
695
703
  return block === undefined
@@ -697,7 +705,7 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
697
705
  : AssistantMessage.make({ id: message.id, text: message.text, at, block })
698
706
  }
699
707
 
700
- const touched = (event: AssistantEvent.AssistantEvent, at: number): ReadonlyArray<string> =>
708
+ const touched = (event: AssistantEvent.AssistantEvent, at: DateTime.Utc): ReadonlyArray<string> =>
701
709
  Match.value(event).pipe(
702
710
  Match.tagsExhaustive({
703
711
  UserMessage: (message) => {
@@ -11,6 +11,7 @@
11
11
  *
12
12
  * @since 0.4.0
13
13
  */
14
+ import type * as DateTime from "effect/DateTime"
14
15
  import * as Effect from "effect/Effect"
15
16
  import * as Predicate from "effect/Predicate"
16
17
  import * as AssistantEvent from "./AssistantEvent.ts"
@@ -34,8 +35,8 @@ export type Status = "pending" | "approved" | "rejected" | "expired"
34
35
  */
35
36
  export interface State {
36
37
  readonly request: AssistantEvent.ApprovalRequested
37
- /** When the call started waiting, in epoch milliseconds. */
38
- readonly at: number
38
+ /** When the call started waiting. */
39
+ readonly at: DateTime.Utc
39
40
  readonly status: Status
40
41
  /** The user's reason, when they rejected it with one. */
41
42
  readonly reason: string | undefined
@@ -1,5 +1,7 @@
1
1
  import * as Prompt from "effect/ai/Prompt"
2
2
  import * as Response from "effect/ai/Response"
3
+ import * as DateTime from "effect/DateTime"
4
+ import * as Duration from "effect/Duration"
3
5
  import * as Match from "effect/Match"
4
6
  import * as Option from "effect/Option"
5
7
  import * as Predicate from "effect/Predicate"
@@ -61,8 +63,8 @@ export const notRunOutput = "Not run: the turn ended before this call ran."
61
63
  export const mayHaveRunOutput =
62
64
  "Stopped: the turn ended while this call ran. It may have done its work; check before doing it again."
63
65
 
64
- const ago = (millis: number) => {
65
- const seconds = Math.max(0, Math.round(millis / 1000))
66
+ const ago = (duration: Duration.Duration) => {
67
+ const seconds = Math.max(0, Math.round(Duration.toSeconds(duration)))
66
68
 
67
69
  return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`
68
70
  }
@@ -88,7 +90,7 @@ const finishedText = (
88
90
  "A report from a specialist you started. The user hasn't seen it.",
89
91
  started === undefined
90
92
  ? `You started it for: ${finished.goal}`
91
- : `You started it ${ago(at.at - started.at)} ago for: ${finished.goal}`,
93
+ : `You started it ${ago(DateTime.distance(started.at, at.at))} ago for: ${finished.goal}`,
92
94
  wrote ? "The user has written since you started it." : "The user hasn't written since you started it.",
93
95
  Match.value(finished.status).pipe(
94
96
  Match.when("answered", () => `Report:\n${finished.report ?? ""}`),