@plotday/twister 0.31.2 → 0.32.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 (98) hide show
  1. package/bin/commands/deploy.js +40 -51
  2. package/bin/commands/deploy.js.map +1 -1
  3. package/bin/commands/generate.js +13 -19
  4. package/bin/commands/generate.js.map +1 -1
  5. package/bin/commands/login.js +16 -20
  6. package/bin/commands/login.js.map +1 -1
  7. package/bin/commands/priority-create.js +5 -2
  8. package/bin/commands/priority-create.js.map +1 -1
  9. package/bin/commands/priority-list.js +5 -2
  10. package/bin/commands/priority-list.js.map +1 -1
  11. package/bin/commands/twist-logs.js +7 -19
  12. package/bin/commands/twist-logs.js.map +1 -1
  13. package/bin/templates/AGENTS.template.md +52 -11
  14. package/bin/utils/token.js +52 -24
  15. package/bin/utils/token.js.map +1 -1
  16. package/bin/utils/url-normalize.js +43 -0
  17. package/bin/utils/url-normalize.js.map +1 -0
  18. package/cli/templates/AGENTS.template.md +52 -11
  19. package/dist/common/calendar.d.ts +19 -4
  20. package/dist/common/calendar.d.ts.map +1 -1
  21. package/dist/docs/assets/hierarchy.js +1 -1
  22. package/dist/docs/assets/search.js +1 -1
  23. package/dist/docs/classes/tool.Tool.html +18 -10
  24. package/dist/docs/classes/tools_ai.AI.html +1 -1
  25. package/dist/docs/classes/tools_callbacks.Callbacks.html +1 -1
  26. package/dist/docs/classes/tools_integrations.Integrations.html +1 -1
  27. package/dist/docs/classes/tools_network.Network.html +1 -1
  28. package/dist/docs/classes/tools_plot.Plot.html +1 -1
  29. package/dist/docs/classes/tools_store.Store.html +1 -1
  30. package/dist/docs/classes/tools_tasks.Tasks.html +36 -13
  31. package/dist/docs/classes/tools_twists.Twists.html +1 -1
  32. package/dist/docs/documents/Building_Custom_Tools.html +10 -0
  33. package/dist/docs/documents/Built-in_Tools.html +39 -4
  34. package/dist/docs/documents/Core_Concepts.html +22 -1
  35. package/dist/docs/documents/Runtime_Environment.html +32 -19
  36. package/dist/docs/enums/plot.ActorType.html +4 -4
  37. package/dist/docs/enums/tag.Tag.html +1 -1
  38. package/dist/docs/hierarchy.html +1 -1
  39. package/dist/docs/media/SYNC_STRATEGIES.md +118 -0
  40. package/dist/docs/types/common_calendar.CalendarTool.html +23 -7
  41. package/dist/docs/types/common_calendar.SyncOptions.html +20 -4
  42. package/dist/docs/types/plot.Activity.html +15 -3
  43. package/dist/docs/types/plot.ActivityOccurrence.html +7 -7
  44. package/dist/docs/types/plot.ActivityOccurrenceUpdate.html +1 -1
  45. package/dist/docs/types/plot.ActivityUpdate.html +10 -2
  46. package/dist/docs/types/plot.ActivityWithNotes.html +1 -1
  47. package/dist/docs/types/plot.Actor.html +5 -5
  48. package/dist/docs/types/plot.ContentType.html +1 -1
  49. package/dist/docs/types/plot.NewActivity.html +21 -2
  50. package/dist/docs/types/plot.NewActivityOccurrence.html +5 -2
  51. package/dist/docs/types/plot.NewActivityWithNotes.html +1 -1
  52. package/dist/docs/types/plot.NewActor.html +1 -1
  53. package/dist/docs/types/plot.NewContact.html +4 -4
  54. package/dist/docs/types/plot.NewNote.html +4 -1
  55. package/dist/docs/types/plot.Note.html +15 -4
  56. package/dist/docs/types/plot.NoteUpdate.html +1 -1
  57. package/dist/docs/types/plot.PickPriorityConfig.html +2 -2
  58. package/dist/llm-docs/common/calendar.d.ts +1 -1
  59. package/dist/llm-docs/common/calendar.d.ts.map +1 -1
  60. package/dist/llm-docs/common/calendar.js +1 -1
  61. package/dist/llm-docs/common/calendar.js.map +1 -1
  62. package/dist/llm-docs/plot.d.ts +1 -1
  63. package/dist/llm-docs/plot.d.ts.map +1 -1
  64. package/dist/llm-docs/plot.js +1 -1
  65. package/dist/llm-docs/plot.js.map +1 -1
  66. package/dist/llm-docs/tag.d.ts +1 -1
  67. package/dist/llm-docs/tag.d.ts.map +1 -1
  68. package/dist/llm-docs/tag.js +1 -1
  69. package/dist/llm-docs/tag.js.map +1 -1
  70. package/dist/llm-docs/tool.d.ts +1 -1
  71. package/dist/llm-docs/tool.d.ts.map +1 -1
  72. package/dist/llm-docs/tool.js +1 -1
  73. package/dist/llm-docs/tool.js.map +1 -1
  74. package/dist/llm-docs/tools/tasks.d.ts +1 -1
  75. package/dist/llm-docs/tools/tasks.d.ts.map +1 -1
  76. package/dist/llm-docs/tools/tasks.js +1 -1
  77. package/dist/llm-docs/tools/tasks.js.map +1 -1
  78. package/dist/llm-docs/twist-guide-template.d.ts +1 -1
  79. package/dist/llm-docs/twist-guide-template.d.ts.map +1 -1
  80. package/dist/llm-docs/twist-guide-template.js +1 -1
  81. package/dist/llm-docs/twist-guide-template.js.map +1 -1
  82. package/dist/plot.d.ts +72 -6
  83. package/dist/plot.d.ts.map +1 -1
  84. package/dist/plot.js.map +1 -1
  85. package/dist/tag.d.ts.map +1 -1
  86. package/dist/tag.js +2 -0
  87. package/dist/tag.js.map +1 -1
  88. package/dist/tool.d.ts +15 -1
  89. package/dist/tool.d.ts.map +1 -1
  90. package/dist/tool.js +15 -1
  91. package/dist/tool.js.map +1 -1
  92. package/dist/tools/tasks.d.ts +52 -13
  93. package/dist/tools/tasks.d.ts.map +1 -1
  94. package/dist/tools/tasks.js +34 -10
  95. package/dist/tools/tasks.js.map +1 -1
  96. package/dist/twist-guide.d.ts +1 -1
  97. package/dist/twist-guide.d.ts.map +1 -1
  98. package/package.json +1 -1
@@ -4,6 +4,6 @@
4
4
  * This file is auto-generated during build. Do not edit manually.
5
5
  * Generated from: prebuild.ts
6
6
  */
7
- declare const _default: "import { ITool } from \"..\";\nimport type { Callback } from \"./callbacks\";\n\n/**\n * Run background tasks and scheduled jobs.\n *\n * The Tasks tool enables twists and tools to queue callbacks. This is especially\n * important for long-running operations and batch processing, since twists\n * operate within runtime limits. Task callbacks also benefit from automatic\n * retries on failure.\n *\n * **Note:** Tasks tool methods are also available directly on Twist and Tool classes\n * via `this.runTask()`, `this.cancelTask()`, and `this.cancelAllTasks()`.\n * This is the recommended approach for most use cases.\n *\n * **Best Practices:**\n * - Break long operations into smaller batches\n * - Create callbacks first using `this.callback()`\n * - Store intermediate state using the Store tool\n *\n * @example\n * ```typescript\n * class SyncTool extends Tool {\n * async startBatchSync(totalItems: number) {\n * // Store initial state using built-in set method\n * await this.set(\"sync_progress\", { processed: 0, total: totalItems });\n *\n * // Create callback and queue first batch using built-in methods\n * const callback = await this.callback(\"processBatch\", { batchNumber: 1 });\n * await this.runTask(callback);\n * }\n *\n * async processBatch(args: any, context: { batchNumber: number }) {\n * // Process one batch of items\n * const progress = await this.get(\"sync_progress\");\n *\n * // ... process items ...\n *\n * if (progress.processed < progress.total) {\n * // Queue next batch using built-in methods\n * const callback = await this.callback(\"processBatch\", {\n * batchNumber: context.batchNumber + 1\n * });\n * await this.runTask(callback);\n * }\n * }\n *\n * async scheduleCleanup() {\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n *\n * const callback = await this.callback(\"cleanupOldData\");\n * return await this.run(callback, { runAt: tomorrow });\n * }\n * }\n * ```\n */\nexport abstract class Tasks extends ITool {\n /**\n * Queues a callback to execute in a separate worker context.\n *\n * The callback will be invoked either immediately or at a scheduled time\n * in an isolated execution environment with limited resources. Use this\n * for breaking up long-running operations into manageable chunks.\n *\n * @param callback - Callback created with `this.callback()`\n * @param options - Optional configuration for the execution\n * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately\n * @returns Promise resolving to a cancellation token (only for scheduled executions)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void>;\n\n /**\n * Cancels a previously scheduled execution.\n *\n * Prevents a scheduled function from executing. No error is thrown\n * if the token is invalid or the execution has already completed.\n *\n * @param token - The cancellation token returned by runTask() with runAt option\n * @returns Promise that resolves when the cancellation is processed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract cancelTask(token: string): Promise<void>;\n\n /**\n * Cancels all scheduled executions for this tool/twist.\n *\n * Cancels all pending scheduled executions created by this tool or twist\n * instance. Immediate executions cannot be cancelled.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n abstract cancelAllTasks(): Promise<void>;\n}\n";
7
+ declare const _default: "import { ITool } from \"..\";\nimport type { Callback } from \"./callbacks\";\n\n/**\n * Run background tasks and scheduled jobs.\n *\n * The Tasks tool enables twists and tools to queue callbacks for execution in separate\n * worker contexts. **This is critical for staying under request limits**: each execution\n * has a limit of ~1000 requests (HTTP requests, tool calls, database operations), and\n * running a task creates a NEW execution with a fresh request limit.\n *\n * **Key distinction:**\n * - **Calling a callback** (via `this.run()`) continues the same execution and shares the request count\n * - **Running a task** (via `this.runTask()`) creates a NEW execution with fresh ~1000 request limit\n *\n * **When to use tasks:**\n * - Processing large datasets that would exceed 1000 requests\n * - Breaking loops into chunks where each chunk stays under the request limit\n * - Scheduling operations for future execution\n *\n * **Note:** Tasks tool methods are also available directly on Twist and Tool classes\n * via `this.runTask()`, `this.cancelTask()`, and `this.cancelAllTasks()`.\n * This is the recommended approach for most use cases.\n *\n * **Best Practices:**\n * - Size batches to stay under ~1000 requests per execution\n * - Calculate requests per item to determine safe batch size\n * - Create callbacks first using `this.callback()`\n * - Store intermediate state using the Store tool\n *\n * @example\n * ```typescript\n * class SyncTool extends Tool {\n * async startBatchSync(totalItems: number) {\n * // Store initial state using built-in set method\n * await this.set(\"sync_progress\", { processed: 0, total: totalItems });\n *\n * // Create callback and queue first batch\n * const callback = await this.callback(\"processBatch\", { batchNumber: 1 });\n * // runTask creates NEW execution with fresh ~1000 request limit\n * await this.runTask(callback);\n * }\n *\n * async processBatch(args: any, context: { batchNumber: number }) {\n * // Process one batch of items (sized to stay under request limit)\n * const progress = await this.get(\"sync_progress\");\n *\n * // If each item makes ~10 requests, process ~100 items per batch\n * // 100 items \u00D7 10 requests = 1000 requests (at limit)\n * const batchSize = 100;\n * const items = await this.fetchItems(progress.processed, batchSize);\n *\n * for (const item of items) {\n * await this.processItem(item); // Makes ~10 requests per item\n * }\n *\n * await this.set(\"sync_progress\", {\n * processed: progress.processed + batchSize,\n * total: progress.total\n * });\n *\n * if (progress.processed < progress.total) {\n * // Queue next batch - creates NEW execution with fresh request limit\n * const callback = await this.callback(\"processBatch\", {\n * batchNumber: context.batchNumber + 1\n * });\n * await this.runTask(callback);\n * }\n * }\n *\n * async scheduleCleanup() {\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n *\n * const callback = await this.callback(\"cleanupOldData\");\n * // Schedule for future execution\n * return await this.runTask(callback, { runAt: tomorrow });\n * }\n * }\n * ```\n */\nexport abstract class Tasks extends ITool {\n /**\n * Queues a callback to execute in a separate worker context with a fresh request limit.\n *\n * **Creates a NEW execution** with its own request limit of ~1000 requests (HTTP requests,\n * tool calls, database operations). This is the primary way to stay under request limits\n * when processing large datasets or making many API calls.\n *\n * The callback will be invoked either immediately or at a scheduled time\n * in an isolated execution environment. Each execution has ~1000 requests and ~60 seconds\n * CPU time. Use this for breaking loops into chunks that stay under the request limit.\n *\n * **Key distinction:**\n * - `this.run(callback)` - Continues same execution, shares request count\n * - `this.runTask(callback)` - NEW execution, fresh request limit\n *\n * @param callback - Callback created with `this.callback()`\n * @param options - Optional configuration for the execution\n * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately\n * @returns Promise resolving to a cancellation token (only for scheduled executions)\n *\n * @example\n * ```typescript\n * // Break large loop into batches to stay under request limit\n * const callback = await this.callback(\"syncBatch\", { page: 1 });\n * await this.runTask(callback); // Fresh execution with ~1000 requests\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void>;\n\n /**\n * Cancels a previously scheduled execution.\n *\n * Prevents a scheduled function from executing. No error is thrown\n * if the token is invalid or the execution has already completed.\n *\n * @param token - The cancellation token returned by runTask() with runAt option\n * @returns Promise that resolves when the cancellation is processed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract cancelTask(token: string): Promise<void>;\n\n /**\n * Cancels all scheduled executions for this tool/twist.\n *\n * Cancels all pending scheduled executions created by this tool or twist\n * instance. Immediate executions cannot be cancelled.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n abstract cancelAllTasks(): Promise<void>;\n}\n";
8
8
  export default _default;
9
9
  //# sourceMappingURL=tasks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tasks.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,gqHAAgqH;AAA/qH,wBAAgrH"}
1
+ {"version":3,"file":"tasks.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,ooLAA+nL;AAA9oL,wBAA+oL"}
@@ -4,5 +4,5 @@
4
4
  * This file is auto-generated during build. Do not edit manually.
5
5
  * Generated from: prebuild.ts
6
6
  */
7
- export default "import { ITool } from \"..\";\nimport type { Callback } from \"./callbacks\";\n\n/**\n * Run background tasks and scheduled jobs.\n *\n * The Tasks tool enables twists and tools to queue callbacks. This is especially\n * important for long-running operations and batch processing, since twists\n * operate within runtime limits. Task callbacks also benefit from automatic\n * retries on failure.\n *\n * **Note:** Tasks tool methods are also available directly on Twist and Tool classes\n * via `this.runTask()`, `this.cancelTask()`, and `this.cancelAllTasks()`.\n * This is the recommended approach for most use cases.\n *\n * **Best Practices:**\n * - Break long operations into smaller batches\n * - Create callbacks first using `this.callback()`\n * - Store intermediate state using the Store tool\n *\n * @example\n * ```typescript\n * class SyncTool extends Tool {\n * async startBatchSync(totalItems: number) {\n * // Store initial state using built-in set method\n * await this.set(\"sync_progress\", { processed: 0, total: totalItems });\n *\n * // Create callback and queue first batch using built-in methods\n * const callback = await this.callback(\"processBatch\", { batchNumber: 1 });\n * await this.runTask(callback);\n * }\n *\n * async processBatch(args: any, context: { batchNumber: number }) {\n * // Process one batch of items\n * const progress = await this.get(\"sync_progress\");\n *\n * // ... process items ...\n *\n * if (progress.processed < progress.total) {\n * // Queue next batch using built-in methods\n * const callback = await this.callback(\"processBatch\", {\n * batchNumber: context.batchNumber + 1\n * });\n * await this.runTask(callback);\n * }\n * }\n *\n * async scheduleCleanup() {\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n *\n * const callback = await this.callback(\"cleanupOldData\");\n * return await this.run(callback, { runAt: tomorrow });\n * }\n * }\n * ```\n */\nexport abstract class Tasks extends ITool {\n /**\n * Queues a callback to execute in a separate worker context.\n *\n * The callback will be invoked either immediately or at a scheduled time\n * in an isolated execution environment with limited resources. Use this\n * for breaking up long-running operations into manageable chunks.\n *\n * @param callback - Callback created with `this.callback()`\n * @param options - Optional configuration for the execution\n * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately\n * @returns Promise resolving to a cancellation token (only for scheduled executions)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void>;\n\n /**\n * Cancels a previously scheduled execution.\n *\n * Prevents a scheduled function from executing. No error is thrown\n * if the token is invalid or the execution has already completed.\n *\n * @param token - The cancellation token returned by runTask() with runAt option\n * @returns Promise that resolves when the cancellation is processed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract cancelTask(token: string): Promise<void>;\n\n /**\n * Cancels all scheduled executions for this tool/twist.\n *\n * Cancels all pending scheduled executions created by this tool or twist\n * instance. Immediate executions cannot be cancelled.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n abstract cancelAllTasks(): Promise<void>;\n}\n";
7
+ export default "import { ITool } from \"..\";\nimport type { Callback } from \"./callbacks\";\n\n/**\n * Run background tasks and scheduled jobs.\n *\n * The Tasks tool enables twists and tools to queue callbacks for execution in separate\n * worker contexts. **This is critical for staying under request limits**: each execution\n * has a limit of ~1000 requests (HTTP requests, tool calls, database operations), and\n * running a task creates a NEW execution with a fresh request limit.\n *\n * **Key distinction:**\n * - **Calling a callback** (via `this.run()`) continues the same execution and shares the request count\n * - **Running a task** (via `this.runTask()`) creates a NEW execution with fresh ~1000 request limit\n *\n * **When to use tasks:**\n * - Processing large datasets that would exceed 1000 requests\n * - Breaking loops into chunks where each chunk stays under the request limit\n * - Scheduling operations for future execution\n *\n * **Note:** Tasks tool methods are also available directly on Twist and Tool classes\n * via `this.runTask()`, `this.cancelTask()`, and `this.cancelAllTasks()`.\n * This is the recommended approach for most use cases.\n *\n * **Best Practices:**\n * - Size batches to stay under ~1000 requests per execution\n * - Calculate requests per item to determine safe batch size\n * - Create callbacks first using `this.callback()`\n * - Store intermediate state using the Store tool\n *\n * @example\n * ```typescript\n * class SyncTool extends Tool {\n * async startBatchSync(totalItems: number) {\n * // Store initial state using built-in set method\n * await this.set(\"sync_progress\", { processed: 0, total: totalItems });\n *\n * // Create callback and queue first batch\n * const callback = await this.callback(\"processBatch\", { batchNumber: 1 });\n * // runTask creates NEW execution with fresh ~1000 request limit\n * await this.runTask(callback);\n * }\n *\n * async processBatch(args: any, context: { batchNumber: number }) {\n * // Process one batch of items (sized to stay under request limit)\n * const progress = await this.get(\"sync_progress\");\n *\n * // If each item makes ~10 requests, process ~100 items per batch\n * // 100 items × 10 requests = 1000 requests (at limit)\n * const batchSize = 100;\n * const items = await this.fetchItems(progress.processed, batchSize);\n *\n * for (const item of items) {\n * await this.processItem(item); // Makes ~10 requests per item\n * }\n *\n * await this.set(\"sync_progress\", {\n * processed: progress.processed + batchSize,\n * total: progress.total\n * });\n *\n * if (progress.processed < progress.total) {\n * // Queue next batch - creates NEW execution with fresh request limit\n * const callback = await this.callback(\"processBatch\", {\n * batchNumber: context.batchNumber + 1\n * });\n * await this.runTask(callback);\n * }\n * }\n *\n * async scheduleCleanup() {\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n *\n * const callback = await this.callback(\"cleanupOldData\");\n * // Schedule for future execution\n * return await this.runTask(callback, { runAt: tomorrow });\n * }\n * }\n * ```\n */\nexport abstract class Tasks extends ITool {\n /**\n * Queues a callback to execute in a separate worker context with a fresh request limit.\n *\n * **Creates a NEW execution** with its own request limit of ~1000 requests (HTTP requests,\n * tool calls, database operations). This is the primary way to stay under request limits\n * when processing large datasets or making many API calls.\n *\n * The callback will be invoked either immediately or at a scheduled time\n * in an isolated execution environment. Each execution has ~1000 requests and ~60 seconds\n * CPU time. Use this for breaking loops into chunks that stay under the request limit.\n *\n * **Key distinction:**\n * - `this.run(callback)` - Continues same execution, shares request count\n * - `this.runTask(callback)` - NEW execution, fresh request limit\n *\n * @param callback - Callback created with `this.callback()`\n * @param options - Optional configuration for the execution\n * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately\n * @returns Promise resolving to a cancellation token (only for scheduled executions)\n *\n * @example\n * ```typescript\n * // Break large loop into batches to stay under request limit\n * const callback = await this.callback(\"syncBatch\", { page: 1 });\n * await this.runTask(callback); // Fresh execution with ~1000 requests\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void>;\n\n /**\n * Cancels a previously scheduled execution.\n *\n * Prevents a scheduled function from executing. No error is thrown\n * if the token is invalid or the execution has already completed.\n *\n * @param token - The cancellation token returned by runTask() with runAt option\n * @returns Promise that resolves when the cancellation is processed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract cancelTask(token: string): Promise<void>;\n\n /**\n * Cancels all scheduled executions for this tool/twist.\n *\n * Cancels all pending scheduled executions created by this tool or twist\n * instance. Immediate executions cannot be cancelled.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n abstract cancelAllTasks(): Promise<void>;\n}\n";
8
8
  //# sourceMappingURL=tasks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tasks.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,gqHAAgqH,CAAC"}
1
+ {"version":3,"file":"tasks.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,+nLAA+nL,CAAC"}
@@ -4,6 +4,6 @@
4
4
  * This file is auto-generated during build. Do not edit manually.
5
5
  * Generated from: cli/templates/AGENTS.template.md
6
6
  */
7
- declare const _default: "# 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## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n \u251C\u2500 Has stable URL or ID?\n \u2502 \u2514\u2500 Yes \u2192 Set Activity.source to the canonical URL/ID\n \u2502 Create Activity (Plot handles deduplication automatically)\n \u2502 Use Note.key for different note types:\n \u2502 - \"description\" for main content\n \u2502 - \"metadata\" for status/priority/assignee\n \u2502 - \"comment-{id}\" for individual comments\n \u2502\n \u2514\u2500 No stable identifier OR need multiple Plot activities per external item?\n \u2514\u2500 Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Activity with that UUID\n \u2502 Store mapping: external_id \u2192 activity_uuid\n \u2502\n \u2514\u2500 No (update/reply/comment) \u2192 Look up mapping by external_id\n \u251C\u2500 Found \u2192 Add Note to existing Activity using stored UUID\n \u2514\u2500 Not found \u2192 Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\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.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\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 note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\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.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\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\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\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(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\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### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\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 notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\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 using source/key pattern (automatic upserts, no manual tracking)\n for (const item of result.items) {\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n });\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 title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\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 title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\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- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\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";
7
+ declare const _default: "# 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 requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\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## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n \u251C\u2500 Has stable URL or ID?\n \u2502 \u2514\u2500 Yes \u2192 Set Activity.source to the canonical URL/ID\n \u2502 Create Activity (Plot handles deduplication automatically)\n \u2502 Use Note.key for different note types:\n \u2502 - \"description\" for main content\n \u2502 - \"metadata\" for status/priority/assignee\n \u2502 - \"comment-{id}\" for individual comments\n \u2502\n \u2514\u2500 No stable identifier OR need multiple Plot activities per external item?\n \u2514\u2500 Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Activity with that UUID\n \u2502 Store mapping: external_id \u2192 activity_uuid\n \u2502\n \u2514\u2500 No (update/reply/comment) \u2192 Look up mapping by external_id\n \u251C\u2500 Found \u2192 Add Note to existing Activity using stored UUID\n \u2514\u2500 Not found \u2192 Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\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.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\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 note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\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.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\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\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\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(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\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### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\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 notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\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 requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **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 initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\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 (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size \u2264 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n unread: !state.initialSync, // false for initial sync, true for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\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 initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\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 title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | `true` | Avoid notification overload from historical items |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n unread: !initialSync, // false for initial, true for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read, preventing spam from bulk historical imports\n- **Incremental sync**: New activities appear as unread, and archived state is preserved (respects user's archiving decisions)\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\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 title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\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- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\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- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\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";
8
8
  export default _default;
9
9
  //# sourceMappingURL=twist-guide-template.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"twist-guide-template.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,+4mBAAqumB;AAApvmB,wBAAqvmB"}
1
+ {"version":3,"file":"twist-guide-template.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,+xsBAAgnsB;AAA/nsB,wBAAgosB"}
@@ -4,5 +4,5 @@
4
4
  * This file is auto-generated during build. Do not edit manually.
5
5
  * Generated from: cli/templates/AGENTS.template.md
6
6
  */
7
- export default "# 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## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n ├─ Has stable URL or ID?\n │ └─ Yes → Set Activity.source to the canonical URL/ID\n │ Create Activity (Plot handles deduplication automatically)\n │ Use Note.key for different note types:\n │ - \"description\" for main content\n │ - \"metadata\" for status/priority/assignee\n │ - \"comment-{id}\" for individual comments\n │\n └─ No stable identifier OR need multiple Plot activities per external item?\n └─ Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n ├─ Yes → Generate UUID with Uuid.Generate()\n │ Create new Activity with that UUID\n │ Store mapping: external_id → activity_uuid\n │\n └─ No (update/reply/comment) → Look up mapping by external_id\n ├─ Found → Add Note to existing Activity using stored UUID\n └─ Not found → Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\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.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\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 note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\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.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\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\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\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(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\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### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\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: `📅 ${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 notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\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 using source/key pattern (automatic upserts, no manual tracking)\n for (const item of result.items) {\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n });\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 title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\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 title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\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- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\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";
7
+ export default "# 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 requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\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## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n ├─ Has stable URL or ID?\n │ └─ Yes → Set Activity.source to the canonical URL/ID\n │ Create Activity (Plot handles deduplication automatically)\n │ Use Note.key for different note types:\n │ - \"description\" for main content\n │ - \"metadata\" for status/priority/assignee\n │ - \"comment-{id}\" for individual comments\n │\n └─ No stable identifier OR need multiple Plot activities per external item?\n └─ Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n ├─ Yes → Generate UUID with Uuid.Generate()\n │ Create new Activity with that UUID\n │ Store mapping: external_id → activity_uuid\n │\n └─ No (update/reply/comment) → Look up mapping by external_id\n ├─ Found → Add Note to existing Activity using stored UUID\n └─ Not found → Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\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.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\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 note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\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.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\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\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\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(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\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### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\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: `📅 ${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 notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\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 requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **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 initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\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 (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size ≤ 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n unread: !state.initialSync, // false for initial sync, true for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\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 initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\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 title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | `true` | Avoid notification overload from historical items |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n unread: !initialSync, // false for initial, true for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read, preventing spam from bulk historical imports\n- **Incremental sync**: New activities appear as unread, and archived state is preserved (respects user's archiving decisions)\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\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 title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\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- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\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- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\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";
8
8
  //# sourceMappingURL=twist-guide-template.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"twist-guide-template.js","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,qumBAAqumB,CAAC"}
1
+ {"version":3,"file":"twist-guide-template.js","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,gnsBAAgnsB,CAAC"}
package/dist/plot.d.ts CHANGED
@@ -379,9 +379,21 @@ export type ActivityCommon = {
379
379
  };
380
380
  export type Activity = ActivityCommon & {
381
381
  /**
382
- * Canonical URL for the item in an external system.
383
- * For example, https://acme.atlassian.net/browse/PROJ-42 could represent a Jira issue.
384
- * When set, it uniquely identifies the activity within a priority tree.
382
+ * Globally unique, stable identifier for the item in an external system.
383
+ * MUST use immutable system-generated IDs, not human-readable slugs or titles.
384
+ *
385
+ * Recommended format: `${domain}:${type}:${id}`
386
+ *
387
+ * Examples:
388
+ * - `linear:issue:549dd8bd-2bc9-43d1-95d5-4b4af0c5af1b` (Linear issue by UUID)
389
+ * - `jira:10001:issue:12345` (Jira issue by numeric ID with cloud ID)
390
+ * - `gmail:thread:18d4e5f2a3b1c9d7` (Gmail thread by system ID)
391
+ *
392
+ * ⚠️ AVOID: URLs with mutable components like team names or issue keys
393
+ * - Bad: `https://linear.app/team/issue/TEAM-123/title` (team and title can change)
394
+ * - Bad: `jira:issue:PROJECT-42` (issue key can change)
395
+ *
396
+ * When set, uniquely identifies the activity within a priority tree for upsert operations.
385
397
  */
386
398
  source: string | null;
387
399
  /** The display title/summary of the activity */
@@ -578,8 +590,12 @@ export type NewActivityOccurrence = Pick<ActivityOccurrence, "occurrence" | "sta
578
590
  twistTags?: Partial<Record<Tag, boolean>>;
579
591
  /**
580
592
  * Whether this occurrence should be marked as unread for users.
581
- * - true: Occurrence is unread for users
593
+ * - true (default): Occurrence is unread for users
582
594
  * - false: Occurrence is marked as read
595
+ * - undefined/omitted: Same as true (default behavior)
596
+ *
597
+ * Only set this field explicitly when you want to mark the occurrence as read (false).
598
+ * For the default unread behavior, omit this field entirely - do NOT set it to true.
583
599
  */
584
600
  unread?: boolean;
585
601
  };
@@ -729,10 +745,35 @@ export type NewActivity = Pick<Activity, "type"> & Partial<Omit<Activity, "autho
729
745
  * Whether the activity should be marked as unread for users.
730
746
  * - true (default): Activity is unread for all users in the priority
731
747
  * - false: Activity is marked as read for all users in the priority at creation time
748
+ * - undefined/omitted: Same as true (default behavior)
749
+ *
750
+ * Only set this field explicitly when you want to mark activities as read (false).
751
+ * For the default unread behavior, omit this field entirely - do NOT set it to true.
732
752
  *
733
753
  * Use false for historical imports to avoid marking old items as unread.
734
754
  */
735
755
  unread?: boolean;
756
+ /**
757
+ * Whether the activity is archived.
758
+ * - true: Archive the activity
759
+ * - false: Unarchive the activity
760
+ * - undefined (default): Preserve current archive state
761
+ *
762
+ * Best practice: Set to false during initial syncs to ensure activities
763
+ * are unarchived. Omit during incremental syncs to preserve user's choice.
764
+ */
765
+ archived?: boolean;
766
+ /**
767
+ * Optional preview content for the activity. Can be Markdown formatted.
768
+ * The preview will be automatically generated from this content (truncated to 100 chars).
769
+ *
770
+ * - string: Use this content for preview generation
771
+ * - null: Explicitly disable preview (no preview will be shown)
772
+ * - undefined (default): Fall back to legacy behavior (generate from first note with content)
773
+ *
774
+ * This field is write-only and won't be returned when reading activities.
775
+ */
776
+ preview?: string | null;
736
777
  /**
737
778
  * Create or update specific occurrences of a recurring activity.
738
779
  * Each entry specifies overrides for a specific occurrence.
@@ -788,6 +829,17 @@ export type ActivityUpdate = ({
788
829
  * This is allowed on all activities the twist has access to.
789
830
  */
790
831
  twistTags?: Partial<Record<Tag, boolean>>;
832
+ /**
833
+ * Optional preview content for the activity. Can be Markdown formatted.
834
+ * The preview will be automatically generated from this content (truncated to 100 chars).
835
+ *
836
+ * - string: Use this content for preview generation
837
+ * - null: Explicitly disable preview (no preview will be shown)
838
+ * - undefined (omitted): Preserve current preview value
839
+ *
840
+ * This field is write-only and won't be returned when reading activities.
841
+ */
842
+ preview?: string | null;
791
843
  /**
792
844
  * Create or update specific occurrences of this recurring activity.
793
845
  * Each entry specifies overrides for a specific occurrence.
@@ -827,9 +879,19 @@ export type ActivityUpdate = ({
827
879
  */
828
880
  export type Note = ActivityCommon & {
829
881
  /**
830
- * Unique identifier for the note within its activity.
882
+ * Globally unique, stable identifier for the note within its activity.
831
883
  * Can be used to upsert without knowing the id.
832
- * For example, "description" could identify the description note for a Jira issue.
884
+ *
885
+ * Use one of these patterns:
886
+ * - Hardcoded semantic keys for fixed note types: "description", "cancellation"
887
+ * - External service IDs for dynamic collections: `comment:${immutableId}`
888
+ *
889
+ * Examples:
890
+ * - `"description"` (for a Jira issue's description note)
891
+ * - `"comment:12345"` (for a specific comment by ID)
892
+ * - `"gmail:msg:18d4e5f2a3b1c9d7"` (for a Gmail message within a thread)
893
+ *
894
+ * ⚠️ Ensure IDs are immutable - avoid human-readable slugs or titles.
833
895
  */
834
896
  key: string | null;
835
897
  /** The parent activity this note belongs to */
@@ -881,6 +943,10 @@ export type NewNote = Partial<Omit<Note, "author" | "activity" | "tags" | "menti
881
943
  * Whether the note should mark the parent activity as unread for users.
882
944
  * - true (default): Activity becomes unread for users who haven't authored the note
883
945
  * - false: Activity is marked as read for all users in the priority at note creation time
946
+ * - undefined/omitted: Same as true (default behavior)
947
+ *
948
+ * Only set this field explicitly when you want to mark the activity as read (false).
949
+ * For the default unread behavior, omit this field entirely - do NOT set it to true.
884
950
  *
885
951
  * Use false for historical imports to avoid marking old items as unread.
886
952
  */
@@ -1 +1 @@
1
- {"version":3,"file":"plot.d.ts","sourceRoot":"","sources":["../src/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,SAAS,CAAA;CAAE,CAAC;AAE/D;;GAEG;AACH,oBAAY,UAAU;IACpB,uBAAuB;IACvB,QAAQ,IAAI;IACZ,+BAA+B;IAC/B,eAAe,IAAI;IACnB,6BAA6B;IAC7B,YAAY,IAAI;IAChB,6BAA6B;IAC7B,QAAQ,IAAI;IACZ,2BAA2B;IAC3B,YAAY,IAAI;IAChB,4BAA4B;IAC5B,YAAY,IAAI;IAChB,qBAAqB;IACrB,MAAM,IAAI;IACV,6BAA6B;IAC7B,UAAU,IAAI;CACf;AAED;;;;;G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IACf,MAAM,OAAO;IACb,KAAK,OAAO;IACZ,IAAI,OAAO;IACX,MAAM,OAAO;IACb,QAAQ,OAAO;IACf,IAAI,OAAO;IACX,GAAG,OAAO;IAGV,MAAM,OAAO;IACb,IAAI,OAAO;IACX,SAAS,OAAO;CACjB"}
package/dist/tag.js CHANGED
@@ -43,6 +43,8 @@ export var Tag;
43
43
  Tag[Tag["Applause"] = 1016] = "Applause";
44
44
  Tag[Tag["Cool"] = 1017] = "Cool";
45
45
  Tag[Tag["Sad"] = 1018] = "Sad";
46
+ // RSVP tags - mutually exclusive per actor
47
+ // When an actor adds one of these tags, the other two are automatically removed
46
48
  Tag[Tag["Attend"] = 1019] = "Attend";
47
49
  Tag[Tag["Skip"] = 1020] = "Skip";
48
50
  Tag[Tag["Undecided"] = 1021] = "Undecided";
package/dist/tag.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tag.js","sourceRoot":"","sources":["../src/tag.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAN,IAAY,GA2CX;AA3CD,WAAY,GAAG;IACb,eAAe;IACf,2BAAO,CAAA;IACP,+BAAS,CAAA;IACT,6BAAQ,CAAA;IACR,qCAAY,CAAA;IACZ,mCAAW,CAAA;IAEX,cAAc;IACd,mCAAY,CAAA;IACZ,mCAAY,CAAA;IACZ,iCAAW,CAAA;IACX,+BAAU,CAAA;IACV,uCAAc,CAAA;IACd,qCAAa,CAAA;IACb,qCAAa,CAAA;IACb,qCAAa,CAAA;IACb,uCAAc,CAAA;IACd,iCAAW,CAAA;IACX,+BAAU,CAAA;IACV,+BAAU,CAAA;IAEV,aAAa;IACb,8BAAU,CAAA;IACV,4BAAS,CAAA;IACT,0CAAgB,CAAA;IAChB,gCAAW,CAAA;IACX,gCAAW,CAAA;IACX,sCAAc,CAAA;IACd,sCAAc,CAAA;IACd,gCAAW,CAAA;IACX,oCAAa,CAAA;IACb,wCAAe,CAAA;IACf,oCAAa,CAAA;IACb,kCAAY,CAAA;IACZ,gCAAW,CAAA;IACX,oCAAa,CAAA;IACb,wCAAe,CAAA;IACf,gCAAW,CAAA;IACX,8BAAU,CAAA;IACV,oCAAa,CAAA;IACb,gCAAW,CAAA;IACX,0CAAgB,CAAA;AAClB,CAAC,EA3CW,GAAG,KAAH,GAAG,QA2Cd"}
1
+ {"version":3,"file":"tag.js","sourceRoot":"","sources":["../src/tag.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAN,IAAY,GA6CX;AA7CD,WAAY,GAAG;IACb,eAAe;IACf,2BAAO,CAAA;IACP,+BAAS,CAAA;IACT,6BAAQ,CAAA;IACR,qCAAY,CAAA;IACZ,mCAAW,CAAA;IAEX,cAAc;IACd,mCAAY,CAAA;IACZ,mCAAY,CAAA;IACZ,iCAAW,CAAA;IACX,+BAAU,CAAA;IACV,uCAAc,CAAA;IACd,qCAAa,CAAA;IACb,qCAAa,CAAA;IACb,qCAAa,CAAA;IACb,uCAAc,CAAA;IACd,iCAAW,CAAA;IACX,+BAAU,CAAA;IACV,+BAAU,CAAA;IAEV,aAAa;IACb,8BAAU,CAAA;IACV,4BAAS,CAAA;IACT,0CAAgB,CAAA;IAChB,gCAAW,CAAA;IACX,gCAAW,CAAA;IACX,sCAAc,CAAA;IACd,sCAAc,CAAA;IACd,gCAAW,CAAA;IACX,oCAAa,CAAA;IACb,wCAAe,CAAA;IACf,oCAAa,CAAA;IACb,kCAAY,CAAA;IACZ,gCAAW,CAAA;IACX,oCAAa,CAAA;IACb,wCAAe,CAAA;IACf,gCAAW,CAAA;IACX,8BAAU,CAAA;IACV,2CAA2C;IAC3C,gFAAgF;IAChF,oCAAa,CAAA;IACb,gCAAW,CAAA;IACX,0CAAgB,CAAA;AAClB,CAAC,EA7CW,GAAG,KAAH,GAAG,QA6Cd"}
package/dist/tool.d.ts CHANGED
@@ -172,12 +172,26 @@ export declare abstract class Tool<TSelf> implements ITool {
172
172
  */
173
173
  protected clearAll(): Promise<void>;
174
174
  /**
175
- * Queues a callback to execute in a separate worker context.
175
+ * Queues a callback to execute in a separate worker context with a fresh request limit.
176
+ *
177
+ * **Creates a NEW execution** with its own request limit of ~1000 requests (HTTP requests,
178
+ * tool calls, database operations). This is the primary way to stay under request limits
179
+ * when processing large datasets or making many API calls.
180
+ *
181
+ * Use this to break long loops into chunks that each stay under the ~1000 request limit.
182
+ * Each task runs in an isolated execution environment with ~1000 requests and ~60 seconds CPU time.
176
183
  *
177
184
  * @param callback - The callback token created with `this.callback()`
178
185
  * @param options - Optional configuration for the execution
179
186
  * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately
180
187
  * @returns Promise resolving to a cancellation token (only for scheduled executions)
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * // Break large loop into batches
192
+ * const callback = await this.callback("processBatch", { page: 1 });
193
+ * await this.runTask(callback); // New execution with fresh request limit
194
+ * ```
181
195
  */
182
196
  protected runTask(callback: Callback, options?: {
183
197
  runAt?: Date;
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EACV,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,WAAW,EACX,QAAQ,EACT,MAAM,eAAe,CAAC;AAEvB,YAAY,EAAE,WAAW,EAAE,CAAC;AAE5B;;;GAGG;AACH,8BAAsB,KAAK;CAAG;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,8BAAsB,IAAI,CAAC,KAAK,CAAE,YAAW,KAAK;IAE9C,SAAS,CAAC,EAAE,EAAE,MAAM;IACpB,SAAS,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC;IACtC,OAAO,CAAC,QAAQ;gBAFN,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,YAAY,CAAC,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C;IAIzC;;;;;;;;;;;;;;;;;;;;;OAqBG;cACa,OAAO,CACrB,QAAQ,EAAE,QAAQ,EAClB,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,IAAI,CAAA;KAAE,GACzB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAIzB;;;;;OAKG;cACa,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxD;;;;OAIG;cACa,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/C;;;;;;;;;OASG;IAEH,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI9C;;;;;;;;OAQG;IAEH,YAAY,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/C;;;;;;;;OAQG;IACH,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAI3B;;;;;;;OAOG;IACH,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B;;;;;;;;OAQG;IACH,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAI9B;;;;;;;OAOG;IACH,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B;;;;OAIG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CAGpC"}
package/dist/tool.js CHANGED
@@ -193,12 +193,26 @@ export class Tool {
193
193
  return this.tools.store.clearAll();
194
194
  }
195
195
  /**
196
- * Queues a callback to execute in a separate worker context.
196
+ * Queues a callback to execute in a separate worker context with a fresh request limit.
197
+ *
198
+ * **Creates a NEW execution** with its own request limit of ~1000 requests (HTTP requests,
199
+ * tool calls, database operations). This is the primary way to stay under request limits
200
+ * when processing large datasets or making many API calls.
201
+ *
202
+ * Use this to break long loops into chunks that each stay under the ~1000 request limit.
203
+ * Each task runs in an isolated execution environment with ~1000 requests and ~60 seconds CPU time.
197
204
  *
198
205
  * @param callback - The callback token created with `this.callback()`
199
206
  * @param options - Optional configuration for the execution
200
207
  * @param options.runAt - If provided, schedules execution at this time; otherwise runs immediately
201
208
  * @returns Promise resolving to a cancellation token (only for scheduled executions)
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * // Break large loop into batches
213
+ * const callback = await this.callback("processBatch", { page: 1 });
214
+ * await this.runTask(callback); // New execution with fresh request limit
215
+ * ```
202
216
  */
203
217
  async runTask(callback, options) {
204
218
  return this.tools.tasks.runTask(callback, options);
package/dist/tool.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,MAAM,OAAgB,KAAK;CAAG;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,OAAgB,IAAI;IAEZ;IACA;IACF;IAHV,YACY,EAAU,EACV,OAA4B,EAC9B,QAAkB;QAFhB,OAAE,GAAF,EAAE,CAAQ;QACV,YAAO,GAAP,OAAO,CAAqB;QAC9B,aAAQ,GAAR,QAAQ,CAAU;IACzB,CAAC;IAEJ;;;OAGG;IACH,IAAc,KAAK;QACjB,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAqB,CAAC;IACrD,CAAC;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,6DAA6D;IAC7D,KAAK,CAAC,KAAkB;QACtB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED;;;;;;;;;;;;;OAaG;IACO,KAAK,CAAC,QAAQ,CAGtB,EAAM,EAAE,GAAG,SAAgB;QAC3B,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,cAAc,CAAC,KAAe;QAC5C,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACO,KAAK,CAA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