effect-assistant 0.14.0 → 0.16.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 +2 -1
  2. package/dist/Assistant.d.ts.map +1 -1
  3. package/dist/Assistant.js +1 -1
  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/AssistantEvent.d.ts +5 -4
  10. package/dist/AssistantEvent.d.ts.map +1 -1
  11. package/dist/AssistantEvent.js +3 -3
  12. package/dist/AssistantEvent.js.map +1 -1
  13. package/dist/ChatLog.js +4 -4
  14. package/dist/ChatLog.js.map +1 -1
  15. package/dist/Memory.d.ts +1 -1
  16. package/dist/Memory.js +2 -2
  17. package/dist/StatusSummary.d.ts +1 -1
  18. package/dist/StatusSummary.js +1 -1
  19. package/dist/Timeline.d.ts +20 -17
  20. package/dist/Timeline.d.ts.map +1 -1
  21. package/dist/Timeline.js +16 -14
  22. package/dist/Timeline.js.map +1 -1
  23. package/dist/ToolApproval.d.ts +3 -2
  24. package/dist/ToolApproval.d.ts.map +1 -1
  25. package/dist/ToolApproval.js +0 -13
  26. package/dist/ToolApproval.js.map +1 -1
  27. package/dist/ToolStatus.d.ts +32 -29
  28. package/dist/ToolStatus.d.ts.map +1 -1
  29. package/dist/ToolStatus.js +42 -27
  30. package/dist/ToolStatus.js.map +1 -1
  31. package/dist/internal/history.js +5 -3
  32. package/dist/internal/history.js.map +1 -1
  33. package/dist/internal/live.js +1 -1
  34. package/dist/internal/loop.d.ts.map +1 -1
  35. package/dist/internal/loop.js +6 -27
  36. package/dist/internal/loop.js.map +1 -1
  37. package/dist/internal/summary.js +1 -1
  38. package/package.json +1 -1
  39. package/src/Assistant.ts +3 -2
  40. package/src/AssistantActivity.ts +5 -4
  41. package/src/AssistantEvent.ts +5 -4
  42. package/src/ChatLog.ts +4 -4
  43. package/src/Timeline.ts +28 -20
  44. package/src/ToolApproval.ts +3 -2
  45. package/src/ToolStatus.ts +66 -41
  46. package/src/internal/history.ts +5 -3
  47. package/src/internal/loop.ts +14 -53
@@ -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.16.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
package/src/ToolStatus.ts CHANGED
@@ -2,25 +2,18 @@
2
2
  * This module provides status labels for tool calls: while a call runs, the chat shows the user a
3
3
  * short line about what the assistant is doing, like "Checking last summer's campaign budget".
4
4
  *
5
- * Mark the tools that take a while or act on something with {@link described}: workflows, reports
6
- * from other systems, orders, specialists. The model then sees a required `description` parameter
7
- * on them and fills it in the chat's language. When the call starts, the chat sends the
8
- * description as a `ChatSignal.Status`; it shows until the next status, so it stays after the call
9
- * ends. The tool's handler never receives the parameter. Quick reads need no label: the chat shows its generic working state for
10
- * them.
5
+ * Give the tools that take a while or act on something a status field with {@link withStatus}:
6
+ * workflows, reports from other systems, orders, specialists. Their parameters get a required
7
+ * `description` field that the model fills in the chat's language. When the call starts, the chat
8
+ * sends the description as a `ChatSignal.Status`; it shows until the next status, so it stays
9
+ * after the call ends. The call runs unchanged: the handler gets `description` with its other
10
+ * parameters. Quick reads need no label: the chat shows its generic working state for them.
11
11
  *
12
12
  * @since 0.13.0
13
13
  */
14
14
  import type * as Tool from "effect/ai/Tool"
15
- import * as Context from "effect/Context"
16
- import type * as Schema from "effect/Schema"
17
-
18
- type Schemas = {
19
- readonly parameters: Schema.Constraint
20
- readonly success: Schema.Constraint
21
- readonly failure: Schema.Constraint
22
- readonly failureMode: Tool.FailureMode
23
- }
15
+ import * as Schema from "effect/Schema"
16
+ import * as SchemaAST from "effect/SchemaAST"
24
17
 
25
18
  /**
26
19
  * The name of the parameter the model fills with a call's status.
@@ -39,53 +32,85 @@ export const parameterName = "description"
39
32
  export const parameterDescription =
40
33
  "Shown to the user while this runs: 3 to 8 plain words in the user's language about what you're doing, like \"Checking last summer's campaign budget\". No tool names, ids or code."
41
34
 
35
+ const statusFieldKey = "effect-assistant/ToolStatus/statusField"
36
+
42
37
  /**
43
- * Annotation for whether a tool's calls show a status, set with {@link described}.
38
+ * The schema of the status field {@link withStatus} adds.
44
39
  *
45
- * @category annotations
46
- * @since 0.13.0
40
+ * @category schemas
41
+ * @since 0.16.0
47
42
  */
48
- export const Described = Context.Reference<boolean>("effect-assistant/ToolStatus/Described", {
49
- defaultValue: () => false
50
- })
43
+ export const StatusField = Schema.String.annotate({ description: parameterDescription, [statusFieldKey]: true })
51
44
 
52
45
  /**
53
- * Marks a tool whose calls show a status while they run.
46
+ * The parameter fields a struct can't have to take a status field: a `description` field of its own.
47
+ *
48
+ * @category models
49
+ * @since 0.16.0
50
+ */
51
+ export type WithoutStatus<Fields extends Schema.Struct.Fields> = typeof parameterName extends keyof Fields
52
+ ? "Error: these parameters have a description field already, so they can't take a status: rename it"
53
+ : unknown
54
+
55
+ /**
56
+ * Adds the status field to a tool's parameters, so its calls show a status while they run.
54
57
  *
55
58
  * **Details**
56
59
  *
57
- * The model sees a required `description` parameter on the tool, and the chat shows what it
58
- * writes there while the call runs. Required, because models leave optional parameters out; a call
59
- * without it still runs, with no status. The handler gets its parameters without it. A tool that has a
60
- * parameter of that name already can't be marked: the loop stops with a defect when it offers one.
60
+ * The struct gets a required `description` field ({@link StatusField}), and keeps its own
61
+ * annotations and checks. Required, because models leave optional parameters out. The chat shows
62
+ * what the model writes there while the call runs; a call with a blank one runs with no status,
63
+ * and a call without it fails validation like a call without any other required parameter. The
64
+ * handler gets `description` like any other parameter. A struct that has a `description` field
65
+ * already is a type error. A tool without parameters takes `Schema.Struct({})`.
61
66
  *
62
- * **Example** (A slow report with a status)
67
+ * **Example** (A tool whose calls show a status)
63
68
  *
64
69
  * ```ts
65
70
  * import { ToolStatus } from "effect-assistant"
66
71
  * import * as Tool from "effect/ai/Tool"
67
72
  * import * as Schema from "effect/Schema"
68
73
  *
69
- * export const CampaignReport = ToolStatus.described(
70
- * Tool.make("campaign_report", {
71
- * description: "The spend and results of a past campaign.",
72
- * parameters: Schema.Struct({ campaignId: Schema.String }),
73
- * success: Schema.Struct({ spent: Schema.Finite })
74
- * })
75
- * )
74
+ * export const ArchiveNote = Tool.make("archive_note", {
75
+ * description: "Archives a note and the files attached to it.",
76
+ * parameters: Schema.Struct({ noteId: Schema.String }).pipe(ToolStatus.withStatus),
77
+ * success: Schema.Struct({ archived: Schema.Boolean })
78
+ * })
76
79
  * ```
77
80
  *
78
- * @category annotations
79
- * @since 0.13.0
81
+ * @category combinators
82
+ * @since 0.16.0
80
83
  */
81
- export const described = <Name extends string, Config extends Schemas, R>(
82
- tool: Tool.Tool<Name, Config, R>
83
- ): Tool.Tool<Name, Config, R> => tool.annotate(Described, true)
84
+ export const withStatus = <Fields extends Schema.Struct.Fields>(
85
+ self: Schema.Struct<Fields> & WithoutStatus<Fields>
86
+ ) => {
87
+ const struct = self.mapFields((fields) => ({ ...fields, [parameterName]: StatusField }))
88
+
89
+ return struct.rebuild(
90
+ new SchemaAST.Objects(
91
+ struct.ast.propertySignatures,
92
+ struct.ast.indexSignatures,
93
+ self.ast.annotations,
94
+ self.ast.checks
95
+ )
96
+ )
97
+ }
84
98
 
85
99
  /**
86
- * Returns whether a tool's calls show a status.
100
+ * Returns whether a tool's calls show a status: its parameters have the field {@link withStatus}
101
+ * adds. A `description` parameter of its own doesn't count.
87
102
  *
88
103
  * @category guards
89
104
  * @since 0.13.0
90
105
  */
91
- export const isDescribed = (tool: Tool.Any): boolean => Context.get(tool.annotations, Described)
106
+ export const isDescribed = (tool: Tool.Any): boolean => {
107
+ const ast = tool.parametersSchema.ast
108
+
109
+ return (
110
+ SchemaAST.isObjects(ast) &&
111
+ ast.propertySignatures.some(
112
+ (property) =>
113
+ property.name === parameterName && SchemaAST.resolveAt<boolean>(statusFieldKey)(property.type) === true
114
+ )
115
+ )
116
+ }
@@ -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 ?? ""}`),
@@ -12,7 +12,6 @@ import * as Effect from "effect/Effect"
12
12
  import * as Option from "effect/Option"
13
13
  import * as Predicate from "effect/Predicate"
14
14
  import * as Schema from "effect/Schema"
15
- import * as SchemaAST from "effect/SchemaAST"
16
15
  import * as Stream from "effect/Stream"
17
16
  import * as AssistantEvent from "../AssistantEvent.ts"
18
17
  import type * as Instructions from "../Instructions.ts"
@@ -91,49 +90,14 @@ export interface StepResult {
91
90
  // every tool's params, `unknown` for a schema of unknown type, though deferred validation encodes none.
92
91
  type RequestTool = Tool.Tool<string, any, any>
93
92
 
94
- // Required in what the model reads, so it writes one with every call; a call without it still runs.
95
- const statusParameter = Schema.String.annotate({ description: ToolStatus.parameterDescription })
96
-
97
- // What the model reads of a described tool: its parameters with the status one. Only the request has it; the call
98
- // runs without it (see `withoutStatus`). A record of no keys (a tool without parameters) becomes an object with it.
99
- const withStatusParameter = (tool: Tool.Any): Tool.Any => {
100
- const ast = tool.parametersSchema.ast
101
-
102
- if (!ToolStatus.isDescribed(tool) || !SchemaAST.isObjects(ast)) return tool
103
-
104
- if (ast.propertySignatures.some((property) => property.name === ToolStatus.parameterName)) {
105
- throw new Error(
106
- `${tool.name} has a parameter named ${ToolStatus.parameterName} already, so it can't show a status: rename it.`
107
- )
108
- }
109
-
110
- const added = Schema.Struct({ [ToolStatus.parameterName]: statusParameter }).ast.propertySignatures
111
-
112
- return tool.setParameters(
113
- Schema.make<Schema.Top>(
114
- new SchemaAST.Objects(
115
- [...ast.propertySignatures, ...added],
116
- ast.indexSignatures.filter((index) => !SchemaAST.isNever(index.type)),
117
- ast.annotations
118
- )
119
- )
120
- )
121
- }
122
-
123
93
  // The loop runs the calls itself, after storing each as started, so the model call runs none. It also decides which
124
94
  // calls wait for approval: the model call would ask for approvals of its own.
125
95
  const requestToolkit = (definitions: ReadonlyArray<Tool.Any>): Toolkit.WithHandler<Record<string, RequestTool>> => ({
126
96
  tools: Object.fromEntries(
127
- definitions.map((tool) => {
128
- const requested = withStatusParameter(tool)
129
-
130
- return [
131
- tool.name,
132
- requested.needsApproval === undefined || requested.needsApproval === false
133
- ? requested
134
- : requested.setNeedsApproval(false)
135
- ]
136
- })
97
+ definitions.map((tool) => [
98
+ tool.name,
99
+ tool.needsApproval === undefined || tool.needsApproval === false ? tool : tool.setNeedsApproval(false)
100
+ ])
137
101
  ),
138
102
  handle: () => Effect.succeed(Stream.empty)
139
103
  })
@@ -181,26 +145,23 @@ const decodeParams = Schema.decodeUnknownOption(Schema.Record(Schema.String, Sch
181
145
  const isDescribedCall = <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) =>
182
146
  tools.definitions.some((tool) => tool.name === call.name && ToolStatus.isDescribed(tool))
183
147
 
184
- // The status the model wrote for a described tool's call, and the call as the tool's handler gets it.
185
- const splitStatus = (call: AssistantEvent.ToolCallPart): readonly [string | undefined, AssistantEvent.ToolCallPart] => {
186
- const params = decodeParams(call.params)
187
-
188
- if (Option.isNone(params) || !Object.hasOwn(params.value, ToolStatus.parameterName)) return [undefined, call]
189
-
190
- const { [ToolStatus.parameterName]: written, ...rest } = params.value
191
- const status = Predicate.isString(written) ? written.trim() : ""
192
-
193
- return [status === "" ? undefined : status, { ...call, params: rest }]
194
- }
148
+ const statusOf = (call: AssistantEvent.ToolCallPart): string | undefined =>
149
+ decodeParams(call.params).pipe(
150
+ Option.flatMapNullishOr((params) => params[ToolStatus.parameterName]),
151
+ Option.filter(Predicate.isString),
152
+ Option.map((written) => written.trim()),
153
+ Option.filter((status) => status !== ""),
154
+ Option.getOrUndefined
155
+ )
195
156
 
196
157
  // A call's status shows when it starts; a message's typing stops once the message is stored.
197
158
  const runCall = Effect.fnUntraced(function* <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) {
198
- const [status, run] = isDescribedCall(tools, call) ? splitStatus(call) : [undefined, call]
159
+ const status = isDescribedCall(tools, call) ? statusOf(call) : undefined
199
160
 
200
161
  const result = yield* Effect.gen(function* () {
201
162
  if (status !== undefined) yield* Live.use((live) => live.callStarted(call.id, status))
202
163
 
203
- const result = yield* tools.run(run)
164
+ const result = yield* tools.run(call)
204
165
 
205
166
  yield* Telemetry.toolOutput(result.result)
206
167