@plotday/twister 0.20.0 → 0.22.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 (95) hide show
  1. package/README.md +5 -5
  2. package/bin/templates/AGENTS.template.md +5 -5
  3. package/bin/templates/README.template.md +1 -1
  4. package/cli/templates/AGENTS.template.md +5 -5
  5. package/cli/templates/README.template.md +1 -1
  6. package/dist/common/calendar.d.ts +4 -4
  7. package/dist/common/calendar.d.ts.map +1 -1
  8. package/dist/common/messaging.d.ts +8 -7
  9. package/dist/common/messaging.d.ts.map +1 -1
  10. package/dist/docs/assets/hierarchy.js +1 -1
  11. package/dist/docs/assets/highlight.css +8 -8
  12. package/dist/docs/assets/navigation.js +1 -1
  13. package/dist/docs/assets/search.js +1 -1
  14. package/dist/docs/classes/tool.ITool.html +1 -1
  15. package/dist/docs/classes/tool.Tool.html +1 -1
  16. package/dist/docs/classes/tools_ai.AI.html +3 -3
  17. package/dist/docs/classes/tools_callbacks.Callbacks.html +1 -1
  18. package/dist/docs/classes/tools_integrations.Integrations.html +1 -1
  19. package/dist/docs/classes/tools_network.Network.html +1 -1
  20. package/dist/docs/classes/tools_plot.Plot.html +52 -31
  21. package/dist/docs/classes/tools_store.Store.html +1 -1
  22. package/dist/docs/classes/tools_tasks.Tasks.html +2 -2
  23. package/dist/docs/classes/tools_twists.Twists.html +6 -6
  24. package/dist/docs/classes/twist.Twist.html +1 -1
  25. package/dist/docs/documents/Building_Custom_Tools.html +8 -9
  26. package/dist/docs/documents/Built-in_Tools.html +26 -14
  27. package/dist/docs/documents/Core_Concepts.html +27 -9
  28. package/dist/docs/documents/Getting_Started.html +12 -3
  29. package/dist/docs/documents/Runtime_Environment.html +8 -9
  30. package/dist/docs/enums/plot.ActivityType.html +3 -3
  31. package/dist/docs/enums/plot.ActorType.html +4 -4
  32. package/dist/docs/enums/tools_plot.ActivityAccess.html +6 -6
  33. package/dist/docs/enums/tools_plot.ContactAccess.html +3 -3
  34. package/dist/docs/enums/tools_plot.PriorityAccess.html +3 -3
  35. package/dist/docs/functions/utils_hash.quickHash.html +1 -0
  36. package/dist/docs/hierarchy.html +1 -1
  37. package/dist/docs/index.html +2 -11
  38. package/dist/docs/interfaces/common_calendar.CalendarTool.html +5 -5
  39. package/dist/docs/interfaces/tools_ai.AIRequest.html +4 -4
  40. package/dist/docs/modules/index.html +1 -1
  41. package/dist/docs/modules/plot.html +1 -1
  42. package/dist/docs/modules/tools_plot.html +1 -1
  43. package/dist/docs/modules/utils_hash.html +1 -0
  44. package/dist/docs/modules.html +1 -1
  45. package/dist/docs/types/plot.Activity.html +16 -52
  46. package/dist/docs/types/plot.ActivityCommon.html +20 -0
  47. package/dist/docs/types/plot.ActivityUpdate.html +2 -8
  48. package/dist/docs/types/plot.ActivityWithNotes.html +1 -0
  49. package/dist/docs/types/plot.Actor.html +5 -5
  50. package/dist/docs/types/plot.NewActivity.html +3 -3
  51. package/dist/docs/types/plot.NewActivityWithNotes.html +1 -0
  52. package/dist/docs/types/plot.NewContact.html +4 -4
  53. package/dist/docs/types/plot.NewNote.html +10 -0
  54. package/dist/docs/types/plot.Note.html +7 -0
  55. package/dist/docs/types/plot.NoteType.html +1 -1
  56. package/dist/docs/types/plot.NoteUpdate.html +14 -0
  57. package/dist/docs/types/plot.PickPriorityConfig.html +3 -3
  58. package/dist/docs/types/tools_network.WebhookRequest.html +1 -1
  59. package/dist/docs/types/{tools_plot.ActivityIntentHandler.html → tools_plot.NoteIntentHandler.html} +5 -5
  60. package/dist/llm-docs/common/calendar.d.ts +1 -1
  61. package/dist/llm-docs/common/calendar.d.ts.map +1 -1
  62. package/dist/llm-docs/common/calendar.js +1 -1
  63. package/dist/llm-docs/common/calendar.js.map +1 -1
  64. package/dist/llm-docs/common/messaging.d.ts +1 -1
  65. package/dist/llm-docs/common/messaging.d.ts.map +1 -1
  66. package/dist/llm-docs/common/messaging.js +1 -1
  67. package/dist/llm-docs/common/messaging.js.map +1 -1
  68. package/dist/llm-docs/plot.d.ts +1 -1
  69. package/dist/llm-docs/plot.d.ts.map +1 -1
  70. package/dist/llm-docs/plot.js +1 -1
  71. package/dist/llm-docs/plot.js.map +1 -1
  72. package/dist/llm-docs/tools/plot.d.ts +1 -1
  73. package/dist/llm-docs/tools/plot.d.ts.map +1 -1
  74. package/dist/llm-docs/tools/plot.js +1 -1
  75. package/dist/llm-docs/tools/plot.js.map +1 -1
  76. package/dist/llm-docs/twist-guide-template.d.ts +1 -1
  77. package/dist/llm-docs/twist-guide-template.d.ts.map +1 -1
  78. package/dist/llm-docs/twist-guide-template.js +1 -1
  79. package/dist/llm-docs/twist-guide-template.js.map +1 -1
  80. package/dist/plot.d.ts +80 -38
  81. package/dist/plot.d.ts.map +1 -1
  82. package/dist/plot.js +1 -1
  83. package/dist/plot.js.map +1 -1
  84. package/dist/tools/plot.d.ts +118 -29
  85. package/dist/tools/plot.d.ts.map +1 -1
  86. package/dist/tools/plot.js +4 -4
  87. package/dist/tools/plot.js.map +1 -1
  88. package/dist/twist-guide.d.ts +1 -1
  89. package/dist/twist-guide.d.ts.map +1 -1
  90. package/dist/utils/hash.d.ts +2 -0
  91. package/dist/utils/hash.d.ts.map +1 -0
  92. package/dist/utils/hash.js +9 -0
  93. package/dist/utils/hash.js.map +1 -0
  94. package/package.json +5 -1
  95. package/dist/docs/documents/Advanced.html +0 -91
@@ -1,13 +1,13 @@
1
- import { type Activity, type ActivityMeta, type ActivityUpdate, type Actor, type ActorId, ITool, type NewActivity, type NewContact, type NewPriority, type Priority, type Tag } from "..";
1
+ import { type Activity, type ActivityUpdate, type Actor, type ActorId, ITool, type NewActivity, type NewActivityWithNotes, type NewContact, type NewNote, type NewPriority, type Note, type NoteUpdate, type Priority, type Tag } from "..";
2
2
  export declare enum ActivityAccess {
3
3
  /**
4
- * Create new Activity on a thread where the twist was mentioned.
5
- * Add/remove tags on Activity where the twist was mentioned.
4
+ * Create new Note on an Activity where the twist was mentioned.
5
+ * Add/remove tags on Activity or Note where the twist was mentioned.
6
6
  */
7
7
  Respond = 0,
8
8
  /**
9
- * Create new, top-level Activity.
10
- * Create new Activity in a thread the twist created.
9
+ * Create new Activity.
10
+ * Create new Note in an Activity the twist created.
11
11
  * All Respond permissions.
12
12
  */
13
13
  Create = 1
@@ -35,13 +35,13 @@ export declare enum ContactAccess {
35
35
  * Intent handler for activity mentions.
36
36
  * Defines how the twist should respond when mentioned in an activity.
37
37
  */
38
- export type ActivityIntentHandler = {
38
+ export type NoteIntentHandler = {
39
39
  /** Human-readable description of what this intent handles */
40
40
  description: string;
41
41
  /** Example phrases or activity content that would match this intent */
42
42
  examples: string[];
43
43
  /** The function to call when this intent is matched */
44
- handler: (activity: Activity) => Promise<void>;
44
+ handler: (note: Note) => Promise<void>;
45
45
  };
46
46
  /**
47
47
  * Built-in tool for interacting with the core Plot data layer.
@@ -77,26 +77,30 @@ export type ActivityIntentHandler = {
77
77
  */
78
78
  export declare abstract class Plot extends ITool {
79
79
  static readonly Options: {
80
- /**
81
- * Activity event callbacks.
82
- */
83
80
  activity?: {
81
+ /**
82
+ * Capability to create Notes and modify tags.
83
+ */
84
84
  access?: ActivityAccess;
85
85
  /**
86
- * Called when an activity is updated.
86
+ * Called when an activity created by this twist is updated.
87
+ * This is often used to implement two-way sync with an external system.
87
88
  *
88
89
  * @param activity - The updated activity
89
90
  * @param changes - Optional changes object containing the previous version and tag modifications
90
91
  */
91
- updated?: (activity: Activity, changes?: {
92
+ updated?: (activity: Activity, changes: {
92
93
  previous: Activity;
93
94
  tagsAdded: Record<Tag, ActorId[]>;
94
95
  tagsRemoved: Record<Tag, ActorId[]>;
95
96
  }) => Promise<void>;
97
+ };
98
+ note?: {
96
99
  /**
97
- * Intent handlers for activity mentions.
98
- * When an activity mentions this twist, the system will match the activity
99
- * content against these intent descriptions and call the matching handler.
100
+ * Respond to mentions in notes.
101
+ *
102
+ * When a note mentions this twist, the system will match the note
103
+ * content against these intents and call the matching handler.
100
104
  *
101
105
  * @example
102
106
  * ```typescript
@@ -111,7 +115,7 @@ export declare abstract class Plot extends ITool {
111
115
  * }]
112
116
  * ```
113
117
  */
114
- intents?: ActivityIntentHandler[];
118
+ intents?: NoteIntentHandler[];
115
119
  };
116
120
  priority?: {
117
121
  access?: PriorityAccess;
@@ -130,7 +134,7 @@ export declare abstract class Plot extends ITool {
130
134
  * @param activity - The activity data to create
131
135
  * @returns Promise resolving to the complete created activity
132
136
  */
133
- abstract createActivity(activity: NewActivity): Promise<Activity>;
137
+ abstract createActivity(activity: NewActivity | NewActivityWithNotes): Promise<Activity>;
134
138
  /**
135
139
  * Creates multiple activities in a single batch operation.
136
140
  *
@@ -141,7 +145,7 @@ export declare abstract class Plot extends ITool {
141
145
  * @param activities - Array of activity data to create
142
146
  * @returns Promise resolving to array of created activities
143
147
  */
144
- abstract createActivities(activities: NewActivity[]): Promise<Activity[]>;
148
+ abstract createActivities(activities: (NewActivity | NewActivityWithNotes)[]): Promise<Activity[]>;
145
149
  /**
146
150
  * Updates an existing activity in the Plot system.
147
151
  *
@@ -195,27 +199,112 @@ export declare abstract class Plot extends ITool {
195
199
  */
196
200
  abstract updateActivity(activity: ActivityUpdate): Promise<void>;
197
201
  /**
198
- * Retrieves all activities in the same thread as the specified activity.
202
+ * Retrieves all notes within an activity.
203
+ *
204
+ * Notes are detailed entries within an activity, ordered by creation time.
205
+ * Each note can contain markdown content, links, and other detailed information
206
+ * related to the parent activity.
207
+ *
208
+ * @param activity - The activity whose notes to retrieve
209
+ * @returns Promise resolving to array of notes in the activity
210
+ */
211
+ abstract getNotes(activity: Activity): Promise<Note[]>;
212
+ /**
213
+ * Creates a new note in an activity.
214
+ *
215
+ * Notes provide detailed content within an activity, supporting markdown,
216
+ * links, and other rich content. The note will be automatically assigned
217
+ * an ID and author information based on the current execution context.
218
+ *
219
+ * @param note - The note data to create
220
+ * @returns Promise resolving to the complete created note
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * // Create a note with content
225
+ * await this.plot.createNote({
226
+ * activity: { id: "activity-123" },
227
+ * note: "Discussion notes from the meeting...",
228
+ * noteType: "markdown"
229
+ * });
230
+ *
231
+ * // Create a note with links
232
+ * await this.plot.createNote({
233
+ * activity: { id: "activity-456" },
234
+ * note: "Meeting recording available",
235
+ * links: [{
236
+ * type: ActivityLinkType.external,
237
+ * title: "View Recording",
238
+ * url: "https://example.com/recording"
239
+ * }]
240
+ * });
241
+ * ```
242
+ */
243
+ abstract createNote(note: NewNote): Promise<Note>;
244
+ /**
245
+ * Creates multiple notes in a single batch operation.
246
+ *
247
+ * This method efficiently creates multiple notes at once, which is
248
+ * more performant than calling createNote() multiple times individually.
249
+ * All notes are created with the same author and access control rules.
199
250
  *
200
- * A thread consists of related activities linked through parent-child
201
- * relationships or other associative connections. This is useful for
202
- * finding conversation histories or related task sequences.
251
+ * @param notes - Array of note data to create
252
+ * @returns Promise resolving to array of created notes
203
253
  *
204
- * @param activity - The activity whose thread to retrieve
205
- * @returns Promise resolving to array of activities in the thread
254
+ * @example
255
+ * ```typescript
256
+ * // Create multiple notes in one batch
257
+ * await this.plot.createNotes([
258
+ * {
259
+ * activity: { id: "activity-123" },
260
+ * note: "First message in thread"
261
+ * },
262
+ * {
263
+ * activity: { id: "activity-123" },
264
+ * note: "Second message in thread"
265
+ * }
266
+ * ]);
267
+ * ```
268
+ */
269
+ abstract createNotes(notes: NewNote[]): Promise<Note[]>;
270
+ /**
271
+ * Updates an existing note in the Plot system.
272
+ *
273
+ * Only the fields provided in the update object will be modified - all other fields
274
+ * remain unchanged. This enables partial updates without needing to fetch and resend
275
+ * the entire note object.
276
+ *
277
+ * @param note - The note update containing the ID and fields to change
278
+ * @returns Promise that resolves when the update is complete
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * // Update note content
283
+ * await this.plot.updateNote({
284
+ * id: "note-123",
285
+ * note: "Updated content with more details"
286
+ * });
287
+ *
288
+ * // Add tags to a note
289
+ * await this.plot.updateNote({
290
+ * id: "note-456",
291
+ * twistTags: {
292
+ * [Tag.Important]: true
293
+ * }
294
+ * });
295
+ * ```
206
296
  */
207
- abstract getThread(activity: Activity): Promise<Activity[]>;
297
+ abstract updateNote(note: NoteUpdate): Promise<void>;
208
298
  /**
209
- * Finds an activity by its metadata.
299
+ * Finds an activity by its meta.source.
210
300
  *
211
301
  * This method enables lookup of activities that were created from external
212
302
  * systems, using the metadata to locate the corresponding Plot activity.
213
- * Useful for preventing duplicate imports and maintaining sync state.
214
303
  *
215
- * @param meta - The activity metadata to search for
304
+ * @param source - The meta.source value to search for
216
305
  * @returns Promise resolving to the matching activity or null if not found
217
306
  */
218
- abstract getActivityByMeta(meta: ActivityMeta): Promise<Activity | null>;
307
+ abstract getActivityBySource(source: string): Promise<Activity | null>;
219
308
  /**
220
309
  * Creates a new priority in the Plot system.
221
310
  *
@@ -1 +1 @@
1
- {"version":3,"file":"plot.d.ts","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,KAAK,OAAO,EACZ,KAAK,EACL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,GAAG,EACT,MAAM,IAAI,CAAC;AAEZ,oBAAY,cAAc;IACxB;;;OAGG;IACH,OAAO,IAAA;IACP;;;;OAIG;IACH,MAAM,IAAA;CACP;AAED,oBAAY,cAAc;IACxB;;;OAGG;IACH,MAAM,IAAA;IACN;;;;OAIG;IACH,IAAI,IAAA;CACL;AAED,oBAAY,aAAa;IACvB,8BAA8B;IAC9B,IAAI,IAAA;IACJ,kCAAkC;IAClC,KAAK,IAAA;CACN;AAED;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,6DAA6D;IAC7D,WAAW,EAAE,MAAM,CAAC;IACpB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,uDAAuD;IACvD,OAAO,EAAE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;;;;;;;;;;;;;;;;OAkDG;IAEH,QAAQ,CAAC,cAAc,CAAC,QAAQ,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAEhE;;;;;;;;;OASG;IAEH,QAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IAEH,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAEjD;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IAEH,QAAQ,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IAEH,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAEpD;;;;;;;;OAQG;IAEH,QAAQ,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAEtE;;;;;;;;OAQG;IAEH,QAAQ,CAAC,cAAc,CAAC,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IAEjE;;;;;;;;;;OAUG;IAEH,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC;IAEnE;;;;;;;;OAQG;IAEH,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC;CACrD"}
@@ -2,13 +2,13 @@ import { ITool, } from "..";
2
2
  export var ActivityAccess;
3
3
  (function (ActivityAccess) {
4
4
  /**
5
- * Create new Activity on a thread where the twist was mentioned.
6
- * Add/remove tags on Activity where the twist was mentioned.
5
+ * Create new Note on an Activity where the twist was mentioned.
6
+ * Add/remove tags on Activity or Note where the twist was mentioned.
7
7
  */
8
8
  ActivityAccess[ActivityAccess["Respond"] = 0] = "Respond";
9
9
  /**
10
- * Create new, top-level Activity.
11
- * Create new Activity in a thread the twist created.
10
+ * Create new Activity.
11
+ * Create new Note in an Activity the twist created.
12
12
  * All Respond permissions.
13
13
  */
14
14
  ActivityAccess[ActivityAccess["Create"] = 1] = "Create";
@@ -1 +1 @@
1
- {"version":3,"file":"plot.js","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,GAMN,MAAM,IAAI,CAAC;AAEZ,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,yDAAO,CAAA;IACP;;;;OAIG;IACH,uDAAM,CAAA;AACR,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAM,CAAA;IACN;;;;OAIG;IACH,mDAAI,CAAA;AACN,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,8BAA8B;IAC9B,iDAAI,CAAA;IACJ,kCAAkC;IAClC,mDAAK,CAAA;AACP,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAeD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,OAAgB,IAAK,SAAQ,KAAK;IACtC,MAAM,CAAU,OAAO,CAgDrB;CAiJH"}
1
+ {"version":3,"file":"plot.js","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,GAUN,MAAM,IAAI,CAAC;AAEZ,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,yDAAO,CAAA;IACP;;;;OAIG;IACH,uDAAM,CAAA;AACR,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAM,CAAA;IACN;;;;OAIG;IACH,mDAAI,CAAA;AACN,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,8BAA8B;IAC9B,iDAAI,CAAA;IACJ,kCAAkC;IAClC,mDAAK,CAAA;AACP,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAeD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,OAAgB,IAAK,SAAQ,KAAK;IACtC,MAAM,CAAU,OAAO,CAkDrB;CAgPH"}
@@ -1,2 +1,2 @@
1
- export declare const TWIST_GUIDE = "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited CPU time**: Each execution has limited CPU time (typically 10 seconds) and memory (128MB)\n- **Use the Run tool**: Queue separate chunks of work with `run.now(functionName, context)`\n- **Break long operations**: Split large operations into smaller batches that can be processed independently\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n twist,\n type Priority,\n type ToolBuilder,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\n\nexport default class MyTwist extends twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot),\n };\n }\n\n async activate(priority: Pick<Priority, \"id\">) {\n // Called when twist is enabled for a priority\n // Common actions: request auth, create setup activities\n }\n\n async activity(activity: Activity) {\n // Called when an activity is routed to this twist\n // Common actions: process external events, update activities\n }\n}\n```\n\n## Tool System\n\n### Accessing Tools\n\nAll tools are declared in the `build` method:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n toolName: build(ToolClass),\n };\n}\n```\n\nAll `build()` calls must occur in the `build` method as they are used for dependency analysis.\n\nIMPORTANT: HTTP access is restricted to URLs requested via `build(Network, { urls: [url1, url2, ...] })` in the `build` method. Wildcards are supported. Use `build(Network, { urls: ['*'] })` if full access is needed.\n\n### Built-in Tools (Always Available)\n\nFor complete API documentation of built-in tools including all methods, types, and detailed examples, see the TypeScript definitions in your installed package at `node_modules/@plotday/twister/src/tools/*.ts`. Each tool file contains comprehensive JSDoc documentation.\n\n**Quick reference - Available tools:**\n\n- `@plotday/twister/tools/plot` - Core data layer (create/update activities, priorities, contacts)\n- `@plotday/twister/tools/ai` - LLM integration (text generation, structured output, reasoning)\n - Use ModelPreferences to specify `speed` (fast/balanced/capable) and `cost` (low/medium/high)\n- `@plotday/twister/tools/store` - Persistent key-value storage (also via `this.set()`, `this.get()`)\n- `@plotday/twister/tools/tasks` - Queue batched work (also via `this.run()`)\n- `@plotday/twister/tools/callbacks` - Persistent function references (also via `this.callback()`)\n- `@plotday/twister/tools/integrations` - OAuth2 authentication flows\n- `@plotday/twister/tools/network` - HTTP access permissions and webhook management\n- `@plotday/twister/tools/twists` - Manage other Twists\n\n**Critical**: Never use instance variables for state. They are lost after function execution. Always use Store methods.\n\n### External Tools (Add to package.json)\n\nAdd tool dependencies to `package.json`:\n\n```json\n{\n \"dependencies\": {\n \"@plotday/twister\": \"workspace:^\",\n \"@plotday/tool-google-calendar\": \"workspace:^\"\n }\n}\n```\n\n#### Common External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar integration\n- `@plotday/tool-outlook-calendar`: Outlook Calendar integration\n- `@plotday/tool-google-contacts`: Google Contacts integration\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Common patterns:\n\n**Request Authentication:**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const authLink = await this.tools.externalTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n await this.tools.plot.createActivity({\n type: ActivityType.Task,\n title: \"Connect your account\",\n links: [authLink],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Task,\n title: \"Setup\",\n});\n\nawait this.set(\"setup_activity_id\", activity.id);\n```\n\n### activity(activity: Activity)\n\nCalled when an activity is routed to the twist. Common patterns:\n\n**Create Activities from External Events:**\n\n```typescript\nasync activity(activity: Activity) {\n await this.tools.plot.createActivity(activity);\n}\n```\n\n**Update Based on User Action:**\n\n```typescript\nasync activity(activity: Activity) {\n if (activity.completed) {\n await this.handleCompletion(activity);\n }\n}\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.url,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool)\nconst token = await this.callback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n token: token,\n};\n\n// Add to activity\nawait this.tools.plot.createActivity({\n type: ActivityType.Task,\n title: \"Task with links\",\n links: [urlLink, callbackLink],\n});\n```\n\n## Authentication Pattern\n\nCommon pattern for OAuth authentication:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Request auth link from tool with callback\n const authLink = await this.tools.googleTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n // Create activity with auth link\n const activity = await this.tools.plot.createActivity({\n type: ActivityType.Task,\n title: \"Connect Google account\",\n links: [authLink],\n });\n\n // Store for later use\n await this.set(\"auth_activity_id\", activity.id);\n}\n\nasync onAuthComplete(authResult: { authToken: string }, provider: string) {\n // Store auth token\n await this.set(`${provider}_auth`, authResult.authToken);\n\n // Continue setup flow\n await this.setupSyncOptions(authResult.authToken);\n}\n```\n\n## Sync Pattern\n\nPattern for syncing external data with callbacks:\n\n```typescript\nasync startSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n\n await this.tools.calendarTool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n calendarId\n );\n}\n\nasync handleEvent(activity: Activity, calendarId: string): Promise<void> {\n // Process incoming event from external service\n await this.tools.plot.createActivity(activity);\n}\n\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `\uD83D\uDCC5 ${calendar.name}${calendar.primary ? \" (Primary)\" : \"\"}`,\n type: ActivityLinkType.callback,\n token: token,\n });\n }\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Which calendars would you like to connect?\",\n links,\n });\n}\n\nasync onCalendarSelected(\n link: ActivityLink,\n provider: string,\n calendarId: string,\n calendarName: string,\n authToken: string\n): Promise<void> {\n // Start sync for selected calendar\n await this.tools.tool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n provider,\n calendarId\n );\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited execution time, you must break long operations into batches. Each batch runs independently in a new execution context.\n\n### Key Principles\n\n1. **Store state between batches**: Use the Store tool to persist progress\n2. **Queue next batch**: Use the Run tool to schedule the next chunk\n3. **Clean up when done**: Delete stored state after completion\n4. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(callback);\n}\n\nasync syncBatch(args: any, resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (keep under time limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results\n for (const item of result.items) {\n await this.tools.plot.createActivity(item);\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n });\n\n // Queue next batch (runs in new execution context)\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n note: `Sync complete: ${state.itemsProcessed + result.items.length} items processed`,\n });\n }\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n note: `Failed to complete operation: ${error.message}`,\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- Most activity should be `type = ActivityType.Note` with a `title` and `note`, and no `start` or `end`. This represents a typical message. `start` and `end` should only be used for a note if it should be displayed for a specific date or time, such as a birthday.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget runtime limits** - Each execution has ~10 seconds. Break long operations into batches with the Tasks tool. Process enough items per batch to be efficient, but few enough to stay under time limits.\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
1
+ export declare const TWIST_GUIDE = "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited CPU time**: Each execution has limited CPU time (typically 10 seconds) and memory (128MB)\n- **Use the Run tool**: Queue separate chunks of work with `run.now(functionName, context)`\n- **Break long operations**: Split large operations into smaller batches that can be processed independently\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n twist,\n type Priority,\n type ToolBuilder,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot),\n };\n }\n\n async activate(priority: Pick<Priority, \"id\">) {\n // Called when twist is enabled for a priority\n // Common actions: request auth, create setup activities\n }\n\n async activity(activity: Activity) {\n // Called when an activity is routed to this twist\n // Common actions: process external events, update activities\n }\n}\n```\n\n## Tool System\n\n### Accessing Tools\n\nAll tools are declared in the `build` method:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n toolName: build(ToolClass),\n };\n}\n```\n\nAll `build()` calls must occur in the `build` method as they are used for dependency analysis.\n\nIMPORTANT: HTTP access is restricted to URLs requested via `build(Network, { urls: [url1, url2, ...] })` in the `build` method. Wildcards are supported. Use `build(Network, { urls: ['*'] })` if full access is needed.\n\n### Built-in Tools (Always Available)\n\nFor complete API documentation of built-in tools including all methods, types, and detailed examples, see the TypeScript definitions in your installed package at `node_modules/@plotday/twister/src/tools/*.ts`. Each tool file contains comprehensive JSDoc documentation.\n\n**Quick reference - Available tools:**\n\n- `@plotday/twister/tools/plot` - Core data layer (create/update activities, priorities, contacts)\n- `@plotday/twister/tools/ai` - LLM integration (text generation, structured output, reasoning)\n - Use ModelPreferences to specify `speed` (fast/balanced/capable) and `cost` (low/medium/high)\n- `@plotday/twister/tools/store` - Persistent key-value storage (also via `this.set()`, `this.get()`)\n- `@plotday/twister/tools/tasks` - Queue batched work (also via `this.run()`)\n- `@plotday/twister/tools/callbacks` - Persistent function references (also via `this.callback()`)\n- `@plotday/twister/tools/integrations` - OAuth2 authentication flows\n- `@plotday/twister/tools/network` - HTTP access permissions and webhook management\n- `@plotday/twister/tools/twists` - Manage other Twists\n\n**Critical**: Never use instance variables for state. They are lost after function execution. Always use Store methods.\n\n### External Tools (Add to package.json)\n\nAdd tool dependencies to `package.json`:\n\n```json\n{\n \"dependencies\": {\n \"@plotday/twister\": \"workspace:^\",\n \"@plotday/tool-google-calendar\": \"workspace:^\"\n }\n}\n```\n\n#### Common External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar integration\n- `@plotday/tool-outlook-calendar`: Outlook Calendar integration\n- `@plotday/tool-google-contacts`: Google Contacts integration\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Common patterns:\n\n**Request Authentication:**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const authLink = await this.tools.externalTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n await this.tools.plot.createActivity({\n type: ActivityType.Action,\n title: \"Connect your account\",\n links: [authLink],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Action,\n title: \"Setup\",\n});\n\nawait this.set(\"setup_activity_id\", activity.id);\n```\n\n### activity(activity: Activity)\n\nCalled when an activity is routed to the twist. Common patterns:\n\n**Create Activities from External Events:**\n\n```typescript\nasync activity(activity: Activity) {\n await this.tools.plot.createActivity(activity);\n}\n```\n\n**Update Based on User Action:**\n\n```typescript\nasync activity(activity: Activity) {\n if (activity.completed) {\n await this.handleCompletion(activity);\n }\n}\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.url,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool)\nconst token = await this.callback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n token: token,\n};\n\n// Add to activity\nawait this.tools.plot.createActivity({\n type: ActivityType.Action,\n title: \"Task with links\",\n links: [urlLink, callbackLink],\n});\n```\n\n## Authentication Pattern\n\nCommon pattern for OAuth authentication:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Request auth link from tool with callback\n const authLink = await this.tools.googleTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n // Create activity with auth link\n const activity = await this.tools.plot.createActivity({\n type: ActivityType.Action,\n title: \"Connect Google account\",\n links: [authLink],\n });\n\n // Store for later use\n await this.set(\"auth_activity_id\", activity.id);\n}\n\nasync onAuthComplete(authResult: { authToken: string }, provider: string) {\n // Store auth token\n await this.set(`${provider}_auth`, authResult.authToken);\n\n // Continue setup flow\n await this.setupSyncOptions(authResult.authToken);\n}\n```\n\n## Sync Pattern\n\nPattern for syncing external data with callbacks:\n\n```typescript\nasync startSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n\n await this.tools.calendarTool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n calendarId\n );\n}\n\nasync handleEvent(activity: Activity, calendarId: string): Promise<void> {\n // Process incoming event from external service\n await this.tools.plot.createActivity(activity);\n}\n\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `\uD83D\uDCC5 ${calendar.name}${calendar.primary ? \" (Primary)\" : \"\"}`,\n type: ActivityLinkType.callback,\n token: token,\n });\n }\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Which calendars would you like to connect?\",\n links,\n });\n}\n\nasync onCalendarSelected(\n link: ActivityLink,\n provider: string,\n calendarId: string,\n calendarName: string,\n authToken: string\n): Promise<void> {\n // Start sync for selected calendar\n await this.tools.tool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n provider,\n calendarId\n );\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited execution time, you must break long operations into batches. Each batch runs independently in a new execution context.\n\n### Key Principles\n\n1. **Store state between batches**: Use the Store tool to persist progress\n2. **Queue next batch**: Use the Run tool to schedule the next chunk\n3. **Clean up when done**: Delete stored state after completion\n4. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(callback);\n}\n\nasync syncBatch(args: any, resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (keep under time limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results\n for (const item of result.items) {\n await this.tools.plot.createActivity(item);\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n });\n\n // Queue next batch (runs in new execution context)\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n note: `Sync complete: ${state.itemsProcessed + result.items.length} items processed`,\n });\n }\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n note: `Failed to complete operation: ${error.message}`,\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- Most activity should be `type = ActivityType.Note` with a `title` and `note`, and no `start` or `end`. This represents a typical message. `start` and `end` should only be used for a note if it should be displayed for a specific date or time, such as a birthday.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget runtime limits** - Each execution has ~10 seconds. Break long operations into batches with the Tasks tool. Process enough items per batch to be efficient, but few enough to stay under time limits.\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
2
2
  //# sourceMappingURL=twist-guide.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"twist-guide.d.ts","sourceRoot":"","sources":["../src/twist-guide.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,WAAW,onZAAsB,CAAC"}
1
+ {"version":3,"file":"twist-guide.d.ts","sourceRoot":"","sources":["../src/twist-guide.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,WAAW,4nZAAsB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare function quickHash(str: string): string;
2
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../src/utils/hash.ts"],"names":[],"mappings":"AAAA,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,UAOpC"}
@@ -0,0 +1,9 @@
1
+ export function quickHash(str) {
2
+ let hash = 0x811c9dc5;
3
+ for (let i = 0; i < str.length; ++i) {
4
+ hash ^= str.charCodeAt(i);
5
+ hash = (hash * 0x01000193) >>> 0;
6
+ }
7
+ return hash.toString(16).padStart(8, "0");
8
+ }
9
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/utils/hash.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;QACpC,IAAI,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plotday/twister",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Plot Twist Creator - Build intelligent Twists that organize and prioritize your activities",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -65,6 +65,10 @@
65
65
  "types": "./dist/utils/types.d.ts",
66
66
  "default": "./dist/utils/types.js"
67
67
  },
68
+ "./utils/hash": {
69
+ "types": "./dist/utils/hash.d.ts",
70
+ "default": "./dist/utils/hash.js"
71
+ },
68
72
  "./common/calendar": {
69
73
  "types": "./dist/common/calendar.d.ts",
70
74
  "default": "./dist/common/calendar.js"