@plotday/twister 0.52.0 → 0.54.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 (219) hide show
  1. package/bin/commands/deploy.js +4 -0
  2. package/bin/commands/deploy.js.map +1 -1
  3. package/bin/templates/AGENTS.template.md +6 -10
  4. package/cli/templates/AGENTS.template.md +6 -10
  5. package/dist/connector.d.ts +179 -10
  6. package/dist/connector.d.ts.map +1 -1
  7. package/dist/connector.js +78 -4
  8. package/dist/connector.js.map +1 -1
  9. package/dist/docs/assets/hierarchy.js +1 -1
  10. package/dist/docs/assets/navigation.js +1 -1
  11. package/dist/docs/assets/search.js +1 -1
  12. package/dist/docs/classes/index.Connector.html +74 -26
  13. package/dist/docs/classes/index.FileNotFoundError.html +2 -0
  14. package/dist/docs/classes/index.Files.html +16 -0
  15. package/dist/docs/classes/index.Imap.html +1 -1
  16. package/dist/docs/classes/index.Options.html +1 -1
  17. package/dist/docs/classes/index.Smtp.html +1 -1
  18. package/dist/docs/classes/tool.ITool.html +1 -1
  19. package/dist/docs/classes/tools_ai.AI.html +7 -5
  20. package/dist/docs/classes/tools_callbacks.Callbacks.html +1 -1
  21. package/dist/docs/classes/tools_integrations.Integrations.html +17 -23
  22. package/dist/docs/classes/tools_network.Network.html +1 -1
  23. package/dist/docs/classes/tools_plot.Plot.html +62 -56
  24. package/dist/docs/classes/tools_store.Store.html +1 -1
  25. package/dist/docs/classes/tools_tasks.Tasks.html +1 -1
  26. package/dist/docs/classes/tools_twists.Twists.html +2 -2
  27. package/dist/docs/classes/twist.Twist.html +3 -3
  28. package/dist/docs/documents/Building_Connectors.html +1 -1
  29. package/dist/docs/enums/plot.ActionType.html +10 -8
  30. package/dist/docs/enums/plot.ActorType.html +4 -4
  31. package/dist/docs/enums/plot.ConferencingProvider.html +6 -6
  32. package/dist/docs/enums/plot.ThemeColor.html +10 -10
  33. package/dist/docs/enums/tag.Tag.html +16 -46
  34. package/dist/docs/enums/tools_ai.AIModel.html +2 -2
  35. package/dist/docs/enums/tools_integrations.AuthProvider.html +13 -13
  36. package/dist/docs/enums/{tools_plot.PriorityAccess.html → tools_plot.FocusAccess.html} +6 -6
  37. package/dist/docs/enums/tools_plot.ThreadAccess.html +1 -1
  38. package/dist/docs/hierarchy.html +1 -1
  39. package/dist/docs/interfaces/tools_ai.AIRequest.html +27 -11
  40. package/dist/docs/interfaces/tools_ai.AIResponse.html +9 -9
  41. package/dist/docs/interfaces/tools_ai.FilePart.html +5 -5
  42. package/dist/docs/interfaces/tools_ai.ImagePart.html +4 -4
  43. package/dist/docs/interfaces/tools_ai.ReasoningPart.html +4 -4
  44. package/dist/docs/interfaces/tools_ai.RedactedReasoningPart.html +3 -3
  45. package/dist/docs/interfaces/tools_ai.TextPart.html +3 -3
  46. package/dist/docs/interfaces/tools_ai.ToolCallPart.html +5 -5
  47. package/dist/docs/interfaces/tools_ai.ToolExecutionOptions.html +4 -4
  48. package/dist/docs/interfaces/tools_ai.ToolResultPart.html +5 -5
  49. package/dist/docs/media/AGENTS.md +22 -14
  50. package/dist/docs/modules/index.html +1 -1
  51. package/dist/docs/modules/plot.html +1 -1
  52. package/dist/docs/modules/tools_integrations.html +1 -1
  53. package/dist/docs/modules/tools_plot.html +1 -1
  54. package/dist/docs/types/index.CreateLinkDraft.html +31 -7
  55. package/dist/docs/types/index.NoteWriteBackResult.html +3 -3
  56. package/dist/docs/types/index.ReactionCapabilities.html +17 -0
  57. package/dist/docs/types/index.ResolvedRecipient.html +24 -0
  58. package/dist/docs/types/index.Schedule.html +1 -1
  59. package/dist/docs/types/plot.Action.html +9 -2
  60. package/dist/docs/types/plot.Actor.html +5 -5
  61. package/dist/docs/types/plot.ActorId.html +1 -1
  62. package/dist/docs/types/plot.Contact.html +4 -4
  63. package/dist/docs/types/plot.ContentType.html +1 -1
  64. package/dist/docs/types/{plot.Priority.html → plot.Focus.html} +14 -11
  65. package/dist/docs/types/plot.FocusUpdate.html +3 -0
  66. package/dist/docs/types/plot.Link.html +16 -16
  67. package/dist/docs/types/plot.LinkUpdate.html +1 -1
  68. package/dist/docs/types/plot.NewActor.html +1 -1
  69. package/dist/docs/types/plot.NewContact.html +1 -1
  70. package/dist/docs/types/plot.NewFocus.html +13 -0
  71. package/dist/docs/types/plot.NewLink.html +6 -6
  72. package/dist/docs/types/plot.NewLinkWithNotes.html +1 -1
  73. package/dist/docs/types/plot.NewNote.html +5 -3
  74. package/dist/docs/types/plot.NewReactions.html +4 -0
  75. package/dist/docs/types/plot.NewTags.html +1 -1
  76. package/dist/docs/types/plot.NewThread.html +6 -4
  77. package/dist/docs/types/plot.NewThreadWithNotes.html +1 -1
  78. package/dist/docs/types/plot.Note.html +2 -2
  79. package/dist/docs/types/plot.NoteUpdate.html +4 -2
  80. package/dist/docs/types/plot.PlanOperation.html +6 -6
  81. package/dist/docs/types/plot.Reaction.html +13 -0
  82. package/dist/docs/types/plot.Reactions.html +3 -0
  83. package/dist/docs/types/plot.Tags.html +1 -1
  84. package/dist/docs/types/plot.Thread.html +1 -1
  85. package/dist/docs/types/plot.ThreadAccessLevel.html +3 -3
  86. package/dist/docs/types/plot.ThreadCommon.html +9 -5
  87. package/dist/docs/types/plot.ThreadFilter.html +2 -2
  88. package/dist/docs/types/plot.ThreadMeta.html +1 -1
  89. package/dist/docs/types/plot.ThreadType.html +4 -4
  90. package/dist/docs/types/plot.ThreadUpdate.html +1 -1
  91. package/dist/docs/types/plot.ThreadWithNotes.html +1 -1
  92. package/dist/docs/types/tools_ai.AIAssistantMessage.html +2 -2
  93. package/dist/docs/types/tools_ai.AICapabilities.html +7 -3
  94. package/dist/docs/types/tools_ai.AIMessage.html +1 -1
  95. package/dist/docs/types/tools_ai.AIOptions.html +2 -2
  96. package/dist/docs/types/tools_ai.AISource.html +1 -1
  97. package/dist/docs/types/tools_ai.AISystemMessage.html +2 -2
  98. package/dist/docs/types/tools_ai.AITool.html +10 -9
  99. package/dist/docs/types/tools_ai.AIToolMessage.html +2 -2
  100. package/dist/docs/types/tools_ai.AIToolSet.html +1 -1
  101. package/dist/docs/types/tools_ai.AIUsage.html +5 -5
  102. package/dist/docs/types/tools_ai.AIUserMessage.html +2 -2
  103. package/dist/docs/types/tools_ai.DataContent.html +1 -1
  104. package/dist/docs/types/tools_ai.ModelPreferences.html +4 -4
  105. package/dist/docs/types/tools_integrations.ArchiveLinkFilter.html +5 -5
  106. package/dist/docs/types/tools_integrations.AuthToken.html +4 -4
  107. package/dist/docs/types/tools_integrations.Authorization.html +4 -4
  108. package/dist/docs/types/tools_integrations.Channel.html +5 -5
  109. package/dist/docs/types/tools_integrations.ComposeConfig.html +35 -0
  110. package/dist/docs/types/tools_integrations.ContactRoleConfig.html +14 -0
  111. package/dist/docs/types/tools_integrations.LinkTypeConfig.html +55 -28
  112. package/dist/docs/types/tools_integrations.SyncContext.html +3 -3
  113. package/dist/docs/types/tools_plot.SearchOptions.html +5 -6
  114. package/dist/docs/types/tools_twists.TwistPermissions.html +1 -1
  115. package/dist/llm-docs/connector.d.ts +1 -1
  116. package/dist/llm-docs/connector.d.ts.map +1 -1
  117. package/dist/llm-docs/connector.js +1 -1
  118. package/dist/llm-docs/connector.js.map +1 -1
  119. package/dist/llm-docs/index.d.ts.map +1 -1
  120. package/dist/llm-docs/index.js +2 -0
  121. package/dist/llm-docs/index.js.map +1 -1
  122. package/dist/llm-docs/plot.d.ts +1 -1
  123. package/dist/llm-docs/plot.d.ts.map +1 -1
  124. package/dist/llm-docs/plot.js +1 -1
  125. package/dist/llm-docs/plot.js.map +1 -1
  126. package/dist/llm-docs/schedule.d.ts +1 -1
  127. package/dist/llm-docs/schedule.d.ts.map +1 -1
  128. package/dist/llm-docs/schedule.js +1 -1
  129. package/dist/llm-docs/schedule.js.map +1 -1
  130. package/dist/llm-docs/tag.d.ts +1 -1
  131. package/dist/llm-docs/tag.d.ts.map +1 -1
  132. package/dist/llm-docs/tag.js +1 -1
  133. package/dist/llm-docs/tag.js.map +1 -1
  134. package/dist/llm-docs/tools/ai.d.ts +1 -1
  135. package/dist/llm-docs/tools/ai.d.ts.map +1 -1
  136. package/dist/llm-docs/tools/ai.js +1 -1
  137. package/dist/llm-docs/tools/ai.js.map +1 -1
  138. package/dist/llm-docs/tools/files.d.ts +9 -0
  139. package/dist/llm-docs/tools/files.d.ts.map +1 -0
  140. package/dist/llm-docs/tools/files.js +8 -0
  141. package/dist/llm-docs/tools/files.js.map +1 -0
  142. package/dist/llm-docs/tools/integrations.d.ts +1 -1
  143. package/dist/llm-docs/tools/integrations.d.ts.map +1 -1
  144. package/dist/llm-docs/tools/integrations.js +1 -1
  145. package/dist/llm-docs/tools/integrations.js.map +1 -1
  146. package/dist/llm-docs/tools/plot.d.ts +1 -1
  147. package/dist/llm-docs/tools/plot.d.ts.map +1 -1
  148. package/dist/llm-docs/tools/plot.js +1 -1
  149. package/dist/llm-docs/tools/plot.js.map +1 -1
  150. package/dist/llm-docs/tools/twists.d.ts +1 -1
  151. package/dist/llm-docs/tools/twists.d.ts.map +1 -1
  152. package/dist/llm-docs/tools/twists.js +1 -1
  153. package/dist/llm-docs/tools/twists.js.map +1 -1
  154. package/dist/llm-docs/twist-guide-template.d.ts +1 -1
  155. package/dist/llm-docs/twist-guide-template.d.ts.map +1 -1
  156. package/dist/llm-docs/twist-guide-template.js +1 -1
  157. package/dist/llm-docs/twist-guide-template.js.map +1 -1
  158. package/dist/llm-docs/twist.d.ts +1 -1
  159. package/dist/llm-docs/twist.d.ts.map +1 -1
  160. package/dist/llm-docs/twist.js +1 -1
  161. package/dist/llm-docs/twist.js.map +1 -1
  162. package/dist/plot.d.ts +146 -85
  163. package/dist/plot.d.ts.map +1 -1
  164. package/dist/plot.js +3 -1
  165. package/dist/plot.js.map +1 -1
  166. package/dist/schedule.d.ts +1 -1
  167. package/dist/tag.d.ts +17 -43
  168. package/dist/tag.d.ts.map +1 -1
  169. package/dist/tag.js +17 -46
  170. package/dist/tag.js.map +1 -1
  171. package/dist/tools/ai.d.ts +46 -10
  172. package/dist/tools/ai.d.ts.map +1 -1
  173. package/dist/tools/ai.js.map +1 -1
  174. package/dist/tools/files.d.ts +33 -0
  175. package/dist/tools/files.d.ts.map +1 -0
  176. package/dist/tools/files.js +22 -0
  177. package/dist/tools/files.js.map +1 -0
  178. package/dist/tools/index.d.ts +1 -0
  179. package/dist/tools/index.d.ts.map +1 -1
  180. package/dist/tools/index.js +1 -0
  181. package/dist/tools/index.js.map +1 -1
  182. package/dist/tools/integrations.d.ts +130 -50
  183. package/dist/tools/integrations.d.ts.map +1 -1
  184. package/dist/tools/integrations.js.map +1 -1
  185. package/dist/tools/plot.d.ts +66 -56
  186. package/dist/tools/plot.d.ts.map +1 -1
  187. package/dist/tools/plot.js +14 -14
  188. package/dist/tools/plot.js.map +1 -1
  189. package/dist/tools/twists.d.ts +2 -2
  190. package/dist/twist-guide.d.ts +1 -1
  191. package/dist/twist-guide.d.ts.map +1 -1
  192. package/dist/twist.d.ts +3 -3
  193. package/dist/twist.js +3 -3
  194. package/package.json +6 -1
  195. package/src/connector.ts +182 -10
  196. package/src/llm-docs/connector.ts +1 -1
  197. package/src/llm-docs/index.ts +2 -0
  198. package/src/llm-docs/plot.ts +1 -1
  199. package/src/llm-docs/schedule.ts +1 -1
  200. package/src/llm-docs/tag.ts +1 -1
  201. package/src/llm-docs/tools/ai.ts +1 -1
  202. package/src/llm-docs/tools/files.ts +8 -0
  203. package/src/llm-docs/tools/integrations.ts +1 -1
  204. package/src/llm-docs/tools/plot.ts +1 -1
  205. package/src/llm-docs/tools/twists.ts +1 -1
  206. package/src/llm-docs/twist-guide-template.ts +1 -1
  207. package/src/llm-docs/twist.ts +1 -1
  208. package/src/plot.ts +156 -75
  209. package/src/schedule.ts +1 -1
  210. package/src/tag.ts +17 -48
  211. package/src/tools/ai.ts +46 -10
  212. package/src/tools/files.ts +37 -0
  213. package/src/tools/index.ts +1 -0
  214. package/src/tools/integrations.ts +131 -61
  215. package/src/tools/plot.ts +69 -59
  216. package/src/tools/twists.ts +2 -2
  217. package/src/twist.ts +3 -3
  218. package/dist/docs/types/plot.NewPriority.html +0 -15
  219. package/dist/docs/types/plot.PriorityUpdate.html +0 -5
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import { type Tag } from \"./tag\";\nimport {\n type Actor,\n type ActorId,\n type NewActor,\n type NewTags,\n type Tags,\n} from \"./plot\";\nimport { Uuid } from \"./utils/uuid\";\n\nexport { Uuid } from \"./utils/uuid\";\n\n/**\n * Represents a schedule entry for a thread.\n *\n * Schedules define when a thread occurs in time. A thread may have zero or more schedules:\n * - Shared schedules (userId is null): visible to all members of the thread's priority\n * - Per-user schedules (userId set): private ordering/scheduling for a specific user\n *\n * For recurring events in the SDK, start/end represent the first occurrence's\n * time. In the database, the `at`/`on` range is expanded to span from the first\n * occurrence start to the last occurrence end (or open-ended if no fixed end).\n * The `duration` column stores the per-occurrence duration, enabling range overlap\n * queries to correctly find all recurring events with occurrences in a given window.\n */\nexport type Schedule = {\n /** When this schedule was created */\n created: Date;\n /** Whether this schedule has been archived */\n archived: boolean;\n /** If set, this is a per-user schedule visible only to this user */\n userId: ActorId | null;\n /** Per-user ordering within a day (only set for per-user schedules) */\n order: number | null;\n /**\n * Start time of the schedule.\n * Date object for timed events, date string in \"YYYY-MM-DD\" format for all-day events.\n */\n start: Date | string | null;\n /**\n * End time of the schedule.\n * Date object for timed events, date string in \"YYYY-MM-DD\" format for all-day events.\n */\n end: Date | string | null;\n /** Recurrence rule in RFC 5545 RRULE format (e.g., \"FREQ=WEEKLY;BYDAY=MO,WE,FR\") */\n recurrenceRule: string | null;\n /** Duration of each occurrence in milliseconds (required for recurring schedules) */\n duration: number | null;\n /** Array of dates to exclude from the recurrence pattern */\n recurrenceExdates: Date[] | null;\n /**\n * For occurrence exceptions: the original date/time of this occurrence in the series.\n * Format: Date object or \"YYYY-MM-DD\" for all-day events.\n */\n occurrence: Date | string | null;\n /** Contacts invited to this schedule (attendees/participants) */\n contacts: ScheduleContact[];\n};\n\nexport type ScheduleContactStatus = \"attend\" | \"skip\";\nexport type ScheduleContactRole = \"organizer\" | \"required\" | \"optional\";\n\nexport type ScheduleContact = {\n contact: Actor;\n status: ScheduleContactStatus | null;\n role: ScheduleContactRole;\n archived: boolean;\n};\n\nexport type NewScheduleContact = {\n contact: NewActor;\n status?: ScheduleContactStatus | null;\n role?: ScheduleContactRole | null;\n archived?: boolean;\n};\n\n/**\n * Type for creating new schedules.\n *\n * Requires `threadId` and `start`. All other fields are optional.\n *\n * @example\n * ```typescript\n * // Simple timed event\n * const schedule: NewSchedule = {\n * threadId: threadId,\n * start: new Date(\"2025-03-15T10:00:00Z\"),\n * end: new Date(\"2025-03-15T11:00:00Z\")\n * };\n *\n * // All-day event\n * const allDay: NewSchedule = {\n * threadId: threadId,\n * start: \"2025-03-15\",\n * end: \"2025-03-16\"\n * };\n *\n * // Recurring weekly event\n * const recurring: NewSchedule = {\n * threadId: threadId,\n * start: new Date(\"2025-01-20T14:00:00Z\"),\n * end: new Date(\"2025-01-20T15:00:00Z\"),\n * recurrenceRule: \"FREQ=WEEKLY;BYDAY=MO\",\n * recurrenceUntil: new Date(\"2025-06-30\")\n * };\n * ```\n */\nexport type NewSchedule = {\n /** The thread this schedule belongs to */\n threadId: Uuid;\n /**\n * Start time. Date for timed events, \"YYYY-MM-DD\" for all-day.\n * Determines whether the schedule uses `at` (timed) or `on` (all-day) storage.\n */\n start: Date | string;\n /** End time. Date for timed events, \"YYYY-MM-DD\" for all-day. */\n end?: Date | string | null;\n /** Recurrence rule in RFC 5545 RRULE format */\n recurrenceRule?: string | null;\n /**\n * For recurring schedules, the last occurrence date (inclusive).\n * When both recurrenceCount and recurrenceUntil are provided, recurrenceCount takes precedence.\n */\n recurrenceUntil?: Date | string | null;\n /**\n * For recurring schedules, the number of occurrences to generate.\n * Takes precedence over recurrenceUntil if both are provided.\n */\n recurrenceCount?: number | null;\n /** Array of dates to exclude from the recurrence pattern */\n recurrenceExdates?: Date[] | null;\n /**\n * For occurrence exceptions: the original date/time of this occurrence.\n */\n occurrence?: Date | string | null;\n /** If set, this is a per-user schedule for the specified user */\n userId?: ActorId | null;\n /** Per-user ordering (only valid with userId) */\n order?: number | null;\n /** Whether to archive this schedule */\n archived?: boolean;\n /** Contacts to upsert on this schedule. Upserted by contact identity. */\n contacts?: NewScheduleContact[];\n};\n\n/**\n * Represents a specific instance of a recurring schedule.\n * All field values are computed by merging the recurring schedule's\n * defaults with any occurrence-specific overrides.\n */\nexport type ScheduleOccurrence = {\n /**\n * Original date/datetime of this occurrence.\n * Use start for the occurrence's current start time.\n */\n occurrence: Date | string;\n\n /** The recurring schedule of which this is an occurrence */\n schedule: Schedule;\n\n /** Effective start for this occurrence (series default + override) */\n start: Date | string;\n /** Effective end for this occurrence */\n end: Date | string | null;\n\n /** Tags for this occurrence */\n tags: Tags;\n};\n\n/**\n * Type for creating or updating schedule occurrences.\n *\n * Use `cancelled: true` to skip a single date in a recurring series\n * (e.g. an upstream calendar reports one occurrence as cancelled).\n * Internally this is translated into an addition to the parent\n * schedule's `recurrenceExdates`; no occurrence schedule row is\n * persisted for the cancelled date. For seeding the full exception\n * list on the master at initial sync, use `NewSchedule.recurrenceExdates`\n * instead.\n *\n * Use a normal occurrence record (without `cancelled`) for genuine\n * overrides — time changes, RSVP differences, etc.\n */\nexport type NewScheduleOccurrence = Pick<\n ScheduleOccurrence,\n \"occurrence\" | \"start\"\n> &\n Partial<\n Omit<ScheduleOccurrence, \"occurrence\" | \"start\" | \"schedule\" | \"tags\">\n > & {\n /** Tags for this occurrence */\n tags?: NewTags;\n\n /** Add or remove the twist's tags on this occurrence */\n twistTags?: Partial<Record<Tag, boolean>>;\n\n /** Whether this occurrence should be marked as unread */\n unread?: boolean;\n\n /** Contacts to upsert on this occurrence's schedule */\n contacts?: NewScheduleContact[];\n\n /**\n * Mark this single date as cancelled. The runtime translates this\n * into an addition to the parent schedule's `recurrenceExdates` and\n * archives any pre-existing override row for the same date — no\n * occurrence schedule row is created.\n */\n cancelled?: boolean;\n };\n\n/**\n * Type for updating schedule occurrences inline.\n */\nexport type ScheduleOccurrenceUpdate = Pick<\n NewScheduleOccurrence,\n \"occurrence\"\n> &\n Partial<Omit<NewScheduleOccurrence, \"occurrence\" | \"schedule\">>;\n";
8
+ export default "import { type Tag } from \"./tag\";\nimport {\n type Actor,\n type ActorId,\n type NewActor,\n type NewTags,\n type Tags,\n} from \"./plot\";\nimport { Uuid } from \"./utils/uuid\";\n\nexport { Uuid } from \"./utils/uuid\";\n\n/**\n * Represents a schedule entry for a thread.\n *\n * Schedules define when a thread occurs in time. A thread may have zero or more schedules:\n * - Shared schedules (userId is null): visible to all members of the thread's focus\n * - Per-user schedules (userId set): private ordering/scheduling for a specific user\n *\n * For recurring events in the SDK, start/end represent the first occurrence's\n * time. In the database, the `at`/`on` range is expanded to span from the first\n * occurrence start to the last occurrence end (or open-ended if no fixed end).\n * The `duration` column stores the per-occurrence duration, enabling range overlap\n * queries to correctly find all recurring events with occurrences in a given window.\n */\nexport type Schedule = {\n /** When this schedule was created */\n created: Date;\n /** Whether this schedule has been archived */\n archived: boolean;\n /** If set, this is a per-user schedule visible only to this user */\n userId: ActorId | null;\n /** Per-user ordering within a day (only set for per-user schedules) */\n order: number | null;\n /**\n * Start time of the schedule.\n * Date object for timed events, date string in \"YYYY-MM-DD\" format for all-day events.\n */\n start: Date | string | null;\n /**\n * End time of the schedule.\n * Date object for timed events, date string in \"YYYY-MM-DD\" format for all-day events.\n */\n end: Date | string | null;\n /** Recurrence rule in RFC 5545 RRULE format (e.g., \"FREQ=WEEKLY;BYDAY=MO,WE,FR\") */\n recurrenceRule: string | null;\n /** Duration of each occurrence in milliseconds (required for recurring schedules) */\n duration: number | null;\n /** Array of dates to exclude from the recurrence pattern */\n recurrenceExdates: Date[] | null;\n /**\n * For occurrence exceptions: the original date/time of this occurrence in the series.\n * Format: Date object or \"YYYY-MM-DD\" for all-day events.\n */\n occurrence: Date | string | null;\n /** Contacts invited to this schedule (attendees/participants) */\n contacts: ScheduleContact[];\n};\n\nexport type ScheduleContactStatus = \"attend\" | \"skip\";\nexport type ScheduleContactRole = \"organizer\" | \"required\" | \"optional\";\n\nexport type ScheduleContact = {\n contact: Actor;\n status: ScheduleContactStatus | null;\n role: ScheduleContactRole;\n archived: boolean;\n};\n\nexport type NewScheduleContact = {\n contact: NewActor;\n status?: ScheduleContactStatus | null;\n role?: ScheduleContactRole | null;\n archived?: boolean;\n};\n\n/**\n * Type for creating new schedules.\n *\n * Requires `threadId` and `start`. All other fields are optional.\n *\n * @example\n * ```typescript\n * // Simple timed event\n * const schedule: NewSchedule = {\n * threadId: threadId,\n * start: new Date(\"2025-03-15T10:00:00Z\"),\n * end: new Date(\"2025-03-15T11:00:00Z\")\n * };\n *\n * // All-day event\n * const allDay: NewSchedule = {\n * threadId: threadId,\n * start: \"2025-03-15\",\n * end: \"2025-03-16\"\n * };\n *\n * // Recurring weekly event\n * const recurring: NewSchedule = {\n * threadId: threadId,\n * start: new Date(\"2025-01-20T14:00:00Z\"),\n * end: new Date(\"2025-01-20T15:00:00Z\"),\n * recurrenceRule: \"FREQ=WEEKLY;BYDAY=MO\",\n * recurrenceUntil: new Date(\"2025-06-30\")\n * };\n * ```\n */\nexport type NewSchedule = {\n /** The thread this schedule belongs to */\n threadId: Uuid;\n /**\n * Start time. Date for timed events, \"YYYY-MM-DD\" for all-day.\n * Determines whether the schedule uses `at` (timed) or `on` (all-day) storage.\n */\n start: Date | string;\n /** End time. Date for timed events, \"YYYY-MM-DD\" for all-day. */\n end?: Date | string | null;\n /** Recurrence rule in RFC 5545 RRULE format */\n recurrenceRule?: string | null;\n /**\n * For recurring schedules, the last occurrence date (inclusive).\n * When both recurrenceCount and recurrenceUntil are provided, recurrenceCount takes precedence.\n */\n recurrenceUntil?: Date | string | null;\n /**\n * For recurring schedules, the number of occurrences to generate.\n * Takes precedence over recurrenceUntil if both are provided.\n */\n recurrenceCount?: number | null;\n /** Array of dates to exclude from the recurrence pattern */\n recurrenceExdates?: Date[] | null;\n /**\n * For occurrence exceptions: the original date/time of this occurrence.\n */\n occurrence?: Date | string | null;\n /** If set, this is a per-user schedule for the specified user */\n userId?: ActorId | null;\n /** Per-user ordering (only valid with userId) */\n order?: number | null;\n /** Whether to archive this schedule */\n archived?: boolean;\n /** Contacts to upsert on this schedule. Upserted by contact identity. */\n contacts?: NewScheduleContact[];\n};\n\n/**\n * Represents a specific instance of a recurring schedule.\n * All field values are computed by merging the recurring schedule's\n * defaults with any occurrence-specific overrides.\n */\nexport type ScheduleOccurrence = {\n /**\n * Original date/datetime of this occurrence.\n * Use start for the occurrence's current start time.\n */\n occurrence: Date | string;\n\n /** The recurring schedule of which this is an occurrence */\n schedule: Schedule;\n\n /** Effective start for this occurrence (series default + override) */\n start: Date | string;\n /** Effective end for this occurrence */\n end: Date | string | null;\n\n /** Tags for this occurrence */\n tags: Tags;\n};\n\n/**\n * Type for creating or updating schedule occurrences.\n *\n * Use `cancelled: true` to skip a single date in a recurring series\n * (e.g. an upstream calendar reports one occurrence as cancelled).\n * Internally this is translated into an addition to the parent\n * schedule's `recurrenceExdates`; no occurrence schedule row is\n * persisted for the cancelled date. For seeding the full exception\n * list on the master at initial sync, use `NewSchedule.recurrenceExdates`\n * instead.\n *\n * Use a normal occurrence record (without `cancelled`) for genuine\n * overrides — time changes, RSVP differences, etc.\n */\nexport type NewScheduleOccurrence = Pick<\n ScheduleOccurrence,\n \"occurrence\" | \"start\"\n> &\n Partial<\n Omit<ScheduleOccurrence, \"occurrence\" | \"start\" | \"schedule\" | \"tags\">\n > & {\n /** Tags for this occurrence */\n tags?: NewTags;\n\n /** Add or remove the twist's tags on this occurrence */\n twistTags?: Partial<Record<Tag, boolean>>;\n\n /** Whether this occurrence should be marked as unread */\n unread?: boolean;\n\n /** Contacts to upsert on this occurrence's schedule */\n contacts?: NewScheduleContact[];\n\n /**\n * Mark this single date as cancelled. The runtime translates this\n * into an addition to the parent schedule's `recurrenceExdates` and\n * archives any pre-existing override row for the same date — no\n * occurrence schedule row is created.\n */\n cancelled?: boolean;\n };\n\n/**\n * Type for updating schedule occurrences inline.\n */\nexport type ScheduleOccurrenceUpdate = Pick<\n NewScheduleOccurrence,\n \"occurrence\"\n> &\n Partial<Omit<NewScheduleOccurrence, \"occurrence\" | \"schedule\">>;\n";
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "/**\n * Thread tags. Three types:\n * 1. Special tags, which trigger other behaviors\n * 2. Toggle tags, which anyone can toggle a shared value on or off\n * 3. Count tags, where everyone can add or remove their own\n */\nexport enum Tag {\n // Special tags\n Todo = 1,\n Done = 3,\n\n // Toggle tags\n Pinned = 100,\n Urgent = 101,\n Goal = 103,\n Decision = 104,\n Waiting = 105,\n Blocked = 106,\n Warning = 107,\n Question = 108,\n Twist = 109,\n Star = 110,\n Idea = 111,\n\n // Count tags\n Yes = 1000,\n No = 1001,\n Volunteer = 1002,\n Tada = 1003,\n Fire = 1004,\n Totally = 1005,\n Looking = 1006,\n Love = 1007,\n Rocket = 1008,\n Sparkles = 1009,\n Thanks = 1010,\n Smile = 1011,\n Wave = 1012,\n Praise = 1015,\n Applause = 1016,\n Cool = 1017,\n Sad = 1018,\n Reply = 1019,\n Thinking = 1013,\n Remember = 1014,\n Agreed = 1020,\n Relieved = 1021,\n Send = 1022,\n Noted = 1023,\n Laugh = 1024,\n Surprised = 1025,\n Confused = 1026,\n Dismayed = 1027,\n}\n";
8
+ export default "/**\n * Compute tags system state the runtime auto-manages on threads and\n * notes (`todo`, `done`, `twist` activity marker, …).\n *\n * The toggle range (100–999) and count range (1000–1027) have been\n * retired in favour of the open Unicode emoji `Reaction` type — see\n * `@plotday/twister/plot`'s `Reactions` / `NewReactions` and the\n * per-row `note.reactions` / `thread.reactions` fields. Connectors\n * route emoji reactions through `reactions`, not `tags`.\n *\n * `Tag.Twist` is the surviving non-trivial tag: a system marker the\n * runtime adds to a note while a twist is processing it, and clears\n * once the twist returns. It's not user-facing and not a reaction.\n */\nexport enum Tag {\n Todo = 1,\n Done = 3,\n /** System marker for \"a twist is processing this note.\" Set by the\n * runtime when a twist callback fires, cleared on return. Twists\n * may still write `{ [Tag.Twist]: true | false }` to twistTags to\n * mark/unmark a note explicitly. */\n Twist = 12,\n}\n";
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import type { Static, TSchema } from \"typebox\";\n\nimport { ITool } from \"..\";\n\n/**\n * Built-in tool for prompting Large Language Models (LLMs).\n *\n * The AI tool provides twists and tools with access to LLM capabilities\n * for natural language processing, text generation, data extraction,\n * and intelligent decision making within their workflows.\n *\n * **Features:**\n * - Access to multiple AI providers (OpenAI, Anthropic, Google, Workers AI)\n * - Multi-turn conversation support with `messages`\n * - Tool calling with automatic execution\n * - Structured output with Typebox schemas via `outputSchema`\n * - Unified API across all models via Vercel AI SDK\n * - Automatic response parsing and validation with full type inference\n *\n * @example\n * ```typescript\n * import { Type } from \"typebox\";\n *\n * class SmartEmailTool extends Tool {\n * private ai: AI;\n *\n * constructor(id: string, tools: ToolBuilder) {\n * super();\n * this.ai = tools.get(AI);\n * }\n *\n * async categorizeEmail(emailContent: string) {\n * // Define the output schema using Typebox\n * const schema = Type.Object({\n * category: Type.Union([\n * Type.Literal(\"work\"),\n * Type.Literal(\"personal\"),\n * Type.Literal(\"spam\"),\n * Type.Literal(\"promotional\")\n * ]),\n * confidence: Type.Number({ minimum: 0, maximum: 1 }),\n * reasoning: Type.Optional(Type.String())\n * });\n *\n * const response = await this.ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * system: \"Classify emails into categories: work, personal, spam, or promotional.\",\n * prompt: `Categorize this email: ${emailContent}`,\n * outputSchema: schema\n * });\n *\n * return response.output;\n * }\n *\n * async generateResponse(emailContent: string) {\n * const response = await this.ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * system: \"Generate professional email responses that are helpful and concise.\",\n * prompt: `Write a response to: ${emailContent}`\n * });\n *\n * return response.text;\n * }\n * }\n * ```\n */\nexport abstract class AI extends ITool {\n /**\n * Returns which AI capabilities are currently available.\n * Check this before calling prompt() or embed() to gracefully\n * handle cases where AI is disabled by the user.\n */\n abstract available(): AICapabilities;\n\n /**\n * Sends a request to an AI model and returns the response using the Vercel AI SDK.\n *\n * Supports text generation, multi-turn conversations, structured outputs,\n * and tool calling across multiple AI providers via Cloudflare AI Gateway.\n *\n * @param request - AI request with model, prompt/messages, and optional configuration\n * @returns Promise resolving to the AI response with generated text and metadata\n *\n * @example\n * ```typescript\n * // Simple text generation\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * prompt: \"Explain quantum computing in simple terms\"\n * });\n * console.log(response.text);\n *\n * // Fast and cheap for simple tasks\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"low\" },\n * prompt: \"Summarize this text...\"\n * });\n * console.log(response.text);\n *\n * // With system instructions for complex reasoning\n * const response = await ai.prompt({\n * model: { speed: \"capable\", cost: \"high\" },\n * system: \"You are a helpful physics tutor.\",\n * prompt: \"Explain quantum entanglement\"\n * });\n * console.log(response.text);\n *\n * // Multi-turn conversation\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * messages: [\n * { role: \"user\", content: \"What is 2+2?\" },\n * { role: \"assistant\", content: \"2+2 equals 4.\" },\n * { role: \"user\", content: \"What about 3+3?\" }\n * ]\n * });\n * console.log(response.text);\n *\n * // Structured output with Typebox schema\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * prompt: \"Extract information: John is 30 years old\",\n * outputSchema: Type.Object({\n * name: Type.String(),\n * age: Type.Number()\n * })\n * });\n * console.log(response.output); // { name: \"John\", age: 30 }\n *\n * // Tool calling\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * prompt: \"What's the weather in San Francisco?\",\n * tools: {\n * getWeather: {\n * description: \"Get weather for a city\",\n * parameters: Type.Object({\n * city: Type.String()\n * }),\n * execute: async ({ city }) => {\n * return { temp: 72, condition: \"sunny\" };\n * }\n * }\n * }\n * });\n * console.log(response.text); // Model's response using tool results\n * console.log(response.toolCalls); // Array of tool calls made\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract prompt<TOOLS extends AIToolSet, SCHEMA extends TSchema = never>(\n request: AIRequest<TOOLS, SCHEMA>\n ): Promise<AIResponse<TOOLS, SCHEMA>>;\n}\n\n/** Options for configuring AI tool usage in a twist. */\nexport type AIOptions = {\n /** Whether AI is required for this twist to function. Default: true */\n required?: boolean;\n};\n\n/** Describes which AI capabilities are currently available to this twist. */\nexport type AICapabilities = {\n /** Whether AI prompting (text generation) is available. */\n prompt: boolean;\n /** Whether AI embedding generation is available. */\n embed: boolean;\n};\n\n/**\n * Model preferences for selecting an AI model based on performance and cost requirements.\n * This allows Plot to match those preferences with user preferences (such as preferred or\n * disallowed providers), as well as availability of newer and better models.\n *\n * @example\n * ```typescript\n * // Fast and cheap - uses Workers AI models like Llama 3.2 1B\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"low\" },\n * prompt: \"Summarize this in one sentence: ...\"\n * });\n *\n * // Balanced performance - uses GPT-5 Mini or Gemini 2.5 Flash\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * prompt: \"Analyze this data...\"\n * });\n *\n * // Most capable - uses Claude Sonnet 4.5 or Opus 4.1\n * const response = await ai.prompt({\n * model: { speed: \"capable\", cost: \"high\" },\n * prompt: \"Solve this complex reasoning problem...\"\n * });\n *\n * // Request a specific model with a hint\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\", hint: AIModel.CLAUDE_SONNET_45 },\n * prompt: \"...\"\n * });\n * ```\n */\nexport type ModelPreferences = {\n /**\n * Desired speed tier:\n * - \"fast\": Optimized for low latency and quick responses\n * - \"balanced\": Good balance of speed and capability\n * - \"capable\": Maximum reasoning and problem-solving ability\n */\n speed: \"fast\" | \"balanced\" | \"capable\";\n\n /**\n * Desired cost tier:\n * - \"low\": Minimal cost, often using Workers AI models (free/very cheap)\n * - \"medium\": Moderate pricing for good performance\n * - \"high\": Premium pricing for best-in-class models\n */\n cost: \"low\" | \"medium\" | \"high\";\n\n /**\n * Optional hint to suggest a specific model. The system will use this\n * model if possible, but may override it based on user preferences.\n */\n hint?: AIModel;\n};\n\n/**\n * Supported AI models available through Cloudflare AI Gateway and Workers AI.\n *\n * Models are organized by provider:\n * - **OpenAI**: Latest GPT models via AI Gateway\n * - **Anthropic**: Claude models via AI Gateway (prefix with \"anthropic/\")\n * - **Google**: Gemini models via AI Gateway (prefix with \"google-ai-studio/\")\n * - **Workers AI**: Models running on Cloudflare's network (free/low cost)\n */\nexport enum AIModel {\n // OpenAI models - Latest GPT and reasoning models\n GPT_5 = \"openai/gpt-5\",\n GPT_5_PRO = \"openai/gpt-5-pro\",\n GPT_5_MINI = \"openai/gpt-5-mini\",\n GPT_5_NANO = \"openai/gpt-5-nano\",\n GPT_4O = \"openai/gpt-4o\",\n GPT_4O_MINI = \"openai/gpt-4o-mini\",\n O3 = \"openai/o3\",\n O3_MINI = \"openai/o3-mini\",\n\n // Anthropic models - Claude 4.x series\n CLAUDE_OPUS_46 = \"anthropic/claude-opus-4-6\",\n CLAUDE_SONNET_46 = \"anthropic/claude-sonnet-4-6\",\n CLAUDE_HAIKU_45 = \"anthropic/claude-haiku-4-5\",\n\n // Google models - Gemini 2.x series\n GEMINI_25_PRO = \"google/gemini-2.5-pro\",\n GEMINI_25_FLASH = \"google/gemini-2.5-flash\",\n GEMINI_25_FLASH_LITE = \"google/gemini-2.5-flash-lite\",\n GEMINI_20_FLASH = \"google/gemini-2.0-flash\",\n GEMINI_20_FLASH_LITE = \"google/gemini-2.0-flash-lite\",\n\n // Cloudflare Workers AI models - Free/low-cost models running on Cloudflare's network\n LLAMA_4_SCOUT_17B = \"meta/llama-4-scout-17b-16e-instruct\",\n LLAMA_33_70B = \"meta/llama-3.3-70b-instruct-fp8-fast\",\n LLAMA_31_8B = \"meta/llama-3.1-8b-instruct-fp8\",\n LLAMA_32_1B = \"meta/llama-3.2-1b-instruct\",\n DEEPSEEK_R1_32B = \"deepseek-ai/deepseek-r1-distill-qwen-32b\",\n}\n\n/**\n * Request parameters for AI text generation, matching Vercel AI SDK's generateText() function.\n */\nexport interface AIRequest<\n TOOLS extends AIToolSet,\n SCHEMA extends TSchema = never\n> {\n /**\n * Model selection preferences based on desired speed and cost characteristics.\n * Plot will automatically select the best available model matching these preferences.\n *\n * @example\n * // Fast and cheap - good for simple tasks\n * model: { speed: \"fast\", cost: \"low\" }\n *\n * @example\n * // Balanced performance - general purpose\n * model: { speed: \"balanced\", cost: \"medium\" }\n *\n * @example\n * // Maximum capability - complex reasoning\n * model: { speed: \"capable\", cost: \"high\" }\n *\n * @example\n * // With a specific model hint\n * model: { speed: \"balanced\", cost: \"medium\", hint: \"anthropic/claude-sonnet-4-6\" }\n */\n model: ModelPreferences;\n\n /**\n * System instructions to guide the model's behavior.\n */\n system?: string;\n\n /**\n * The user's input prompt. Can be a simple string or an array of messages for multi-turn conversations.\n */\n prompt?: string;\n\n /**\n * Conversation messages for multi-turn interactions.\n * Replaces 'prompt' for more complex conversations.\n */\n messages?: AIMessage[];\n\n /**\n * Tools that the model can call during generation.\n * Each tool definition includes a description, input schema, and optional execute function.\n */\n tools?: TOOLS;\n\n /**\n * Controls which tools the model can use.\n * - \"auto\": Model decides whether to use tools\n * - \"none\": Model cannot use tools\n * - \"required\": Model must use at least one tool\n * - { type: \"tool\", toolName: string }: Model must use specific tool\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n /**\n * Structured output schema using Typebox.\n * Typebox schemas are JSON Schema objects that provide full TypeScript type inference.\n */\n outputSchema?: SCHEMA;\n\n /**\n * Maximum number of tokens to generate.\n */\n maxOutputTokens?: number;\n\n /**\n * Temperature for controlling randomness (0-2).\n * Higher values make output more random, lower values more deterministic.\n */\n temperature?: number;\n\n /**\n * Top P sampling parameter (0-1).\n * Controls diversity by limiting to top probability tokens.\n */\n topP?: number;\n}\n\n/**\n * Response from AI text generation, matching Vercel AI SDK's GenerateTextResult.\n */\nexport interface AIResponse<\n TOOLS extends AIToolSet,\n SCHEMA extends TSchema = never\n> {\n /**\n * The generated text.\n */\n text: string;\n\n /**\n * Tool calls made by the model during generation.\n */\n toolCalls?: ToolCallArray<TOOLS>;\n\n /**\n * Results from tool executions.\n */\n toolResults?: ToolResultArray<TOOLS>;\n\n /**\n * Reason why the model stopped generating.\n */\n finishReason:\n | \"stop\"\n | \"length\"\n | \"content-filter\"\n | \"tool-calls\"\n | \"error\"\n | \"other\"\n | \"unknown\";\n\n /**\n * Token usage information for this generation.\n */\n usage: AIUsage;\n\n /**\n * Sources used by the model (if supported).\n */\n sources?: Array<AISource>;\n\n /**\n * Structured output when using outputSchema.\n * Type is automatically inferred from the Typebox schema.\n */\n output?: Static<SCHEMA>;\n\n /**\n * Response metadata including messages.\n */\n response?: {\n id?: string;\n timestamp?: Date;\n modelId?: string;\n messages?: AIMessage[];\n };\n}\n\n// ============================================================================\n// Message Types\n// ============================================================================\n\n/**\n * A system message. It can contain system information.\n *\n * Note: using the \"system\" part of the prompt is strongly preferred\n * to increase the resilience against prompt injection attacks,\n * and because not all providers support several system messages.\n */\nexport type AISystemMessage = {\n role: \"system\";\n content: string;\n};\n\n/**\n * A user message. It can contain text or a combination of text and images.\n */\nexport type AIUserMessage = {\n role: \"user\";\n content: string | Array<TextPart | ImagePart | FilePart>;\n};\n\n/**\n * An assistant message. It can contain text, tool calls, or a combination of text and tool calls.\n */\nexport type AIAssistantMessage = {\n role: \"assistant\";\n content:\n | string\n | Array<\n TextPart | FilePart | ReasoningPart | ToolCallPart | ToolResultPart\n >;\n};\n\n/**\n * A tool message. It contains the result of one or more tool calls.\n */\nexport type AIToolMessage = {\n role: \"tool\";\n content: Array<ToolResultPart>;\n};\n\n/**\n * A message that can be used in the `messages` field of a prompt.\n * It can be a user message, an assistant message, or a tool message.\n */\nexport type AIMessage =\n | AISystemMessage\n | AIUserMessage\n | AIAssistantMessage\n | AIToolMessage;\n\n// ============================================================================\n// Usage & Sources\n// ============================================================================\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type AIUsage = {\n /**\n * The number of tokens used in the prompt.\n */\n inputTokens?: number;\n /**\n * The number of tokens used in the completion.\n */\n outputTokens?: number;\n /**\n * The total number of tokens used (promptTokens + completionTokens).\n */\n totalTokens?: number;\n /**\n * The number of reasoning tokens used in the completion.\n */\n reasoningTokens?: number;\n};\n\n/**\n * A source that has been used as input to generate the response.\n */\nexport type AISource =\n | {\n type: \"source\";\n /**\n * A URL source. This is returned by web search RAG models.\n */\n sourceType: \"url\";\n /**\n * The ID of the source.\n */\n id: string;\n /**\n * The URL of the source.\n */\n url: string;\n /**\n * The title of the source.\n */\n title?: string;\n }\n | {\n type: \"source\";\n /**\n * The type of source - document sources reference files/documents.\n */\n sourceType: \"document\";\n /**\n * The ID of the source.\n */\n id: string;\n /**\n * IANA media type of the document (e.g., 'application/pdf').\n */\n mediaType: string;\n /**\n * The title of the document.\n */\n title: string;\n /**\n * Optional filename of the document.\n */\n filename?: string;\n };\n\n// ============================================================================\n// Content Parts\n// ============================================================================\n\n/**\n * Text content part of a prompt. It contains a string of text.\n */\nexport interface TextPart {\n type: \"text\";\n /**\n * The text content.\n */\n text: string;\n}\n\n/**\n * Data content. Can either be a base64-encoded string, a Uint8Array, or an ArrayBuffer.\n */\nexport type DataContent = string | Uint8Array | ArrayBuffer;\n\n/**\n * Image content part of a prompt. It contains an image.\n */\nexport interface ImagePart {\n type: \"image\";\n /**\n * Image data. Can either be:\n *\n * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n * - URL: a URL that points to the image\n */\n image: DataContent | URL;\n /**\n * Optional mime type of the image.\n */\n mimeType?: string;\n}\n\n/**\n * File content part of a prompt. It contains a file.\n */\nexport interface FilePart {\n type: \"file\";\n /**\n * File data. Can either be:\n *\n * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n * - URL: a URL that points to the file\n */\n data: DataContent | URL;\n /**\n * Optional filename of the file.\n */\n filename?: string;\n /**\n * IANA media type of the file.\n *\n * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n */\n mediaType: string;\n}\n\n/**\n * Reasoning content part of a prompt. It contains a reasoning.\n */\nexport interface ReasoningPart {\n type: \"reasoning\";\n /**\n * The reasoning text.\n */\n text: string;\n /**\n * An optional signature for verifying that the reasoning originated from the model.\n */\n signature?: string;\n}\n\n/**\n * Redacted reasoning content part of a prompt.\n */\nexport interface RedactedReasoningPart {\n type: \"redacted-reasoning\";\n /**\n * Redacted reasoning data.\n */\n data: string;\n}\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: \"tool-call\";\n /**\n * ID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n /**\n * Name of the tool that is being called.\n */\n toolName: string;\n /**\n * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n input: unknown;\n}\n\ntype JSONValue = null | string | number | boolean | JSONObject | JSONArray;\ntype JSONObject = {\n [key: string]: JSONValue;\n};\ntype JSONArray = JSONValue[];\n\n/**\n * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.\n */\nexport interface ToolResultPart {\n type: \"tool-result\";\n /**\n * ID of the tool call that this result is associated with.\n */\n toolCallId: string;\n /**\n * Name of the tool that generated this result.\n */\n toolName: string;\n /**\n * Result of the tool call. This is a JSON-serializable object.\n */\n output:\n | {\n type: \"text\";\n value: string;\n }\n | {\n type: \"json\";\n value: JSONValue;\n }\n | {\n type: \"error-text\";\n value: string;\n }\n | {\n type: \"error-json\";\n value: JSONValue;\n }\n | {\n type: \"content\";\n value: Array<\n | {\n type: \"text\";\n /**\nText content.\n*/\n text: string;\n }\n | {\n type: \"media\";\n /**\nBase-64 encoded media data.\n*/\n data: string;\n /**\nIANA media type.\n@see https://www.iana.org/assignments/media-types/media-types.xhtml\n*/\n mediaType: string;\n }\n >;\n };\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\ntype ToolParameters = TSchema;\n\ntype inferParameters<PARAMETERS extends ToolParameters> = Static<PARAMETERS>;\n\n/**\n * Options passed to tool execution functions.\n */\nexport interface ToolExecutionOptions {\n /**\n * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n */\n toolCallId: string;\n /**\n * Messages that were sent to the language model to initiate the response that contained the tool call.\n * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n */\n messages: AIMessage[];\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport type AITool<PARAMETERS extends ToolParameters = any, RESULT = any> = {\n /**\n * The schema of the input that the tool expects. The language model will use this to generate the input.\n * It is also used to validate the output of the language model.\n * Use descriptions to make the input understandable for the language model.\n */\n parameters: PARAMETERS;\n /**\n * The schema of the input that the tool expects. The language model will use this to generate the input.\n * It is also used to validate the output of the language model.\n * Use descriptions to make the input understandable for the language model.\n */\n inputSchema: TSchema;\n /**\n * An optional description of what the tool does.\n * Will be used by the language model to decide whether to use the tool.\n * Not used for provider-defined tools.\n */\n description?: string;\n /**\n * An async function that is called with the arguments from the tool call and produces a result.\n * If not provided, the tool will not be executed automatically.\n *\n * @param args - The input of the tool call\n * @param options - Execution options including abort signal and messages\n */\n execute?: (\n args: inferParameters<PARAMETERS>,\n options: ToolExecutionOptions\n ) => PromiseLike<RESULT>;\n} & (\n | {\n /**\n * Function tool.\n */\n type?: undefined | \"function\";\n }\n | {\n /**\n * Provider-defined tool.\n */\n type: \"provider-defined\";\n /**\n * The ID of the tool. Should follow the format `<provider-name>.<tool-name>`.\n */\n id: `${string}.${string}`;\n /**\n * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n */\n args: Record<string, unknown>;\n }\n);\n\n/**\n * Tool choice for the generation. It supports the following settings:\n *\n * - `auto` (default): the model can choose whether and which tools to call.\n * - `required`: the model must call a tool. It can choose which tool to call.\n * - `none`: the model must not call tools\n * - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool\n */\ntype ToolChoice<TOOLS extends Record<string, unknown>> =\n | \"auto\"\n | \"none\"\n | \"required\"\n | {\n type: \"tool\";\n toolName: Extract<keyof TOOLS, string>;\n };\n\nexport type AIToolSet = Record<\n string,\n (\n | AITool<never, never>\n | AITool<any, any>\n | AITool<any, never>\n | AITool<never, any>\n ) &\n Pick<AITool<any, any>, \"execute\">\n>;\n\n// ============================================================================\n// Internal Helper Types\n// ============================================================================\n\ntype ToolCallUnion<_TOOLS extends AIToolSet> = {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n args?: unknown;\n};\n\ntype ToolCallArray<TOOLS extends AIToolSet> = Array<ToolCallUnion<TOOLS>>;\n\ntype ToolResultUnion<_TOOLS extends AIToolSet> = {\n type: \"tool-result\";\n toolCallId: string;\n toolName: string;\n args?: unknown;\n result?: unknown;\n};\n\ntype ToolResultArray<TOOLS extends AIToolSet> = Array<ToolResultUnion<TOOLS>>;\n";
8
+ export default "import type { Static, TSchema } from \"typebox\";\n\nimport { ITool } from \"..\";\n\n/**\n * Built-in tool for prompting Large Language Models (LLMs).\n *\n * The AI tool provides twists and tools with access to LLM capabilities\n * for natural language processing, text generation, data extraction,\n * and intelligent decision making within their workflows.\n *\n * **Features:**\n * - Access to multiple AI providers (OpenAI, Anthropic, Google, Workers AI)\n * - Multi-turn conversation support with `messages`\n * - Tool calling with automatic execution\n * - Structured output with Typebox schemas via `outputSchema`\n * - Unified API across all models via Vercel AI SDK\n * - Automatic response parsing and validation with full type inference\n *\n * @example\n * ```typescript\n * import { Type } from \"typebox\";\n *\n * class SmartEmailTool extends Tool {\n * private ai: AI;\n *\n * constructor(id: string, tools: ToolBuilder) {\n * super();\n * this.ai = tools.get(AI);\n * }\n *\n * async categorizeEmail(emailContent: string) {\n * // Define the output schema using Typebox\n * const schema = Type.Object({\n * category: Type.Union([\n * Type.Literal(\"work\"),\n * Type.Literal(\"personal\"),\n * Type.Literal(\"spam\"),\n * Type.Literal(\"promotional\")\n * ]),\n * confidence: Type.Number({ minimum: 0, maximum: 1 }),\n * reasoning: Type.Optional(Type.String())\n * });\n *\n * const response = await this.ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * system: \"Classify emails into categories: work, personal, spam, or promotional.\",\n * prompt: `Categorize this email: ${emailContent}`,\n * outputSchema: schema\n * });\n *\n * return response.output;\n * }\n *\n * async generateResponse(emailContent: string) {\n * const response = await this.ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * system: \"Generate professional email responses that are helpful and concise.\",\n * prompt: `Write a response to: ${emailContent}`\n * });\n *\n * return response.text;\n * }\n * }\n * ```\n */\nexport abstract class AI extends ITool {\n /**\n * Returns which AI capabilities are currently available.\n * Check this before calling prompt() or embed() to gracefully\n * handle cases where AI is disabled by the user.\n *\n * Built-in tools are accessed as RPC stubs, so from a twist this call\n * resolves asynchronously — always `await` it.\n */\n abstract available(): AICapabilities | Promise<AICapabilities>;\n\n /**\n * Sends a request to an AI model and returns the response using the Vercel AI SDK.\n *\n * Supports text generation, multi-turn conversations, structured outputs,\n * and tool calling across multiple AI providers via Cloudflare AI Gateway.\n *\n * @param request - AI request with model, prompt/messages, and optional configuration\n * @returns Promise resolving to the AI response with generated text and metadata\n *\n * @example\n * ```typescript\n * // Simple text generation\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * prompt: \"Explain quantum computing in simple terms\"\n * });\n * console.log(response.text);\n *\n * // Fast and cheap for simple tasks\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"low\" },\n * prompt: \"Summarize this text...\"\n * });\n * console.log(response.text);\n *\n * // With system instructions for complex reasoning\n * const response = await ai.prompt({\n * model: { speed: \"capable\", cost: \"high\" },\n * system: \"You are a helpful physics tutor.\",\n * prompt: \"Explain quantum entanglement\"\n * });\n * console.log(response.text);\n *\n * // Multi-turn conversation\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * messages: [\n * { role: \"user\", content: \"What is 2+2?\" },\n * { role: \"assistant\", content: \"2+2 equals 4.\" },\n * { role: \"user\", content: \"What about 3+3?\" }\n * ]\n * });\n * console.log(response.text);\n *\n * // Structured output with Typebox schema\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"medium\" },\n * prompt: \"Extract information: John is 30 years old\",\n * outputSchema: Type.Object({\n * name: Type.String(),\n * age: Type.Number()\n * })\n * });\n * console.log(response.output); // { name: \"John\", age: 30 }\n *\n * // Tool calling\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * prompt: \"What's the weather in San Francisco?\",\n * tools: {\n * getWeather: {\n * description: \"Get weather for a city\",\n * inputSchema: Type.Object({\n * city: Type.String()\n * }),\n * execute: async ({ city }) => {\n * return { temp: 72, condition: \"sunny\" };\n * }\n * }\n * }\n * });\n * console.log(response.text); // Model's response using tool results\n * console.log(response.toolCalls); // Array of tool calls made\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract prompt<TOOLS extends AIToolSet, SCHEMA extends TSchema = never>(\n request: AIRequest<TOOLS, SCHEMA>\n ): Promise<AIResponse<TOOLS, SCHEMA>>;\n}\n\n/** Options for configuring AI tool usage in a twist. */\nexport type AIOptions = {\n /** Whether AI is required for this twist to function. Default: true */\n required?: boolean;\n};\n\n/** Describes which AI capabilities are currently available to this twist. */\nexport type AICapabilities = {\n /** Whether AI prompting (text generation) is available. */\n prompt: boolean;\n /** Whether AI embedding generation is available. */\n embed: boolean;\n /**\n * Whether provider-native web search is available. True for Plot AI and\n * Anthropic/Google BYOK providers; false for OpenAI/custom BYOK providers\n * that don't expose a server-side web search tool through this runtime.\n */\n webSearch: boolean;\n};\n\n/**\n * Model preferences for selecting an AI model based on performance and cost requirements.\n * This allows Plot to match those preferences with user preferences (such as preferred or\n * disallowed providers), as well as availability of newer and better models.\n *\n * @example\n * ```typescript\n * // Fast and cheap - uses Workers AI models like Llama 3.2 1B\n * const response = await ai.prompt({\n * model: { speed: \"fast\", cost: \"low\" },\n * prompt: \"Summarize this in one sentence: ...\"\n * });\n *\n * // Balanced performance - uses GPT-5 Mini or Gemini 2.5 Flash\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\" },\n * prompt: \"Analyze this data...\"\n * });\n *\n * // Most capable - uses Claude Sonnet 4.5 or Opus 4.1\n * const response = await ai.prompt({\n * model: { speed: \"capable\", cost: \"high\" },\n * prompt: \"Solve this complex reasoning problem...\"\n * });\n *\n * // Request a specific model with a hint\n * const response = await ai.prompt({\n * model: { speed: \"balanced\", cost: \"medium\", hint: AIModel.CLAUDE_SONNET_45 },\n * prompt: \"...\"\n * });\n * ```\n */\nexport type ModelPreferences = {\n /**\n * Desired speed tier:\n * - \"fast\": Optimized for low latency and quick responses\n * - \"balanced\": Good balance of speed and capability\n * - \"capable\": Maximum reasoning and problem-solving ability\n */\n speed: \"fast\" | \"balanced\" | \"capable\";\n\n /**\n * Desired cost tier:\n * - \"low\": Minimal cost, often using Workers AI models (free/very cheap)\n * - \"medium\": Moderate pricing for good performance\n * - \"high\": Premium pricing for best-in-class models\n */\n cost: \"low\" | \"medium\" | \"high\";\n\n /**\n * Optional hint to suggest a specific model. The system will use this\n * model if possible, but may override it based on user preferences.\n */\n hint?: AIModel;\n};\n\n/**\n * Supported AI models available through Cloudflare AI Gateway and Workers AI.\n *\n * Models are organized by provider:\n * - **OpenAI**: Latest GPT models via AI Gateway\n * - **Anthropic**: Claude models via AI Gateway (prefix with \"anthropic/\")\n * - **Google**: Gemini models via AI Gateway (prefix with \"google-ai-studio/\")\n * - **Workers AI**: Models running on Cloudflare's network (free/low cost)\n */\nexport enum AIModel {\n // OpenAI models - Latest GPT and reasoning models\n GPT_5 = \"openai/gpt-5\",\n GPT_5_PRO = \"openai/gpt-5-pro\",\n GPT_5_MINI = \"openai/gpt-5-mini\",\n GPT_5_NANO = \"openai/gpt-5-nano\",\n GPT_4O = \"openai/gpt-4o\",\n GPT_4O_MINI = \"openai/gpt-4o-mini\",\n O3 = \"openai/o3\",\n O3_MINI = \"openai/o3-mini\",\n\n // Anthropic models - Claude 4.x series\n CLAUDE_OPUS_46 = \"anthropic/claude-opus-4-6\",\n CLAUDE_SONNET_46 = \"anthropic/claude-sonnet-4-6\",\n CLAUDE_HAIKU_45 = \"anthropic/claude-haiku-4-5\",\n\n // Google models - Gemini 2.x series\n GEMINI_25_PRO = \"google/gemini-2.5-pro\",\n GEMINI_25_FLASH = \"google/gemini-2.5-flash\",\n GEMINI_25_FLASH_LITE = \"google/gemini-2.5-flash-lite\",\n GEMINI_20_FLASH = \"google/gemini-2.0-flash\",\n GEMINI_20_FLASH_LITE = \"google/gemini-2.0-flash-lite\",\n\n // Cloudflare Workers AI models - Free/low-cost models running on Cloudflare's network\n LLAMA_4_SCOUT_17B = \"meta/llama-4-scout-17b-16e-instruct\",\n LLAMA_33_70B = \"meta/llama-3.3-70b-instruct-fp8-fast\",\n LLAMA_31_8B = \"meta/llama-3.1-8b-instruct-fp8\",\n LLAMA_32_1B = \"meta/llama-3.2-1b-instruct\",\n DEEPSEEK_R1_32B = \"deepseek-ai/deepseek-r1-distill-qwen-32b\",\n}\n\n/**\n * Request parameters for AI text generation, matching Vercel AI SDK's generateText() function.\n */\nexport interface AIRequest<\n TOOLS extends AIToolSet,\n SCHEMA extends TSchema = never\n> {\n /**\n * Model selection preferences based on desired speed and cost characteristics.\n * Plot will automatically select the best available model matching these preferences.\n *\n * @example\n * // Fast and cheap - good for simple tasks\n * model: { speed: \"fast\", cost: \"low\" }\n *\n * @example\n * // Balanced performance - general purpose\n * model: { speed: \"balanced\", cost: \"medium\" }\n *\n * @example\n * // Maximum capability - complex reasoning\n * model: { speed: \"capable\", cost: \"high\" }\n *\n * @example\n * // With a specific model hint\n * model: { speed: \"balanced\", cost: \"medium\", hint: \"anthropic/claude-sonnet-4-6\" }\n */\n model: ModelPreferences;\n\n /**\n * System instructions to guide the model's behavior.\n */\n system?: string;\n\n /**\n * The user's input prompt. Can be a simple string or an array of messages for multi-turn conversations.\n */\n prompt?: string;\n\n /**\n * Conversation messages for multi-turn interactions.\n * Replaces 'prompt' for more complex conversations.\n */\n messages?: AIMessage[];\n\n /**\n * Tools that the model can call during generation.\n * Each tool definition includes a description, input schema, and optional execute function.\n */\n tools?: TOOLS;\n\n /**\n * Controls which tools the model can use.\n * - \"auto\": Model decides whether to use tools\n * - \"none\": Model cannot use tools\n * - \"required\": Model must use at least one tool\n * - { type: \"tool\", toolName: string }: Model must use specific tool\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n /**\n * Structured output schema using Typebox.\n * Typebox schemas are JSON Schema objects that provide full TypeScript type inference.\n */\n outputSchema?: SCHEMA;\n\n /**\n * Maximum number of tokens to generate.\n */\n maxOutputTokens?: number;\n\n /**\n * Temperature for controlling randomness (0-2).\n * Higher values make output more random, lower values more deterministic.\n */\n temperature?: number;\n\n /**\n * Top P sampling parameter (0-1).\n * Controls diversity by limiting to top probability tokens.\n */\n topP?: number;\n\n /**\n * Enable provider-native web search so the model can retrieve\n * up-to-date information from the web. The search is executed\n * server-side by the provider and any pages used are returned in\n * {@link AIResponse.sources}.\n *\n * Only available on web-search-capable providers (Anthropic and\n * Google). Check {@link AICapabilities.webSearch} via `available()`\n * before relying on it; on unsupported providers the flag is ignored.\n *\n * Pass `true` for defaults, or an object to cap the number of searches.\n */\n webSearch?: boolean | { maxUses?: number };\n\n /**\n * Maximum number of sequential generation steps for agentic tool use.\n * When the model calls a tool, its result is fed back and the model is\n * called again, up to `maxSteps` times, until it produces a final answer.\n *\n * Defaults to 1 (single step — tool calls are returned but not looped),\n * preserving prior behavior. Set higher (e.g. 6) to let the model chain\n * tool calls into a final answer.\n */\n maxSteps?: number;\n}\n\n/**\n * Response from AI text generation, matching Vercel AI SDK's GenerateTextResult.\n */\nexport interface AIResponse<\n TOOLS extends AIToolSet,\n SCHEMA extends TSchema = never\n> {\n /**\n * The generated text.\n */\n text: string;\n\n /**\n * Tool calls made by the model during generation.\n */\n toolCalls?: ToolCallArray<TOOLS>;\n\n /**\n * Results from tool executions.\n */\n toolResults?: ToolResultArray<TOOLS>;\n\n /**\n * Reason why the model stopped generating.\n */\n finishReason:\n | \"stop\"\n | \"length\"\n | \"content-filter\"\n | \"tool-calls\"\n | \"error\"\n | \"other\"\n | \"unknown\";\n\n /**\n * Token usage information for this generation.\n */\n usage: AIUsage;\n\n /**\n * Sources used by the model (if supported).\n */\n sources?: Array<AISource>;\n\n /**\n * Structured output when using outputSchema.\n * Type is automatically inferred from the Typebox schema.\n */\n output?: Static<SCHEMA>;\n\n /**\n * Response metadata including messages.\n */\n response?: {\n id?: string;\n timestamp?: Date;\n modelId?: string;\n messages?: AIMessage[];\n };\n}\n\n// ============================================================================\n// Message Types\n// ============================================================================\n\n/**\n * A system message. It can contain system information.\n *\n * Note: using the \"system\" part of the prompt is strongly preferred\n * to increase the resilience against prompt injection attacks,\n * and because not all providers support several system messages.\n */\nexport type AISystemMessage = {\n role: \"system\";\n content: string;\n};\n\n/**\n * A user message. It can contain text or a combination of text and images.\n */\nexport type AIUserMessage = {\n role: \"user\";\n content: string | Array<TextPart | ImagePart | FilePart>;\n};\n\n/**\n * An assistant message. It can contain text, tool calls, or a combination of text and tool calls.\n */\nexport type AIAssistantMessage = {\n role: \"assistant\";\n content:\n | string\n | Array<\n TextPart | FilePart | ReasoningPart | ToolCallPart | ToolResultPart\n >;\n};\n\n/**\n * A tool message. It contains the result of one or more tool calls.\n */\nexport type AIToolMessage = {\n role: \"tool\";\n content: Array<ToolResultPart>;\n};\n\n/**\n * A message that can be used in the `messages` field of a prompt.\n * It can be a user message, an assistant message, or a tool message.\n */\nexport type AIMessage =\n | AISystemMessage\n | AIUserMessage\n | AIAssistantMessage\n | AIToolMessage;\n\n// ============================================================================\n// Usage & Sources\n// ============================================================================\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type AIUsage = {\n /**\n * The number of tokens used in the prompt.\n */\n inputTokens?: number;\n /**\n * The number of tokens used in the completion.\n */\n outputTokens?: number;\n /**\n * The total number of tokens used (promptTokens + completionTokens).\n */\n totalTokens?: number;\n /**\n * The number of reasoning tokens used in the completion.\n */\n reasoningTokens?: number;\n};\n\n/**\n * A source that has been used as input to generate the response.\n */\nexport type AISource =\n | {\n type: \"source\";\n /**\n * A URL source. This is returned by web search RAG models.\n */\n sourceType: \"url\";\n /**\n * The ID of the source.\n */\n id: string;\n /**\n * The URL of the source.\n */\n url: string;\n /**\n * The title of the source.\n */\n title?: string;\n }\n | {\n type: \"source\";\n /**\n * The type of source - document sources reference files/documents.\n */\n sourceType: \"document\";\n /**\n * The ID of the source.\n */\n id: string;\n /**\n * IANA media type of the document (e.g., 'application/pdf').\n */\n mediaType: string;\n /**\n * The title of the document.\n */\n title: string;\n /**\n * Optional filename of the document.\n */\n filename?: string;\n };\n\n// ============================================================================\n// Content Parts\n// ============================================================================\n\n/**\n * Text content part of a prompt. It contains a string of text.\n */\nexport interface TextPart {\n type: \"text\";\n /**\n * The text content.\n */\n text: string;\n}\n\n/**\n * Data content. Can either be a base64-encoded string, a Uint8Array, or an ArrayBuffer.\n */\nexport type DataContent = string | Uint8Array | ArrayBuffer;\n\n/**\n * Image content part of a prompt. It contains an image.\n */\nexport interface ImagePart {\n type: \"image\";\n /**\n * Image data. Can either be:\n *\n * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n * - URL: a URL that points to the image\n */\n image: DataContent | URL;\n /**\n * Optional mime type of the image.\n */\n mimeType?: string;\n}\n\n/**\n * File content part of a prompt. It contains a file.\n */\nexport interface FilePart {\n type: \"file\";\n /**\n * File data. Can either be:\n *\n * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n * - URL: a URL that points to the file\n */\n data: DataContent | URL;\n /**\n * Optional filename of the file.\n */\n filename?: string;\n /**\n * IANA media type of the file.\n *\n * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n */\n mediaType: string;\n}\n\n/**\n * Reasoning content part of a prompt. It contains a reasoning.\n */\nexport interface ReasoningPart {\n type: \"reasoning\";\n /**\n * The reasoning text.\n */\n text: string;\n /**\n * An optional signature for verifying that the reasoning originated from the model.\n */\n signature?: string;\n}\n\n/**\n * Redacted reasoning content part of a prompt.\n */\nexport interface RedactedReasoningPart {\n type: \"redacted-reasoning\";\n /**\n * Redacted reasoning data.\n */\n data: string;\n}\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: \"tool-call\";\n /**\n * ID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n /**\n * Name of the tool that is being called.\n */\n toolName: string;\n /**\n * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n input: unknown;\n}\n\ntype JSONValue = null | string | number | boolean | JSONObject | JSONArray;\ntype JSONObject = {\n [key: string]: JSONValue;\n};\ntype JSONArray = JSONValue[];\n\n/**\n * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.\n */\nexport interface ToolResultPart {\n type: \"tool-result\";\n /**\n * ID of the tool call that this result is associated with.\n */\n toolCallId: string;\n /**\n * Name of the tool that generated this result.\n */\n toolName: string;\n /**\n * Result of the tool call. This is a JSON-serializable object.\n */\n output:\n | {\n type: \"text\";\n value: string;\n }\n | {\n type: \"json\";\n value: JSONValue;\n }\n | {\n type: \"error-text\";\n value: string;\n }\n | {\n type: \"error-json\";\n value: JSONValue;\n }\n | {\n type: \"content\";\n value: Array<\n | {\n type: \"text\";\n /**\nText content.\n*/\n text: string;\n }\n | {\n type: \"media\";\n /**\nBase-64 encoded media data.\n*/\n data: string;\n /**\nIANA media type.\n@see https://www.iana.org/assignments/media-types/media-types.xhtml\n*/\n mediaType: string;\n }\n >;\n };\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\ntype ToolParameters = TSchema;\n\ntype inferParameters<PARAMETERS extends ToolParameters> = Static<PARAMETERS>;\n\n/**\n * Options passed to tool execution functions.\n */\nexport interface ToolExecutionOptions {\n /**\n * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n */\n toolCallId: string;\n /**\n * Messages that were sent to the language model to initiate the response that contained the tool call.\n * The messages **do not** include the system prompt nor the assistant response that contained the tool call.\n */\n messages: AIMessage[];\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport type AITool<PARAMETERS extends ToolParameters = any, RESULT = any> = {\n /**\n * The schema of the input that the tool expects, expressed as a Typebox\n * schema. The language model uses this to generate (and the runtime to\n * validate) the tool input. Use field descriptions to make the input\n * understandable for the model.\n *\n * This is the canonical field read by the runtime. `parameters` is an\n * accepted alias for backwards compatibility.\n */\n inputSchema: TSchema;\n /**\n * @deprecated Alias for {@link inputSchema}. Prefer `inputSchema`.\n */\n parameters?: PARAMETERS;\n /**\n * An optional description of what the tool does.\n * Will be used by the language model to decide whether to use the tool.\n * Not used for provider-defined tools.\n */\n description?: string;\n /**\n * An async function that is called with the arguments from the tool call and produces a result.\n * If not provided, the tool will not be executed automatically.\n *\n * @param args - The input of the tool call\n * @param options - Execution options including abort signal and messages\n */\n execute?: (\n args: inferParameters<PARAMETERS>,\n options: ToolExecutionOptions\n ) => PromiseLike<RESULT>;\n} & (\n | {\n /**\n * Function tool.\n */\n type?: undefined | \"function\";\n }\n | {\n /**\n * Provider-defined tool.\n */\n type: \"provider-defined\";\n /**\n * The ID of the tool. Should follow the format `<provider-name>.<tool-name>`.\n */\n id: `${string}.${string}`;\n /**\n * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n */\n args: Record<string, unknown>;\n }\n);\n\n/**\n * Tool choice for the generation. It supports the following settings:\n *\n * - `auto` (default): the model can choose whether and which tools to call.\n * - `required`: the model must call a tool. It can choose which tool to call.\n * - `none`: the model must not call tools\n * - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool\n */\ntype ToolChoice<TOOLS extends Record<string, unknown>> =\n | \"auto\"\n | \"none\"\n | \"required\"\n | {\n type: \"tool\";\n toolName: Extract<keyof TOOLS, string>;\n };\n\nexport type AIToolSet = Record<\n string,\n (\n | AITool<never, never>\n | AITool<any, any>\n | AITool<any, never>\n | AITool<never, any>\n ) &\n Pick<AITool<any, any>, \"execute\">\n>;\n\n// ============================================================================\n// Internal Helper Types\n// ============================================================================\n\ntype ToolCallUnion<_TOOLS extends AIToolSet> = {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n args?: unknown;\n};\n\ntype ToolCallArray<TOOLS extends AIToolSet> = Array<ToolCallUnion<TOOLS>>;\n\ntype ToolResultUnion<_TOOLS extends AIToolSet> = {\n type: \"tool-result\";\n toolCallId: string;\n toolName: string;\n args?: unknown;\n result?: unknown;\n};\n\ntype ToolResultArray<TOOLS extends AIToolSet> = Array<ToolResultUnion<TOOLS>>;\n";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Generated LLM documentation for @plotday/twister/tools/files
3
+ *
4
+ * This file is auto-generated during build. Do not edit manually.
5
+ * Generated from: prebuild.ts
6
+ */
7
+
8
+ export default "import { ITool } from \"..\";\n\n/**\n * Built-in tool for reading files attached to notes in Plot.\n *\n * Files are uploaded by clients via POST /files which creates an\n * ActionType.file entry on a note. Connectors call read() during outbound\n * (e.g. onNoteCreated) to retrieve those bytes and send them to the source\n * system.\n *\n * For inbound attachments, connectors emit ActionType.fileRef actions and\n * implement Connector.downloadAttachment — no upload tool is needed because\n * inbound bytes never enter Plot's R2 storage.\n */\nexport abstract class Files extends ITool {\n /**\n * Read a file uploaded by a client and attached to a note in a focus\n * where this twist is installed.\n *\n * @param fileId The id from an ActionType.file action.\n * @returns Bytes plus original metadata.\n * @throws FileNotFoundError if the file is missing or out of scope.\n */\n abstract read(fileId: string): Promise<{\n data: Uint8Array;\n fileName: string;\n mimeType: string;\n fileSize: number;\n }>;\n}\n\nexport class FileNotFoundError extends Error {\n constructor(fileId: string) {\n super(`File not found or out of scope: ${fileId}`);\n this.name = \"FileNotFoundError\";\n }\n}\n";
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import {\n type Actor,\n type ActorId,\n type NewContact,\n type NewLinkWithNotes,\n ITool,\n Serializable,\n} from \"..\";\nimport { Tag } from \"../tag\";\nimport type { JSONValue } from \"../utils/types\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getChannels() and managed by users in the twist setup/edit modal.\n */\nexport type Channel = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n /** Optional nested channel resources (e.g., subfolders) */\n children?: Channel[];\n /** Per-channel link type configs. Overrides twist-level linkTypes when present. */\n linkTypes?: LinkTypeConfig[];\n};\n\n/**\n * Describes a link type that a connector creates.\n * Used for display in the UI (icons, labels).\n */\nexport type LinkTypeConfig = {\n /** Machine-readable type identifier (e.g., \"issue\", \"pull_request\") */\n type: string;\n /** Human-readable label (e.g., \"Issue\", \"Pull Request\") */\n label: string;\n /** URL to an icon for this link type (light mode). Prefer Iconify `logos/*` URLs. */\n logo?: string;\n /** URL to an icon for dark mode. Use when the default logo is invisible on dark backgrounds (e.g., Iconify `simple-icons/*` with `?color=`). */\n logoDark?: string;\n /** URL to a monochrome icon (uses `currentColor`). Prefer Iconify `simple-icons/*` URLs without a `?color=` param. */\n logoMono?: string;\n /** Possible status values for this type */\n statuses?: Array<{\n /** Machine-readable status (e.g., \"open\", \"done\") */\n status: string;\n /** Human-readable label (e.g., \"Open\", \"Done\") */\n label: string;\n /** Tag to propagate to thread when this status is active (e.g., Tag.Done) */\n tag?: Tag;\n /** Whether this status represents completion (done, closed, merged, cancelled, etc.) */\n done?: boolean;\n /**\n * Mark the thread `active=true` in Plot when a link enters this status.\n * Use for messaging-style flags where the user has indicated they want\n * to act on the thread now — Gmail's \"starred\", Slack's \"later\", etc.\n * The Plot user can later un-flag the thread without breaking the\n * connector relationship.\n */\n active?: boolean;\n /**\n * Mark the thread `task=true` in Plot when a link enters this status.\n * Use for project-tracker assignments — Linear / Todoist / Jira / etc.\n * `task` puts the thread on the user's task list without flooding their\n * inbox under `active`: the user explicitly flips it to `active` when\n * they decide to start.\n */\n task?: boolean;\n /**\n * Mark the thread `to_read=true` in Plot when a link enters this status.\n * Use for connectors that explicitly track read-later state (Pocket\n * archives, Slack \"remind me\", etc).\n */\n toRead?: boolean;\n /**\n * @deprecated Use `active` (messaging) or `task` (project tracker) instead.\n * Treated as `task: true` for backward compatibility.\n *\n * Original meaning: whether this status represents the connector's\n * \"to-do\" / active state. When a user adds a thread to Plot's agenda,\n * done-status links flip to the status marked `todo: true` (e.g.,\n * Gmail's \"starred\", Linear's \"todo\").\n */\n todo?: boolean;\n /**\n * Default status applied when Plot asks the connector to create a new\n * item of this type via `Connector.onCreateLink`. Declaring at least one\n * status with `createDefault: true` is how a link type opts in to\n * Plot-initiated creation. At most one status per type should set this.\n */\n createDefault?: boolean;\n }>;\n /** Whether this link type supports displaying and changing the assignee */\n supportsAssignee?: boolean;\n /** Default thread creation mode for this link type: 'all' | 'actionable' | 'manual' */\n defaultCreateThreads?: string;\n};\n\n/**\n * Context passed to onChannelEnabled with plan-based sync hints.\n * Connectors can use these hints to limit initial sync scope.\n */\nexport type SyncContext = {\n /**\n * Earliest date to include in initial sync, based on the user's plan.\n *\n * Non-calendar connectors should use this as their date filter (timeMin,\n * created.gte, etc.) during initial sync. Calendar connectors should\n * ignore this for API queries (to avoid missing recurring events) — the\n * API layer filters non-recurring items automatically.\n *\n * Undefined when no limit applies.\n */\n syncHistoryMin?: Date;\n\n /**\n * True when this is a recovery dispatch after the connection's auth was\n * restored (the user re-authorized a previously-broken connection).\n *\n * The framework calls `onChannelEnabled` again for every channel that was\n * already enabled at the time of re-auth so the connector can recover from\n * the auth gap. Connectors should:\n *\n * 1. Drop any persisted incremental sync cursors / sync tokens so the\n * next sync re-walks history (the cursor may be stale or invalid —\n * Google Calendar invalidates syncTokens after ~7 days).\n * 2. Re-register webhooks (any prior subscription may have been\n * invalidated during the auth outage).\n * 3. Treat this as a backfill that walks history but does NOT spam\n * notifications — set `unread: false` and `archived: false` on\n * items as you would during initial sync.\n *\n * Most connectors can take the same code path as a fresh\n * `onChannelEnabled` for `recovering: true` as long as that path\n * overwrites stored state rather than appending to it.\n */\n recovering?: boolean;\n};\n\n/**\n * Built-in tool for managing OAuth authentication and channel resources.\n *\n * The Integrations tool:\n * 1. Manages channel resources (calendars, projects, etc.) per actor\n * 2. Returns tokens for the user who enabled sync on a channel\n * 3. Supports per-actor auth via actAs() for write-back operations\n * 4. Provides saveLink/saveContacts for Connectors to save data directly\n *\n * Connectors declare their provider, scopes, and channel lifecycle methods as\n * class properties and methods. The Integrations tool reads these automatically.\n * Auth and channel management is handled in the twist edit modal in Flutter.\n *\n * @example\n * ```typescript\n * class CalendarConnector extends Connector<CalendarConnector> {\n * readonly provider = AuthProvider.Google;\n * readonly scopes = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations),\n * };\n * }\n *\n * async getChannels(auth: Authorization, token: AuthToken): Promise<Channel[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n *\n * async onChannelEnabled(channel: Channel) {\n * // Start syncing\n * }\n *\n * async onChannelDisabled(channel: Channel) {\n * // Stop syncing\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a channel resource.\n *\n * Returns the token of the user who enabled sync on the given channel.\n * If the channel is not enabled or the token is expired/invalid, returns null.\n *\n * @param channelId - The channel resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n abstract get(channelId: string): Promise<AuthToken | null>;\n /**\n * Retrieves an access token for a channel resource.\n *\n * @param provider - The OAuth provider (deprecated, ignored for single-provider connectors)\n * @param channelId - The channel resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n * @deprecated Use get(channelId) instead. The provider is implicit from the connector.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, channelId: string): Promise<AuthToken | null>;\n\n /**\n * Execute a callback as a specific actor, requesting auth if needed.\n *\n * If the actor has a valid token, calls the callback immediately with it.\n * If the actor has no token, creates a private auth note in the specified\n * activity prompting them to connect. Once they authorize, this callback fires.\n *\n * @param provider - The OAuth provider\n * @param actorId - The actor to act as\n * @param activityId - The activity to create an auth note in (if needed)\n * @param callback - Function to call with the token\n * @param extraArgs - Additional arguments to pass to the callback\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract actAs<\n TArgs extends Serializable[],\n TCallback extends (token: AuthToken, ...args: TArgs) => any\n >(\n provider: AuthProvider,\n actorId: ActorId,\n activityId: Uuid,\n callback: TCallback,\n ...extraArgs: TArgs\n ): Promise<void>;\n\n /**\n * Saves a link with notes to the connector's priority.\n *\n * Creates a thread+link pair. The thread is a lightweight container;\n * the link holds the external entity data (source, meta, type, status, etc.).\n *\n * This method is available only to Connectors (not regular Twists).\n *\n * @param link - The link with notes to save\n * @returns Promise resolving to the saved thread's UUID, or null if the\n * link was filtered out (e.g. older than the plan's sync history limit)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveLink(link: NewLinkWithNotes): Promise<Uuid | null>;\n\n /**\n * Batch version of {@link saveLink} — saves many links in one call.\n *\n * Connectors syncing many items per page (e.g. calendar events, issues,\n * messages) should prefer this over looping `saveLink`. Each `saveLink`\n * crosses the runtime boundary and counts against the per-execution\n * request budget; `saveLinks` collapses N saves into a single crossing.\n *\n * Failures on individual links DO NOT abort the batch. A bad item lands\n * as `null` in its slot and the rest still save. This prevents one\n * malformed record from losing an entire page of sync progress.\n *\n * This method is available only to Connectors (not regular Twists).\n *\n * @param links - Array of links with notes to save\n * @returns Array of the same length and order as `links`. Each entry is\n * the saved thread's UUID, or `null` if the link was filtered out\n * (e.g. older than the plan's sync history limit) OR failed to save.\n * The two null causes are not distinguished; the save failure is\n * logged server-side.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveLinks(links: NewLinkWithNotes[]): Promise<(Uuid | null)[]>;\n\n /**\n * Saves contacts to the connector's priority.\n *\n * @param contacts - Array of contacts to save\n * @returns Promise resolving to the saved actors\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveContacts(contacts: NewContact[]): Promise<Actor[]>;\n\n /**\n * Archives links matching the given filter that were created by this connector.\n *\n * For each archived link's thread, if no other non-archived links remain,\n * the thread is also archived.\n *\n * @param filter - Filter criteria for which links to archive\n * @returns Promise that resolves when archiving is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract archiveLinks(filter: ArchiveLinkFilter): Promise<void>;\n\n /**\n * Sets or clears todo status on a thread owned by this connector.\n *\n * @param source - The link source URL identifying the thread\n * @param actorId - The user to set the todo for\n * @param todo - true to mark as todo, false to clear/complete\n * @param options - Additional options\n * @param options.date - The todo date (when todo=true). Defaults to today.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract setThreadToDo(\n source: string,\n actorId: ActorId,\n todo: boolean,\n options?: { date?: Date | string }\n ): Promise<void>;\n\n /**\n * Signal that initial bulk-sync (or recovery sync) for a channel is fully\n * complete. The Flutter app uses this to clear the \"syncing…\" indicator\n * on the connection.\n *\n * The framework automatically marks a channel as syncing when it dispatches\n * `onChannelEnabled` (whether initial-enable, auto-enable from\n * `setChannels`, or recovery after re-auth). Connectors do NOT need to\n * call anything to start tracking — only to signal completion.\n *\n * Call this exactly once when the initial backfill has finished (no more\n * pages, all phases exhausted). Do NOT call it on every incremental sync.\n *\n * If `onChannelEnabled` throws an unhandled exception, the framework\n * automatically clears the syncing state — connectors don't need a\n * `try/catch` to clear state on failure.\n *\n * No-op when no auth/user mapping exists for the channel (e.g. key-based\n * connectors that don't have a per-user OAuth association).\n *\n * @param channelId - The channel resource ID whose initial sync just finished\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract channelSyncCompleted(channelId: string): Promise<void>;\n\n /**\n * Flag a connection as needing re-authentication so the Flutter app\n * surfaces a re-auth prompt on the next sync.\n *\n * Call this when a connector's API call returns a permanent auth-style\n * error that the runtime can't observe through token refresh — e.g.\n * Slack `invalid_auth` / `token_revoked` / `not_authed`, or a 401 on a\n * provider that doesn't refresh. The runtime already flags reauth\n * automatically when an OAuth refresh permanently fails or when the\n * stored token is missing on a get(); only call this for cases the\n * runtime can't see.\n *\n * Idempotent: safe to call repeatedly; existing reauth flags are not\n * overwritten. No-op when the channel has no `enabledBy` actor (e.g.\n * key-based connectors).\n *\n * @param channelId - The channel resource ID whose token is bad\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract markNeedsReauth(channelId: string): Promise<void>;\n\n}\n\n/**\n * Filter criteria for archiving links.\n * All fields are optional; only provided fields are used for matching.\n */\nexport type ArchiveLinkFilter = {\n /** Filter by channel ID */\n channelId?: string;\n /** Filter by link type (e.g., \"issue\", \"pull_request\") */\n type?: string;\n /** Filter by link status (e.g., \"open\", \"closed\") */\n status?: string;\n /** Filter by metadata fields (uses containment matching) */\n meta?: Record<string, JSONValue>;\n};\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n /** Todoist OAuth provider for Todoist task management */\n Todoist = \"todoist\",\n /** Airtable OAuth provider for Airtable bases */\n Airtable = \"airtable\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
8
+ export default "import {\n type Actor,\n type ActorId,\n type NewContact,\n type NewLinkWithNotes,\n ITool,\n} from \"..\";\nimport type { JSONValue } from \"../utils/types\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getChannels() and managed by users in the twist setup/edit modal.\n */\nexport type Channel = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n /** Optional nested channel resources (e.g., subfolders) */\n children?: Channel[];\n /** Per-channel link type configs. Overrides twist-level linkTypes when present. */\n linkTypes?: LinkTypeConfig[];\n};\n\n/**\n * Describes a link type that a connector creates.\n * Used for display in the UI (icons, labels).\n */\nexport type LinkTypeConfig = {\n /** Machine-readable type identifier (e.g., \"issue\", \"pull_request\") */\n type: string;\n /** Human-readable label (e.g., \"Issue\", \"Pull Request\") */\n label: string;\n /**\n * Connector's word for a note on a linked item of this type — used by the\n * Flutter app to adapt note/composer copy (\"Add a comment\" on Linear,\n * \"Add a message\" on Slack, \"Add a reply\" on Gmail). Defaults to \"note\"\n * when omitted. Use the singular noun in title case (e.g. \"Comment\").\n */\n noteLabel?: string;\n /** URL to an icon for this link type (light mode). Prefer Iconify `logos/*` URLs. */\n logo?: string;\n /** URL to an icon for dark mode. Use when the default logo is invisible on dark backgrounds (e.g., Iconify `simple-icons/*` with `?color=`). */\n logoDark?: string;\n /** URL to a monochrome icon (uses `currentColor`). Prefer Iconify `simple-icons/*` URLs without a `?color=` param. */\n logoMono?: string;\n /** Possible status values for this type */\n statuses?: Array<{\n /** Machine-readable status (e.g., \"open\", \"done\") */\n status: string;\n /** Human-readable label (e.g., \"Open\", \"Done\") */\n label: string;\n /** Whether this status represents completion (done, closed, merged, cancelled, etc.) */\n done?: boolean;\n /**\n * Mark the thread `active=true` in Plot when a link enters this status.\n * Use for messaging-style flags where the user has indicated they want\n * to act on the thread now — Gmail's \"starred\", Slack's \"later\", etc.\n * The Plot user can later un-flag the thread without breaking the\n * connector relationship.\n */\n active?: boolean;\n /**\n * Marks this status as the connector's \"to-do\" / active state. When a\n * user brings a done thread back into Plot's agenda, done-status links\n * are flipped to the status marked `todo: true` (e.g. Gmail's \"starred\",\n * Linear's \"unstarted\"); connectors that don't mark one fall back to the\n * first non-done status.\n */\n todo?: boolean;\n }>;\n /** Whether this link type supports displaying and changing the assignee */\n supportsAssignee?: boolean;\n /** Default thread creation mode for this link type: 'all' | 'actionable' | 'manual' */\n defaultCreateThreads?: string;\n /**\n * Opt-in: declares this link type is composable from Plot via\n * `Connector.onCreateLink`. Omit to make the link type sync-only (no\n * \"Create new …\" picker entry).\n *\n * Connectors that need multiple compose modes for what users perceive as\n * the same kind of thing (e.g. Slack channel post vs DM) should declare\n * **separate linkTypes**, one per user-facing thread type. That keeps\n * each linkType isomorphic to one filter chip.\n */\n compose?: ComposeConfig;\n /**\n * Per-connector contact roles. Examples:\n * email → [{id:\"to\",label:\"To\",default:true},{id:\"cc\",label:\"CC\"},{id:\"bcc\",label:\"BCC\",hidden:true}]\n * calendar → [{id:\"required\",label:\"Required\",default:true},{id:\"optional\",label:\"Optional\"}]\n *\n * Plot uses this list to render a role picker on each contact chip in the\n * composer and to label non-default roles on existing threads. Exactly one\n * role should be marked `default: true`. Connectors that don't distinguish\n * roles (Slack, Linear) omit this field entirely.\n */\n contactRoles?: ContactRoleConfig[];\n /**\n * Whether contacts on an existing thread can be added, removed, or have\n * their role changed (email-style mid-thread recipient changes). When\n * false, the thread's contact list is fixed after creation. Defaults to\n * false when omitted.\n */\n supportsContactChanges?: boolean;\n /**\n * Declares how sharing on threads of this link type is scoped:\n *\n * - `\"thread\"` (default): one roster shared across all notes in the\n * thread. Native Plot threads, Slack DMs, calendar events.\n * - `\"channel\"`: visibility is the external channel's membership;\n * the per-thread `contacts` array is ignored for sharing UI.\n * Slack channels, Linear projects.\n * - `\"message\"`: each note carries its own recipient set via\n * `note.access_contacts`; the thread roster is the union across\n * all messages. Email.\n *\n * Omit to default to `\"thread\"`. When set to `\"message\"`, every\n * note this connector ingests must populate `access_contacts`\n * explicitly (never NULL).\n */\n sharingModel?: \"thread\" | \"channel\" | \"message\";\n};\n\n/**\n * Declares how a link type is composable from Plot via\n * `Connector.onCreateLink`. Attached to {@link LinkTypeConfig.compose}.\n */\nexport type ComposeConfig = {\n /**\n * Selects the destination model for the \"Create new …\" picker.\n *\n * - `\"channels\"` (default): one chip per enabled channel (e.g. a Linear\n * team, a Slack channel). Existing behaviour for task-tracker / calendar\n * connectors.\n * - `\"contacts\"`: one chip per connection (account); the user picks\n * recipients from their contacts. The runtime pre-resolves the chosen\n * Plot contacts to platform account IDs via the per-connection\n * `contact_external_account` rows and delivers them as\n * `CreateLinkDraft.recipients`. Contacts without a row for this specific\n * connection are filtered out of the picker — used by closed-roster\n * messaging platforms (Slack DM, Teams DM, Google Chat DM, LinkedIn DM).\n * - `\"addresses\"`: one chip per connection; the picker accepts any\n * contact with an addressable identifier (e.g. an email) or a free-form\n * typed address. The runtime fills `recipients` for contacts with a\n * connection-scoped row and falls back to the contact's primary address\n * (e.g. `contact.email`) when no row exists. Free-form addresses arrive\n * via the thread's `inviteEmails`. Used by open address spaces like\n * Gmail.\n */\n targets?: \"channels\" | \"contacts\" | \"addresses\";\n /**\n * Status to assign newly-created links. Should match an entry in the\n * parent linkType's `statuses[]`, OR a symbolic id that the connector's\n * `onCreateLink` resolves itself (e.g. Linear's `\"unstarted\"` category is\n * resolved per-team to a state UUID inside the connector — see\n * `connectors/linear/src/linear.ts`).\n */\n status: string;\n /**\n * Optional override for the picker chip / \"Create new …\" copy. Defaults\n * to the parent linkType's `label`. Use to disambiguate compose entries\n * when the parent label alone isn't specific enough (e.g. \"Direct\n * messages\" for a DM-mode compose on a chat connector).\n */\n label?: string;\n};\n\n/**\n * Declares one contact role for a connector's link type. See\n * `LinkTypeConfig.contactRoles`.\n */\nexport type ContactRoleConfig = {\n /** Stable machine id, e.g. \"to\" / \"cc\" / \"bcc\" / \"required\" / \"optional\". */\n id: string;\n /** Display label shown next to a contact chip, e.g. \"To\", \"CC\", \"Required\". */\n label: string;\n /** Exactly one role per linkType should be marked default. */\n default?: boolean;\n /**\n * Hidden roles are visible only to (a) the contact themselves and\n * (b) the user who added them. The API filters them out of every other\n * viewer's `thread.contacts` and `thread.contactMeta`. Use for BCC-style\n * semantics where other recipients must not see the hidden contact.\n */\n hidden?: boolean;\n};\n\n/**\n * Context passed to onChannelEnabled with plan-based sync hints.\n * Connectors can use these hints to limit initial sync scope.\n */\nexport type SyncContext = {\n /**\n * Earliest date to include in initial sync, based on the user's plan.\n *\n * Non-calendar connectors should use this as their date filter (timeMin,\n * created.gte, etc.) during initial sync. Calendar connectors should\n * ignore this for API queries (to avoid missing recurring events) — the\n * API layer filters non-recurring items automatically.\n *\n * Undefined when no limit applies.\n */\n syncHistoryMin?: Date;\n\n /**\n * True when this is a recovery dispatch after the connection's auth was\n * restored (the user re-authorized a previously-broken connection).\n *\n * The framework calls `onChannelEnabled` again for every channel that was\n * already enabled at the time of re-auth so the connector can recover from\n * the auth gap. Connectors should:\n *\n * 1. Drop any persisted incremental sync cursors / sync tokens so the\n * next sync re-walks history (the cursor may be stale or invalid —\n * Google Calendar invalidates syncTokens after ~7 days).\n * 2. Re-register webhooks (any prior subscription may have been\n * invalidated during the auth outage).\n * 3. Treat this as a backfill that walks history but does NOT spam\n * notifications — set `unread: false` and `archived: false` on\n * items as you would during initial sync.\n *\n * Most connectors can take the same code path as a fresh\n * `onChannelEnabled` for `recovering: true` as long as that path\n * overwrites stored state rather than appending to it.\n */\n recovering?: boolean;\n};\n\n/**\n * Built-in tool for managing OAuth authentication and channel resources.\n *\n * The Integrations tool:\n * 1. Manages channel resources (calendars, projects, etc.) per actor\n * 2. Returns tokens for the user who enabled sync on a channel\n * 3. Supports per-actor auth via actAs() for write-back operations\n * 4. Provides saveLink/saveContacts for Connectors to save data directly\n *\n * Connectors declare their provider, scopes, and channel lifecycle methods as\n * class properties and methods. The Integrations tool reads these automatically.\n * Auth and channel management is handled in the twist edit modal in Flutter.\n *\n * @example\n * ```typescript\n * class CalendarConnector extends Connector<CalendarConnector> {\n * readonly provider = AuthProvider.Google;\n * readonly scopes = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations),\n * };\n * }\n *\n * async getChannels(auth: Authorization, token: AuthToken): Promise<Channel[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n *\n * async onChannelEnabled(channel: Channel) {\n * // Start syncing\n * }\n *\n * async onChannelDisabled(channel: Channel) {\n * // Stop syncing\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a channel resource.\n *\n * Returns the token of the user who enabled sync on the given channel.\n * If the channel is not enabled or the token is expired/invalid, returns null.\n *\n * @param channelId - The channel resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n abstract get(channelId: string): Promise<AuthToken | null>;\n /**\n * Retrieves an access token for a channel resource.\n *\n * @param provider - The OAuth provider (deprecated, ignored for single-provider connectors)\n * @param channelId - The channel resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n * @deprecated Use get(channelId) instead. The provider is implicit from the connector.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, channelId: string): Promise<AuthToken | null>;\n\n /**\n * Saves a link with notes to the connector's focus.\n *\n * Creates a thread+link pair. The thread is a lightweight container;\n * the link holds the external entity data (source, meta, type, status, etc.).\n *\n * This method is available only to Connectors (not regular Twists).\n *\n * @param link - The link with notes to save\n * @returns Promise resolving to the saved thread's UUID, or null if the\n * link was filtered out (e.g. older than the plan's sync history limit)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveLink(link: NewLinkWithNotes): Promise<Uuid | null>;\n\n /**\n * Batch version of {@link saveLink} — saves many links in one call.\n *\n * Connectors syncing many items per page (e.g. calendar events, issues,\n * messages) should prefer this over looping `saveLink`. Each `saveLink`\n * crosses the runtime boundary and counts against the per-execution\n * request budget; `saveLinks` collapses N saves into a single crossing.\n *\n * Failures on individual links DO NOT abort the batch. A bad item lands\n * as `null` in its slot and the rest still save. This prevents one\n * malformed record from losing an entire page of sync progress.\n *\n * This method is available only to Connectors (not regular Twists).\n *\n * @param links - Array of links with notes to save\n * @returns Array of the same length and order as `links`. Each entry is\n * the saved thread's UUID, or `null` if the link was filtered out\n * (e.g. older than the plan's sync history limit) OR failed to save.\n * The two null causes are not distinguished; the save failure is\n * logged server-side.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveLinks(links: NewLinkWithNotes[]): Promise<(Uuid | null)[]>;\n\n /**\n * Upserts contacts into the connector's focus without requiring a Link.\n *\n * Use this for messaging connectors to bulk-sync workspace members so the\n * recipient picker can filter contacts by reachable platform account. Populate\n * `NewContact.source` to persist `contact_external_account` rows (the platform\n * identity used to address the contact). Returns one `Actor` per input, in order.\n *\n * @param contacts - Contacts to upsert, keyed by `source`/`key`\n * @returns Promise resolving to the saved actors, 1:1 with input order\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract saveContacts(contacts: NewContact[]): Promise<Actor[]>;\n\n /**\n * Archives links matching the given filter that were created by this connector.\n *\n * For each archived link's thread, if no other non-archived links remain,\n * the thread is also archived.\n *\n * @param filter - Filter criteria for which links to archive\n * @returns Promise that resolves when archiving is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract archiveLinks(filter: ArchiveLinkFilter): Promise<void>;\n\n /**\n * Sets or clears todo status on a thread owned by this connector.\n *\n * @param source - The link source URL identifying the thread\n * @param actorId - The user to set the todo for\n * @param todo - true to mark as todo, false to clear/complete\n * @param options - Additional options\n * @param options.date - The todo date (when todo=true). Defaults to today.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract setThreadToDo(\n source: string,\n actorId: ActorId,\n todo: boolean,\n options?: { date?: Date | string }\n ): Promise<void>;\n\n /**\n * Signal that initial bulk-sync (or recovery sync) for a channel is fully\n * complete. The Flutter app uses this to clear the \"syncing…\" indicator\n * on the connection.\n *\n * The framework automatically marks a channel as syncing when it dispatches\n * `onChannelEnabled` (whether initial-enable, auto-enable from\n * `setChannels`, or recovery after re-auth). Connectors do NOT need to\n * call anything to start tracking — only to signal completion.\n *\n * Call this exactly once when the initial backfill has finished (no more\n * pages, all phases exhausted). Do NOT call it on every incremental sync.\n *\n * If `onChannelEnabled` throws an unhandled exception, the framework\n * automatically clears the syncing state — connectors don't need a\n * `try/catch` to clear state on failure.\n *\n * No-op when no auth/user mapping exists for the channel (e.g. key-based\n * connectors that don't have a per-user OAuth association).\n *\n * @param channelId - The channel resource ID whose initial sync just finished\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract channelSyncCompleted(channelId: string): Promise<void>;\n\n /**\n * Flag a connection as needing re-authentication so the Flutter app\n * surfaces a re-auth prompt on the next sync.\n *\n * Call this when a connector's API call returns a permanent auth-style\n * error that the runtime can't observe through token refresh — e.g.\n * Slack `invalid_auth` / `token_revoked` / `not_authed`, or a 401 on a\n * provider that doesn't refresh. The runtime already flags reauth\n * automatically when an OAuth refresh permanently fails or when the\n * stored token is missing on a get(); only call this for cases the\n * runtime can't see.\n *\n * Idempotent: safe to call repeatedly; existing reauth flags are not\n * overwritten. No-op when the channel has no `enabledBy` actor (e.g.\n * key-based connectors).\n *\n * @param channelId - The channel resource ID whose token is bad\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract markNeedsReauth(channelId: string): Promise<void>;\n\n}\n\n/**\n * Filter criteria for archiving links.\n * All fields are optional; only provided fields are used for matching.\n */\nexport type ArchiveLinkFilter = {\n /** Filter by channel ID */\n channelId?: string;\n /** Filter by link type (e.g., \"issue\", \"pull_request\") */\n type?: string;\n /** Filter by link status (e.g., \"open\", \"closed\") */\n status?: string;\n /** Filter by metadata fields (uses containment matching) */\n meta?: Record<string, JSONValue>;\n};\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n /** Todoist OAuth provider for Todoist task management */\n Todoist = \"todoist\",\n /** Airtable OAuth provider for Airtable bases */\n Airtable = \"airtable\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import {\n type Action,\n type Thread,\n type ThreadUpdate,\n type Actor,\n type ActorId,\n ITool,\n type Link,\n type LinkUpdate,\n type NewThread,\n type NewThreadWithNotes,\n type NewNote,\n type NewPriority,\n type Note,\n type NoteUpdate,\n type PlanOperation,\n type Priority,\n type PriorityUpdate,\n Uuid,\n} from \"..\";\nimport {\n type Schedule,\n type NewSchedule,\n} from \"../schedule\";\nimport type { Callback } from \"./callbacks\";\n\nexport enum ThreadAccess {\n /**\n * Create new Note on a Thread where the twist was mentioned.\n * Add/remove tags on Thread or Note where the twist was mentioned.\n */\n Respond,\n /**\n * Create new Thread.\n * Create new Note in a Thread the twist created.\n * All Respond permissions.\n */\n Create,\n /**\n * List/query all Threads owned by the twist's user.\n * Update any Thread (title, tags, archived, type, priority) regardless of creator.\n * Create Notes on any Thread (not just own or mentioned).\n * All Create permissions.\n */\n Full,\n}\n\nexport enum PriorityAccess {\n /**\n * Create new Priorities under the twist owner's priority tree.\n * Update Priorities created by the twist.\n */\n Create,\n /**\n * Read all Priorities owned by the twist's user.\n * Create new Priorities under the twist owner's priority tree.\n * Update and archive any Priority owned by the twist's user.\n */\n Full,\n}\n\nexport enum ContactAccess {\n /** Read existing contact details. Without this, only the ID will be provided. */\n Read,\n}\n\nexport enum LinkAccess {\n /** Read links on any thread owned by the twist's user. */\n Read,\n /** Read + update links, including moving links between threads owned by the twist's user. */\n Full,\n}\n\n/**\n * Intent handler for thread mentions.\n * Defines how the twist should respond when mentioned in a thread.\n */\nexport type NoteIntentHandler = {\n /** Human-readable description of what this intent handles */\n description: string;\n /** Example phrases or activity content that would match this intent */\n examples: string[];\n /** The function to call when this intent is matched */\n handler: (note: Note) => Promise<void>;\n};\n\n/**\n * Filter for querying links from connected source channels.\n */\nexport type LinkFilter = {\n /** Only return links from these channel IDs. */\n channelIds?: string[];\n /** Only return links created/updated after this date. */\n since?: Date;\n /** Only return links of this type. */\n type?: string;\n /** Maximum number of links to return. */\n limit?: number;\n};\n\ntype SearchResultBase = {\n thread: { id: string; title: string | null };\n priority: { id: string; title: string | null };\n similarity: number;\n};\n\nexport type NoteSearchResult = SearchResultBase & {\n type: 'note';\n id: string;\n content: string | null;\n};\n\nexport type LinkSearchResult = SearchResultBase & {\n type: 'link';\n id: string;\n title: string | null;\n sourceUrl: string | null;\n content: string | null;\n};\n\nexport type SearchResult = NoteSearchResult | LinkSearchResult;\n\n/** Default number of search results returned */\nexport const SEARCH_DEFAULT_LIMIT = 10;\n/** Maximum number of search results allowed */\nexport const SEARCH_MAX_LIMIT = 30;\n\nexport type SearchOptions = {\n /** Max results to return (default: 10, max: 30) */\n limit?: number;\n /** Minimum similarity score 0-1 (default: 0.3) */\n threshold?: number;\n /**\n * Scope search to this priority + descendants. Must be owned by the twist\n * owner. When omitted, the server scopes the search to the owner's entire\n * priority tree.\n */\n priorityId?: string;\n};\n\n/**\n * Built-in tool for interacting with the core Plot data layer.\n *\n * The Plot tool provides twists with the ability to create and manage threads,\n * priorities, and contacts within the Plot system. This is the primary interface\n * for twists to persist data and interact with the Plot database.\n *\n * @example\n * ```typescript\n * class MyTwist extends Twist {\n * private plot: Plot;\n *\n * constructor(id: string, tools: ToolBuilder) {\n * super();\n * this.plot = tools.get(Plot);\n * }\n *\n * async activate() {\n * // Create a welcome thread\n * await this.plot.createThread({\n * title: \"Welcome to Plot!\",\n * actions: [{\n * title: \"Get Started\",\n * type: ActionType.external,\n * url: \"https://plot.day/docs\"\n * }]\n * });\n * }\n * }\n * ```\n */\nexport abstract class Plot extends ITool {\n /**\n * Configuration options for the Plot tool.\n *\n * **Important**: All permissions must be explicitly requested. There are no default permissions.\n *\n * @example\n * ```typescript\n * // Minimal configuration with required permissions\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot, {\n * thread: {\n * access: ThreadAccess.Create\n * }\n * })\n * };\n * }\n *\n * // Full configuration with callbacks\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot, {\n * thread: {\n * access: ThreadAccess.Create,\n * },\n * note: {\n * intents: [{\n * description: \"Schedule meetings\",\n * examples: [\"Schedule a meeting tomorrow\"],\n * handler: this.onSchedulingIntent\n * }],\n * },\n * link: true,\n * priority: {\n * access: PriorityAccess.Full\n * },\n * contact: {\n * access: ContactAccess.Read\n * }\n * })\n * };\n * }\n * ```\n */\n static readonly Options: {\n thread?: {\n /**\n * Capability to create Notes and modify tags.\n * Must be explicitly set to grant permissions.\n */\n access?: ThreadAccess;\n /** When true, auto-mention this twist on new notes in threads where it authored content. */\n defaultMention?: boolean;\n };\n note?: {\n /** When true, auto-mention this twist on new notes in threads where it was @-mentioned. */\n defaultMention?: boolean;\n /**\n * Respond to mentions in notes.\n *\n * When a note mentions this twist, the system will match the note\n * content against these intents and call the matching handler.\n *\n * @example\n * ```typescript\n * intents: [{\n * description: \"Schedule or reschedule calendar events\",\n * examples: [\"Schedule a meeting tomorrow at 2pm\", \"Move my 3pm meeting to 4pm\"],\n * handler: this.onSchedulingRequest\n * }, {\n * description: \"Find available meeting times\",\n * examples: [\"When am I free this week?\", \"Find time for a 1 hour meeting\"],\n * handler: this.onAvailabilityRequest\n * }]\n * ```\n */\n intents?: NoteIntentHandler[];\n };\n /** Enable link processing from connected source channels. */\n link?: true | {\n /** Access level for links. When omitted with `link: true`, only source channel links are accessible. */\n access?: LinkAccess;\n };\n priority?: {\n access?: PriorityAccess;\n };\n contact?: {\n access?: ContactAccess;\n };\n /** Enable semantic search across notes and links owned by the twist's user. */\n search?: true;\n /**\n * When true, admin write operations (on threads/notes/links/priorities not created by this twist)\n * require user approval via plan actions instead of executing immediately.\n * Read operations and operations on the twist's own content still work directly.\n */\n requireApproval?: boolean;\n };\n\n /**\n * Creates a new thread in the Plot system.\n *\n * The thread will be automatically assigned an ID and author information\n * based on the current execution context. All other fields from NewThread\n * will be preserved in the created thread.\n *\n * @param thread - The thread data to create\n * @returns Promise resolving to the created thread's ID\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createThread(\n thread: NewThread | NewThreadWithNotes\n ): Promise<Uuid>;\n\n /**\n * Creates multiple threads in a single batch operation.\n *\n * This method efficiently creates multiple threads at once, which is\n * more performant than calling createThread() multiple times individually.\n * All threads are created with the same author and access control rules.\n *\n * @param threads - Array of thread data to create\n * @returns Promise resolving to array of created thread IDs\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createThreads(\n threads: (NewThread | NewThreadWithNotes)[]\n ): Promise<Uuid[]>;\n\n /**\n * Updates an existing thread in the Plot system.\n *\n * **Important**: This method only updates existing threads. It will throw an error\n * if the thread does not exist. Use `createThread()` to create or update (upsert)\n * threads.\n *\n * Only the fields provided in the update object will be modified - all other fields\n * remain unchanged. This enables partial updates without needing to fetch and resend\n * the entire thread object.\n *\n * For tags, provide a Record<number, boolean> where true adds a tag and false removes it.\n * Tags not included in the update remain unchanged.\n *\n * When updating the parent, the thread's path will be automatically recalculated to\n * maintain the correct hierarchical structure.\n *\n * Scheduling is handled separately via `createSchedule()` / `updateSchedule()`.\n *\n * @param thread - The thread update containing the ID or source and fields to change\n * @returns Promise that resolves when the update is complete\n * @throws Error if the thread does not exist\n *\n * @example\n * ```typescript\n * // Mark a task as complete\n * await this.plot.updateThread({\n * id: \"task-123\",\n * done: new Date()\n * });\n *\n * // Add and remove tags\n * await this.plot.updateThread({\n * id: \"thread-789\",\n * tags: {\n * 1: true, // Add tag with ID 1\n * 2: false // Remove tag with ID 2\n * }\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateThread(thread: ThreadUpdate): Promise<void>;\n\n /**\n * Retrieves all notes within a thread.\n *\n * Notes are detailed entries within a thread, ordered by creation time.\n * Each note can contain markdown content, actions, and other detailed information\n * related to the parent thread.\n *\n * @param thread - The thread whose notes to retrieve\n * @returns Promise resolving to array of notes in the thread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getNotes(thread: Thread): Promise<Note[]>;\n\n /**\n * Creates a new note in a thread.\n *\n * Notes provide detailed content within a thread, supporting markdown,\n * actions, and other rich content. The note will be automatically assigned\n * an ID and author information based on the current execution context.\n *\n * @param note - The note data to create\n * @returns Promise resolving to the created note's ID\n *\n * @example\n * ```typescript\n * // Create a note with content\n * await this.plot.createNote({\n * thread: { id: \"thread-123\" },\n * note: \"Discussion notes from the meeting...\",\n * contentType: \"markdown\"\n * });\n *\n * // Create a note with actions\n * await this.plot.createNote({\n * thread: { id: \"thread-456\" },\n * note: \"Meeting recording available\",\n * actions: [{\n * type: ActionType.external,\n * title: \"View Recording\",\n * url: \"https://example.com/recording\"\n * }]\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createNote(note: NewNote): Promise<Uuid>;\n\n /**\n * Creates multiple notes in a single batch operation.\n *\n * This method efficiently creates multiple notes at once, which is\n * more performant than calling createNote() multiple times individually.\n * All notes are created with the same author and access control rules.\n *\n * @param notes - Array of note data to create\n * @returns Promise resolving to array of created note IDs\n *\n * @example\n * ```typescript\n * // Create multiple notes in one batch\n * await this.plot.createNotes([\n * {\n * thread: { id: \"thread-123\" },\n * note: \"First message in thread\"\n * },\n * {\n * thread: { id: \"thread-123\" },\n * note: \"Second message in thread\"\n * }\n * ]);\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createNotes(notes: NewNote[]): Promise<Uuid[]>;\n\n /**\n * Updates an existing note in the Plot system.\n *\n * **Important**: This method only updates existing notes. It will throw an error\n * if the note does not exist. Use `createNote()` to create or update (upsert) notes.\n *\n * Only the fields provided in the update object will be modified - all other fields\n * remain unchanged. This enables partial updates without needing to fetch and resend\n * the entire note object.\n *\n * @param note - The note update containing the ID or key and fields to change\n * @returns Promise that resolves when the update is complete\n * @throws Error if the note does not exist\n *\n * @example\n * ```typescript\n * // Update note content\n * await this.plot.updateNote({\n * id: \"note-123\",\n * note: \"Updated content with more details\"\n * });\n *\n * // Add tags to a note\n * await this.plot.updateNote({\n * id: \"note-456\",\n * twistTags: {\n * [Tag.Important]: true\n * }\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateNote(note: NoteUpdate): Promise<void>;\n\n /**\n * Retrieves a thread by ID or source.\n *\n * This method enables lookup of threads either by their unique ID or by their\n * source identifier (canonical URL from an external system). Archived threads\n * are included in the results.\n *\n * @param thread - Thread lookup by ID or source\n * @returns Promise resolving to the matching thread or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getThread(\n thread: { id: Uuid } | { source: string }\n ): Promise<Thread | null>;\n\n /**\n * Retrieves a note by ID or key.\n *\n * This method enables lookup of notes either by their unique ID or by their\n * key (unique identifier within the thread). Archived notes are included\n * in the results.\n *\n * @param note - Note lookup by ID or key\n * @returns Promise resolving to the matching note or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getNote(note: { id: Uuid } | { key: string }): Promise<Note | null>;\n\n /**\n * Creates a new priority in the Plot system.\n *\n * Priorities serve as organizational containers for threads and twists.\n * The created priority will be automatically assigned a unique ID.\n *\n * @param priority - The priority data to create\n * @returns Promise resolving to the complete created priority\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createPriority(priority: NewPriority): Promise<Priority & { created: boolean }>;\n\n /**\n * Retrieves a priority by ID or key.\n *\n * Archived priorities are included in the results.\n *\n * @param priority - Priority lookup by ID or key\n * @returns Promise resolving to the matching priority or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getPriority(\n priority: { id: Uuid } | { key: string }\n ): Promise<Priority | null>;\n\n /**\n * Updates an existing priority in the Plot system.\n *\n * The priority is identified by either its ID or key.\n * Only the fields specified in the update will be changed.\n *\n * @param update - Priority update containing ID/key and fields to change\n * @returns Promise that resolves when the update is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updatePriority(update: PriorityUpdate): Promise<void>;\n\n /**\n * Retrieves actors by their IDs.\n *\n * Actors represent users, contacts, or twists in the Plot system.\n * This method requires ContactAccess.Read permission.\n *\n * @param ids - Array of actor IDs to retrieve\n * @returns Promise resolving to array of actors\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getActors(ids: ActorId[]): Promise<Actor[]>;\n\n /**\n * Returns the full Actor for the user who installed this twist.\n * Useful for per-user operations like schedule creation, or when\n * the owner's name or email is needed.\n */\n abstract getOwner(): Promise<Actor>;\n\n /**\n * Returns the user ID (`twist_instance.owner_id`) that installed this\n * twist. This is the same value exposed on Twist via `this.userId`.\n */\n abstract getUserId(): Promise<string>;\n\n /**\n * Creates a new schedule for a thread.\n *\n * Schedules define when a thread occurs in time. A thread can have\n * multiple schedules (shared and per-user).\n *\n * @param schedule - The schedule data to create\n * @returns Promise resolving to the created schedule\n *\n * @example\n * ```typescript\n * // Schedule a timed event\n * const threadId = await this.plot.createThread({\n * title: \"Team standup\"\n * });\n * await this.plot.createSchedule({\n * threadId,\n * start: new Date(\"2025-01-15T10:00:00Z\"),\n * end: new Date(\"2025-01-15T10:30:00Z\"),\n * recurrenceRule: \"FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\"\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createSchedule(schedule: NewSchedule): Promise<Schedule>;\n\n /**\n * Retrieves all schedules for a thread.\n *\n * @param threadId - The thread whose schedules to retrieve\n * @returns Promise resolving to array of schedules for the thread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getSchedules(threadId: Uuid): Promise<Schedule[]>;\n\n /**\n * Retrieves links from connected source channels.\n *\n * Requires `link: true` in Plot options.\n *\n * @param filter - Optional filter criteria for links\n * @returns Promise resolving to array of links with their notes\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getLinks(filter?: LinkFilter): Promise<Array<{ link: Link; notes: Note[] }>>;\n\n /**\n * Searches notes and links using semantic similarity.\n *\n * Requires `search: true` in Plot options.\n *\n * @param query - The search query text\n * @param options - Optional search configuration\n * @returns Promise resolving to array of search results ordered by similarity\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract search(query: string, options?: SearchOptions): Promise<SearchResult[]>;\n\n /**\n * Lists threads owned by the twist's user.\n *\n * Requires `ThreadAccess.Full`.\n *\n * @param options - Query options for filtering threads\n * @returns Promise resolving to array of threads\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getThreads(options?: {\n /**\n * Priority to list threads from. Must be owned by the twist owner.\n * When omitted, defaults to the owner's root priority.\n */\n priorityId?: Uuid;\n /** Include threads from descendant priorities. Default: true. */\n includeDescendants?: boolean;\n /** Include archived threads. Default: false. */\n includeArchived?: boolean;\n /** Maximum number of threads to return. Default: 50, max: 200. */\n limit?: number;\n /** Number of threads to skip for pagination. Default: 0. */\n offset?: number;\n }): Promise<Thread[]>;\n\n /**\n * Lists priorities owned by the twist's user.\n *\n * Requires `PriorityAccess.Full`.\n *\n * @param options - Query options for filtering priorities\n * @returns Promise resolving to array of priorities\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getPriorities(options?: {\n /**\n * Parent priority to list children of. Must be owned by the twist\n * owner. When omitted, defaults to the owner's root priority.\n */\n parentId?: Uuid;\n /** Include all descendants, not just direct children. Default: false. */\n includeDescendants?: boolean;\n /** Include archived priorities. Default: false. */\n includeArchived?: boolean;\n }): Promise<Priority[]>;\n\n /**\n * Updates a link.\n *\n * Requires `LinkAccess.Full`. Set `threadId` to move the link to a different thread.\n *\n * @param link - The link update containing the ID and fields to change\n * @returns Promise that resolves when the update is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateLink(link: LinkUpdate): Promise<void>;\n\n /**\n * Creates a plan of operations for user approval.\n *\n * Returns an Action that can be attached to a note. The user can approve,\n * deny, or request changes. On approval, operations are executed by the API.\n *\n * Requires `requireApproval: true` in Plot options.\n *\n * @param options - Plan configuration\n * @returns An Action of type `plan` to attach to a note\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createPlan(options: {\n /** Human-readable title summarizing the plan */\n title: string;\n /** Array of operations to execute on approval */\n operations: PlanOperation[];\n /** Callback invoked with (action, approved: boolean) when the user responds */\n callback: Callback;\n }): Action;\n}\n";
8
+ export default "import {\n type Action,\n type Thread,\n type ThreadUpdate,\n type Actor,\n type ActorId,\n ITool,\n type Link,\n type LinkUpdate,\n type NewThread,\n type NewThreadWithNotes,\n type NewNote,\n type NewFocus,\n type Note,\n type NoteUpdate,\n type PlanOperation,\n type Focus,\n type FocusUpdate,\n Uuid,\n} from \"..\";\nimport {\n type Schedule,\n type NewSchedule,\n} from \"../schedule\";\nimport type { Callback } from \"./callbacks\";\n\nexport enum ThreadAccess {\n /**\n * Create new Note on a Thread where the twist was mentioned.\n * Add/remove tags on Thread or Note where the twist was mentioned.\n */\n Respond,\n /**\n * Create new Thread.\n * Create new Note in a Thread the twist created.\n * All Respond permissions.\n */\n Create,\n /**\n * List/query all Threads owned by the twist's user.\n * Update any Thread (title, tags, archived, type, focus) regardless of creator.\n * Create Notes on any Thread (not just own or mentioned).\n * All Create permissions.\n */\n Full,\n}\n\nexport enum FocusAccess {\n /**\n * Create new Focuses for the twist owner.\n * Update Focuses created by the twist.\n */\n Create,\n /**\n * Read all Focuses owned by the twist's user.\n * Create new Focuses for the twist owner.\n * Update and archive any Focus owned by the twist's user.\n */\n Full,\n}\n\nexport enum ContactAccess {\n /** Read existing contact details. Without this, only the ID will be provided. */\n Read,\n}\n\nexport enum LinkAccess {\n /** Read links on any thread owned by the twist's user. */\n Read,\n /** Read + update links, including moving links between threads owned by the twist's user. */\n Full,\n}\n\n/**\n * Intent handler for thread mentions.\n * Defines how the twist should respond when mentioned in a thread.\n */\nexport type NoteIntentHandler = {\n /** Human-readable description of what this intent handles */\n description: string;\n /** Example phrases or activity content that would match this intent */\n examples: string[];\n /** The function to call when this intent is matched */\n handler: (note: Note) => Promise<void>;\n};\n\n/**\n * Filter for querying links from connected source channels.\n */\nexport type LinkFilter = {\n /** Only return links from these channel IDs. */\n channelIds?: string[];\n /** Only return links created/updated after this date. */\n since?: Date;\n /** Only return links of this type. */\n type?: string;\n /** Maximum number of links to return. */\n limit?: number;\n};\n\ntype SearchResultBase = {\n thread: { id: string; title: string | null };\n focus: { id: string; title: string | null };\n similarity: number;\n};\n\nexport type NoteSearchResult = SearchResultBase & {\n type: 'note';\n id: string;\n content: string | null;\n};\n\nexport type LinkSearchResult = SearchResultBase & {\n type: 'link';\n id: string;\n title: string | null;\n sourceUrl: string | null;\n content: string | null;\n};\n\nexport type SearchResult = NoteSearchResult | LinkSearchResult;\n\n/** Default number of search results returned */\nexport const SEARCH_DEFAULT_LIMIT = 10;\n/** Maximum number of search results allowed */\nexport const SEARCH_MAX_LIMIT = 30;\n\nexport type SearchOptions = {\n /** Max results to return (default: 10, max: 30) */\n limit?: number;\n /** Minimum similarity score 0-1 (default: 0.3) */\n threshold?: number;\n /**\n * Scope search to this focus. Must be owned by the twist owner. When\n * omitted, the server scopes the search across all of the owner's focuses.\n */\n focusId?: string;\n};\n\n/**\n * Built-in tool for interacting with the core Plot data layer.\n *\n * The Plot tool provides twists with the ability to create and manage threads,\n * focuses, and contacts within the Plot system. This is the primary interface\n * for twists to persist data and interact with the Plot database.\n *\n * @example\n * ```typescript\n * class MyTwist extends Twist {\n * private plot: Plot;\n *\n * constructor(id: string, tools: ToolBuilder) {\n * super();\n * this.plot = tools.get(Plot);\n * }\n *\n * async activate() {\n * // Create a welcome thread\n * await this.plot.createThread({\n * title: \"Welcome to Plot!\",\n * actions: [{\n * title: \"Get Started\",\n * type: ActionType.external,\n * url: \"https://plot.day/docs\"\n * }]\n * });\n * }\n * }\n * ```\n */\nexport abstract class Plot extends ITool {\n /**\n * Configuration options for the Plot tool.\n *\n * **Important**: All permissions must be explicitly requested. There are no default permissions.\n *\n * @example\n * ```typescript\n * // Minimal configuration with required permissions\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot, {\n * thread: {\n * access: ThreadAccess.Create\n * }\n * })\n * };\n * }\n *\n * // Full configuration with callbacks\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot, {\n * thread: {\n * access: ThreadAccess.Create,\n * },\n * note: {\n * intents: [{\n * description: \"Schedule meetings\",\n * examples: [\"Schedule a meeting tomorrow\"],\n * handler: this.onSchedulingIntent\n * }],\n * },\n * link: true,\n * focus: {\n * access: FocusAccess.Full\n * },\n * contact: {\n * access: ContactAccess.Read\n * }\n * })\n * };\n * }\n * ```\n */\n static readonly Options: {\n thread?: {\n /**\n * Capability to create Notes and modify tags.\n * Must be explicitly set to grant permissions.\n */\n access?: ThreadAccess;\n /** When true, auto-mention this twist on new notes in threads where it authored content. */\n defaultMention?: boolean;\n };\n note?: {\n /** When true, auto-mention this twist on new notes in threads where it was @-mentioned. */\n defaultMention?: boolean;\n /**\n * Respond to mentions in notes.\n *\n * When a note mentions this twist, the system will match the note\n * content against these intents and call the matching handler.\n *\n * @example\n * ```typescript\n * intents: [{\n * description: \"Schedule or reschedule calendar events\",\n * examples: [\"Schedule a meeting tomorrow at 2pm\", \"Move my 3pm meeting to 4pm\"],\n * handler: this.onSchedulingRequest\n * }, {\n * description: \"Find available meeting times\",\n * examples: [\"When am I free this week?\", \"Find time for a 1 hour meeting\"],\n * handler: this.onAvailabilityRequest\n * }]\n * ```\n */\n intents?: NoteIntentHandler[];\n /**\n * Single conversational handler for mentions.\n *\n * When set, EVERY mention of this twist is routed directly to this\n * handler — intent matching (and the built-in \"What can you do?\" /\n * \"Remove yourself\" intents) is skipped. Use this to build a\n * general-purpose conversational assistant that responds to any\n * request, rather than classifying into a fixed set of `intents`.\n *\n * `handler` and `intents` are mutually exclusive; when both are\n * present, `handler` takes precedence and `intents` is ignored.\n *\n * @example\n * ```typescript\n * note: {\n * defaultMention: true,\n * handler: this.respond, // (note: Note) => Promise<void>\n * }\n * ```\n */\n handler?: (note: Note) => Promise<void>;\n };\n /** Enable link processing from connected source channels. */\n link?: true | {\n /** Access level for links. When omitted with `link: true`, only source channel links are accessible. */\n access?: LinkAccess;\n };\n focus?: {\n access?: FocusAccess;\n };\n contact?: {\n access?: ContactAccess;\n };\n /** Enable semantic search across notes and links owned by the twist's user. */\n search?: true;\n /**\n * When true, admin write operations (on threads/notes/links/focuses not created by this twist)\n * require user approval via plan actions instead of executing immediately.\n * Read operations and operations on the twist's own content still work directly.\n */\n requireApproval?: boolean;\n };\n\n /**\n * Creates a new thread in the Plot system.\n *\n * The thread will be automatically assigned an ID and author information\n * based on the current execution context. All other fields from NewThread\n * will be preserved in the created thread.\n *\n * @param thread - The thread data to create\n * @returns Promise resolving to the created thread's ID\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createThread(\n thread: NewThread | NewThreadWithNotes\n ): Promise<Uuid>;\n\n /**\n * Creates multiple threads in a single batch operation.\n *\n * This method efficiently creates multiple threads at once, which is\n * more performant than calling createThread() multiple times individually.\n * All threads are created with the same author and access control rules.\n *\n * @param threads - Array of thread data to create\n * @returns Promise resolving to array of created thread IDs\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createThreads(\n threads: (NewThread | NewThreadWithNotes)[]\n ): Promise<Uuid[]>;\n\n /**\n * Updates an existing thread in the Plot system.\n *\n * **Important**: This method only updates existing threads. It will throw an error\n * if the thread does not exist. Use `createThread()` to create or update (upsert)\n * threads.\n *\n * Only the fields provided in the update object will be modified - all other fields\n * remain unchanged. This enables partial updates without needing to fetch and resend\n * the entire thread object.\n *\n * For tags, provide a Record<number, boolean> where true adds a tag and false removes it.\n * Tags not included in the update remain unchanged.\n *\n * Set `focus` to move the thread to a different focus.\n *\n * Scheduling is handled separately via `createSchedule()` / `updateSchedule()`.\n *\n * @param thread - The thread update containing the ID or source and fields to change\n * @returns Promise that resolves when the update is complete\n * @throws Error if the thread does not exist\n *\n * @example\n * ```typescript\n * // Mark a task as complete\n * await this.plot.updateThread({\n * id: \"task-123\",\n * done: new Date()\n * });\n *\n * // Add and remove tags\n * await this.plot.updateThread({\n * id: \"thread-789\",\n * tags: {\n * 1: true, // Add tag with ID 1\n * 2: false // Remove tag with ID 2\n * }\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateThread(thread: ThreadUpdate): Promise<void>;\n\n /**\n * Retrieves all notes within a thread.\n *\n * Notes are detailed entries within a thread, ordered by creation time.\n * Each note can contain markdown content, actions, and other detailed information\n * related to the parent thread.\n *\n * @param thread - The thread whose notes to retrieve\n * @returns Promise resolving to array of notes in the thread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getNotes(thread: Thread): Promise<Note[]>;\n\n /**\n * Creates a new note in a thread.\n *\n * Notes provide detailed content within a thread, supporting markdown,\n * actions, and other rich content. The note will be automatically assigned\n * an ID and author information based on the current execution context.\n *\n * @param note - The note data to create\n * @returns Promise resolving to the created note's ID\n *\n * @example\n * ```typescript\n * // Create a note with content\n * await this.plot.createNote({\n * thread: { id: \"thread-123\" },\n * note: \"Discussion notes from the meeting...\",\n * contentType: \"markdown\"\n * });\n *\n * // Create a note with actions\n * await this.plot.createNote({\n * thread: { id: \"thread-456\" },\n * note: \"Meeting recording available\",\n * actions: [{\n * type: ActionType.external,\n * title: \"View Recording\",\n * url: \"https://example.com/recording\"\n * }]\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createNote(note: NewNote): Promise<Uuid>;\n\n /**\n * Creates multiple notes in a single batch operation.\n *\n * This method efficiently creates multiple notes at once, which is\n * more performant than calling createNote() multiple times individually.\n * All notes are created with the same author and access control rules.\n *\n * @param notes - Array of note data to create\n * @returns Promise resolving to array of created note IDs\n *\n * @example\n * ```typescript\n * // Create multiple notes in one batch\n * await this.plot.createNotes([\n * {\n * thread: { id: \"thread-123\" },\n * note: \"First message in thread\"\n * },\n * {\n * thread: { id: \"thread-123\" },\n * note: \"Second message in thread\"\n * }\n * ]);\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createNotes(notes: NewNote[]): Promise<Uuid[]>;\n\n /**\n * Updates an existing note in the Plot system.\n *\n * **Important**: This method only updates existing notes. It will throw an error\n * if the note does not exist. Use `createNote()` to create or update (upsert) notes.\n *\n * Only the fields provided in the update object will be modified - all other fields\n * remain unchanged. This enables partial updates without needing to fetch and resend\n * the entire note object.\n *\n * @param note - The note update containing the ID or key and fields to change\n * @returns Promise that resolves when the update is complete\n * @throws Error if the note does not exist\n *\n * @example\n * ```typescript\n * // Update note content\n * await this.plot.updateNote({\n * id: \"note-123\",\n * note: \"Updated content with more details\"\n * });\n *\n * // Add tags to a note\n * await this.plot.updateNote({\n * id: \"note-456\",\n * twistTags: {\n * [Tag.Important]: true\n * }\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateNote(note: NoteUpdate): Promise<void>;\n\n /**\n * Retrieves a thread by ID or source.\n *\n * This method enables lookup of threads either by their unique ID or by their\n * source identifier (canonical URL from an external system). Archived threads\n * are included in the results.\n *\n * @param thread - Thread lookup by ID or source\n * @returns Promise resolving to the matching thread or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getThread(\n thread: { id: Uuid } | { source: string }\n ): Promise<Thread | null>;\n\n /**\n * Retrieves a note by ID or key.\n *\n * This method enables lookup of notes either by their unique ID or by their\n * key (unique identifier within the thread). Archived notes are included\n * in the results.\n *\n * @param note - Note lookup by ID or key\n * @returns Promise resolving to the matching note or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getNote(note: { id: Uuid } | { key: string }): Promise<Note | null>;\n\n /**\n * Creates a new focus in the Plot system.\n *\n * Focuses serve as organizational containers for threads and twists.\n * The created focus will be automatically assigned a unique ID.\n *\n * @param focus - The focus data to create\n * @returns Promise resolving to the complete created focus\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createFocus(focus: NewFocus): Promise<Focus & { created: boolean }>;\n\n /**\n * Retrieves a focus by ID or key.\n *\n * Archived focuses are included in the results.\n *\n * @param focus - Focus lookup by ID or key\n * @returns Promise resolving to the matching focus or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getFocus(\n focus: { id: Uuid } | { key: string }\n ): Promise<Focus | null>;\n\n /**\n * Updates an existing focus in the Plot system.\n *\n * The focus is identified by either its ID or key.\n * Only the fields specified in the update will be changed.\n *\n * @param update - Focus update containing ID/key and fields to change\n * @returns Promise that resolves when the update is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateFocus(update: FocusUpdate): Promise<void>;\n\n /**\n * Retrieves actors by their IDs.\n *\n * Actors represent users, contacts, or twists in the Plot system.\n * This method requires ContactAccess.Read permission.\n *\n * @param ids - Array of actor IDs to retrieve\n * @returns Promise resolving to array of actors\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getActors(ids: ActorId[]): Promise<Actor[]>;\n\n /**\n * Returns the full Actor for the user who installed this twist.\n * Useful for per-user operations like schedule creation, or when\n * the owner's name or email is needed.\n */\n abstract getOwner(): Promise<Actor>;\n\n /**\n * Returns the user ID (`twist_instance.owner_id`) that installed this\n * twist. This is the same value exposed on Twist via `this.userId`.\n */\n abstract getUserId(): Promise<string>;\n\n /**\n * Creates a new schedule for a thread.\n *\n * Schedules define when a thread occurs in time. A thread can have\n * multiple schedules (shared and per-user).\n *\n * @param schedule - The schedule data to create\n * @returns Promise resolving to the created schedule\n *\n * @example\n * ```typescript\n * // Schedule a timed event\n * const threadId = await this.plot.createThread({\n * title: \"Team standup\"\n * });\n * await this.plot.createSchedule({\n * threadId,\n * start: new Date(\"2025-01-15T10:00:00Z\"),\n * end: new Date(\"2025-01-15T10:30:00Z\"),\n * recurrenceRule: \"FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\"\n * });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createSchedule(schedule: NewSchedule): Promise<Schedule>;\n\n /**\n * Retrieves all schedules for a thread.\n *\n * @param threadId - The thread whose schedules to retrieve\n * @returns Promise resolving to array of schedules for the thread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getSchedules(threadId: Uuid): Promise<Schedule[]>;\n\n /**\n * Retrieves links from connected source channels.\n *\n * Requires `link: true` in Plot options.\n *\n * @param filter - Optional filter criteria for links\n * @returns Promise resolving to array of links with their notes\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getLinks(filter?: LinkFilter): Promise<Array<{ link: Link; notes: Note[] }>>;\n\n /**\n * Searches notes and links using semantic similarity.\n *\n * Requires `search: true` in Plot options.\n *\n * @param query - The search query text\n * @param options - Optional search configuration\n * @returns Promise resolving to array of search results ordered by similarity\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract search(query: string, options?: SearchOptions): Promise<SearchResult[]>;\n\n /**\n * Lists threads owned by the twist's user.\n *\n * Requires `ThreadAccess.Full`.\n *\n * @param options - Query options for filtering threads\n * @returns Promise resolving to array of threads\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getThreads(options?: {\n /**\n * Focus to list threads from. Must be owned by the twist owner.\n * When omitted, defaults to the owner's Inbox.\n */\n focusId?: Uuid;\n /** Include archived threads. Default: false. */\n includeArchived?: boolean;\n /** Maximum number of threads to return. Default: 50, max: 200. */\n limit?: number;\n /** Number of threads to skip for pagination. Default: 0. */\n offset?: number;\n }): Promise<Thread[]>;\n\n /**\n * Lists focuses owned by the twist's user.\n *\n * Requires `FocusAccess.Full`.\n *\n * @param options - Query options for filtering focuses\n * @returns Promise resolving to array of focuses\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract getFocuses(options?: {\n /** Include archived focuses. Default: false. */\n includeArchived?: boolean;\n }): Promise<Focus[]>;\n\n /**\n * Updates a link.\n *\n * Requires `LinkAccess.Full`. Set `threadId` to move the link to a different thread.\n *\n * @param link - The link update containing the ID and fields to change\n * @returns Promise that resolves when the update is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract updateLink(link: LinkUpdate): Promise<void>;\n\n /**\n * Creates a plan of operations for user approval.\n *\n * Returns an Action that can be attached to a note. The user can approve,\n * deny, or request changes. On approval, operations are executed by the API.\n *\n * Requires `requireApproval: true` in Plot options.\n *\n * @param options - Plan configuration\n * @returns An Action of type `plan` to attach to a note\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract createPlan(options: {\n /** Human-readable title summarizing the plan */\n title: string;\n /** Array of operations to execute on approval */\n operations: PlanOperation[];\n /** Callback invoked with (action, approved: boolean) when the user responds */\n callback: Callback;\n }): Action;\n}\n";
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import { type Callback, ITool } from \"..\";\n\n/**\n * Twist source code structure containing dependencies and source files.\n */\nexport interface TwistSource {\n /**\n * Package dependencies with version specifiers\n * @example { \"@plotday/twister\": \"workspace:^\", \"@plotday/tool-google-calendar\": \"^1.0.0\" }\n */\n dependencies: Record<string, string>;\n\n /**\n * Source files with their content\n * Must include \"index.ts\" as the entry point\n * @example { \"index.ts\": \"export default class MyTwist extends Twist {...}\" }\n */\n files: Record<string, string>;\n}\n\n/**\n * Represents a log entry from a twist execution.\n */\nexport type Log = {\n timestamp: Date;\n environment: \"personal\" | \"private\" | \"review\" | \"public\";\n severity: \"log\" | \"error\" | \"warn\" | \"info\";\n message: string;\n};\n\n/**\n * Twist permissions returned after deployment.\n * Nested structure mapping domains to entities to permission flags.\n *\n * Format: { domain: { entity: flags[] } }\n * - domain: Tool name (e.g., \"network\", \"plot\")\n * - entity: Domain-specific identifier (e.g., URL pattern, resource type)\n * - flags: Array of permission flags (\"read\", \"write\", \"update\", \"use\")\n *\n * @example\n * ```typescript\n * {\n * \"network\": {\n * \"https://api.example.com/*\": [\"use\"],\n * \"https://googleapis.com/*\": [\"use\"]\n * },\n * \"plot\": {\n * \"thread:mentioned\": [\"read\", \"write\", \"update\"],\n * \"priority\": [\"read\", \"write\", \"update\"]\n * }\n * }\n * ```\n */\nexport type TwistPermissions = Record<string, Record<string, string[]>>;\n\n/**\n * Built-in tool for managing twists and deployments.\n *\n * The Twists tool provides twists with the ability to create twist IDs\n * and programmatically deploy twists.\n *\n * @example\n * ```typescript\n * class TwistBuilderTwist extends Twist {\n * build(build: ToolBuilder) {\n * return {\n * twists: build.get(Twists)\n * }\n * }\n *\n * async activate() {\n * const twistId = await this.tools.twists.create();\n * // Display twist ID to user\n * }\n * }\n * ```\n */\nexport abstract class Twists extends ITool {\n /**\n * Creates a new twist ID and grants access to people in the current priority.\n *\n * @returns Promise resolving to the generated twist ID\n * @throws When twist creation fails\n *\n * @example\n * ```typescript\n * const twistId = await twist.create();\n * console.log(`Your twist ID: ${twistId}`);\n * ```\n */\n abstract create(): Promise<string>;\n\n /**\n * Generates twist source code from a specification using AI.\n *\n * This method uses Claude AI to generate TypeScript source code and dependencies\n * from a markdown specification. The generated source is validated by attempting\n * to build it, with iterative error correction (up to 3 attempts).\n *\n * @param spec - Markdown specification describing the twist functionality\n * @returns Promise resolving to twist source (dependencies and files)\n * @throws When generation fails after maximum attempts\n *\n * @example\n * ```typescript\n * const source = await twist.generate(`\n * # Calendar Sync Twist\n *\n * This twist syncs Google Calendar events to Plot activities.\n *\n * ## Features\n * - Authenticate with Google\n * - Sync calendar events\n * - Create activities from events\n * `);\n *\n * // source.dependencies: { \"@plotday/twister\": \"workspace:^\", ... }\n * // source.files: { \"index.ts\": \"export default class...\" }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract generate(spec: string): Promise<TwistSource>;\n\n /**\n * Deploys a twist programmatically.\n *\n * This method provides the same functionality as the plot deploy CLI\n * command, but can be called from within a twist. Accepts either:\n * - A pre-bundled module (JavaScript code)\n * - A source object (dependencies + files) which is built in a sandbox\n *\n * @param options - Deployment configuration\n * @param options.twistId - Twist ID for deployment\n * @param options.module - Pre-bundled twist module code (mutually exclusive with source)\n * @param options.source - Twist source code with dependencies (mutually exclusive with module)\n * @param options.environment - Target environment (defaults to \"personal\")\n * @param options.name - Optional twist name (required for first deploy)\n * @param options.description - Optional twist description (required for first deploy)\n * @param options.dryRun - If true, validates without deploying (returns errors if any)\n * @returns Promise resolving to deployment result with version and optional errors\n * @throws When deployment fails or user lacks access\n *\n * @example\n * ```typescript\n * // Deploy with a module\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * module: 'export default class MyTwist extends Twist {...}',\n * environment: 'personal',\n * name: 'My Twist',\n * description: 'Does something cool'\n * });\n * console.log(`Deployed version ${result.version}`);\n *\n * // Deploy with source\n * const source = await twist.generate(spec);\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * source,\n * environment: 'personal',\n * name: 'My Twist',\n * });\n *\n * // Validate with dryRun\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * source,\n * dryRun: true,\n * });\n * if (result.errors?.length) {\n * console.error('Build errors:', result.errors);\n * }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract deploy(\n options: {\n twistId: string;\n environment?: \"personal\" | \"private\" | \"review\";\n name?: string;\n description?: string;\n dryRun?: boolean;\n } & (\n | {\n module: string;\n }\n | {\n source: TwistSource;\n }\n )\n ): Promise<{\n version: string;\n permissions: TwistPermissions;\n errors?: string[];\n }>;\n\n /**\n * Subscribes to logs from a twist.\n *\n * This method registers a callback to receive batches of logs from twist executions.\n * The callback will be invoked with an array of logs whenever new logs are captured\n * from the twist's console output.\n *\n * @param twistId - Twist ID (root ID) to watch logs for\n * @param callback - Callback token created via CallbackTool that will receive log batches\n * @returns Promise that resolves when the subscription is created\n * @throws When subscription fails\n *\n * @example\n * ```typescript\n * // Create twist and callback\n * const twistId = await this.twist.create();\n * const callback = await this.callback.create(\"onLogs\");\n *\n * // Subscribe to logs\n * await this.twist.watchLogs(twistId, callback);\n *\n * // Implement handler\n * async onLogs(logs: Log[]) {\n * for (const log of logs) {\n * console.log(`[${log.environment}] ${log.severity}: ${log.message}`);\n * }\n * }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract watchLogs(twistId: string, callback: Callback): Promise<void>;\n}\n";
8
+ export default "import { type Callback, ITool } from \"..\";\n\n/**\n * Twist source code structure containing dependencies and source files.\n */\nexport interface TwistSource {\n /**\n * Package dependencies with version specifiers\n * @example { \"@plotday/twister\": \"workspace:^\", \"@plotday/tool-google-calendar\": \"^1.0.0\" }\n */\n dependencies: Record<string, string>;\n\n /**\n * Source files with their content\n * Must include \"index.ts\" as the entry point\n * @example { \"index.ts\": \"export default class MyTwist extends Twist {...}\" }\n */\n files: Record<string, string>;\n}\n\n/**\n * Represents a log entry from a twist execution.\n */\nexport type Log = {\n timestamp: Date;\n environment: \"personal\" | \"private\" | \"review\" | \"public\";\n severity: \"log\" | \"error\" | \"warn\" | \"info\";\n message: string;\n};\n\n/**\n * Twist permissions returned after deployment.\n * Nested structure mapping domains to entities to permission flags.\n *\n * Format: { domain: { entity: flags[] } }\n * - domain: Tool name (e.g., \"network\", \"plot\")\n * - entity: Domain-specific identifier (e.g., URL pattern, resource type)\n * - flags: Array of permission flags (\"read\", \"write\", \"update\", \"use\")\n *\n * @example\n * ```typescript\n * {\n * \"network\": {\n * \"https://api.example.com/*\": [\"use\"],\n * \"https://googleapis.com/*\": [\"use\"]\n * },\n * \"plot\": {\n * \"thread:mentioned\": [\"read\", \"write\", \"update\"],\n * \"focus\": [\"read\", \"write\", \"update\"]\n * }\n * }\n * ```\n */\nexport type TwistPermissions = Record<string, Record<string, string[]>>;\n\n/**\n * Built-in tool for managing twists and deployments.\n *\n * The Twists tool provides twists with the ability to create twist IDs\n * and programmatically deploy twists.\n *\n * @example\n * ```typescript\n * class TwistBuilderTwist extends Twist {\n * build(build: ToolBuilder) {\n * return {\n * twists: build.get(Twists)\n * }\n * }\n *\n * async activate() {\n * const twistId = await this.tools.twists.create();\n * // Display twist ID to user\n * }\n * }\n * ```\n */\nexport abstract class Twists extends ITool {\n /**\n * Creates a new twist ID and grants access to people in the current focus.\n *\n * @returns Promise resolving to the generated twist ID\n * @throws When twist creation fails\n *\n * @example\n * ```typescript\n * const twistId = await twist.create();\n * console.log(`Your twist ID: ${twistId}`);\n * ```\n */\n abstract create(): Promise<string>;\n\n /**\n * Generates twist source code from a specification using AI.\n *\n * This method uses Claude AI to generate TypeScript source code and dependencies\n * from a markdown specification. The generated source is validated by attempting\n * to build it, with iterative error correction (up to 3 attempts).\n *\n * @param spec - Markdown specification describing the twist functionality\n * @returns Promise resolving to twist source (dependencies and files)\n * @throws When generation fails after maximum attempts\n *\n * @example\n * ```typescript\n * const source = await twist.generate(`\n * # Calendar Sync Twist\n *\n * This twist syncs Google Calendar events to Plot activities.\n *\n * ## Features\n * - Authenticate with Google\n * - Sync calendar events\n * - Create activities from events\n * `);\n *\n * // source.dependencies: { \"@plotday/twister\": \"workspace:^\", ... }\n * // source.files: { \"index.ts\": \"export default class...\" }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract generate(spec: string): Promise<TwistSource>;\n\n /**\n * Deploys a twist programmatically.\n *\n * This method provides the same functionality as the plot deploy CLI\n * command, but can be called from within a twist. Accepts either:\n * - A pre-bundled module (JavaScript code)\n * - A source object (dependencies + files) which is built in a sandbox\n *\n * @param options - Deployment configuration\n * @param options.twistId - Twist ID for deployment\n * @param options.module - Pre-bundled twist module code (mutually exclusive with source)\n * @param options.source - Twist source code with dependencies (mutually exclusive with module)\n * @param options.environment - Target environment (defaults to \"personal\")\n * @param options.name - Optional twist name (required for first deploy)\n * @param options.description - Optional twist description (required for first deploy)\n * @param options.dryRun - If true, validates without deploying (returns errors if any)\n * @returns Promise resolving to deployment result with version and optional errors\n * @throws When deployment fails or user lacks access\n *\n * @example\n * ```typescript\n * // Deploy with a module\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * module: 'export default class MyTwist extends Twist {...}',\n * environment: 'personal',\n * name: 'My Twist',\n * description: 'Does something cool'\n * });\n * console.log(`Deployed version ${result.version}`);\n *\n * // Deploy with source\n * const source = await twist.generate(spec);\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * source,\n * environment: 'personal',\n * name: 'My Twist',\n * });\n *\n * // Validate with dryRun\n * const result = await twist.deploy({\n * twistId: 'abc-123-...',\n * source,\n * dryRun: true,\n * });\n * if (result.errors?.length) {\n * console.error('Build errors:', result.errors);\n * }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract deploy(\n options: {\n twistId: string;\n environment?: \"personal\" | \"private\" | \"review\";\n name?: string;\n description?: string;\n dryRun?: boolean;\n } & (\n | {\n module: string;\n }\n | {\n source: TwistSource;\n }\n )\n ): Promise<{\n version: string;\n permissions: TwistPermissions;\n errors?: string[];\n }>;\n\n /**\n * Subscribes to logs from a twist.\n *\n * This method registers a callback to receive batches of logs from twist executions.\n * The callback will be invoked with an array of logs whenever new logs are captured\n * from the twist's console output.\n *\n * @param twistId - Twist ID (root ID) to watch logs for\n * @param callback - Callback token created via CallbackTool that will receive log batches\n * @returns Promise that resolves when the subscription is created\n * @throws When subscription fails\n *\n * @example\n * ```typescript\n * // Create twist and callback\n * const twistId = await this.twist.create();\n * const callback = await this.callback.create(\"onLogs\");\n *\n * // Subscribe to logs\n * await this.twist.watchLogs(twistId, callback);\n *\n * // Implement handler\n * async onLogs(logs: Log[]) {\n * for (const log of logs) {\n * console.log(`[${log.environment}] ${log.severity}: ${log.message}`);\n * }\n * }\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract watchLogs(twistId: string, callback: Callback): Promise<void>;\n}\n";