@plotday/twister 0.38.0 → 0.40.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 (118) hide show
  1. package/README.md +22 -16
  2. package/bin/commands/create.js +4 -4
  3. package/bin/commands/create.js.map +1 -1
  4. package/bin/index.js +1 -1
  5. package/bin/index.js.map +1 -1
  6. package/bin/templates/AGENTS.template.md +32 -0
  7. package/bin/templates/README.template.md +2 -2
  8. package/bin/utils/bundle.js +1 -1
  9. package/bin/utils/bundle.js.map +1 -1
  10. package/cli/templates/AGENTS.template.md +32 -0
  11. package/cli/templates/README.template.md +2 -2
  12. package/dist/{source.d.ts → connector.d.ts} +24 -22
  13. package/dist/connector.d.ts.map +1 -0
  14. package/dist/{source.js → connector.js} +23 -21
  15. package/dist/connector.js.map +1 -0
  16. package/dist/docs/assets/hierarchy.js +1 -1
  17. package/dist/docs/assets/navigation.js +1 -1
  18. package/dist/docs/assets/search.js +1 -1
  19. package/dist/docs/classes/{index.Source.html → index.Connector.html} +27 -27
  20. package/dist/docs/classes/index.Options.html +1 -1
  21. package/dist/docs/classes/tools_ai.AI.html +7 -3
  22. package/dist/docs/classes/tools_callbacks.Callbacks.html +1 -1
  23. package/dist/docs/classes/tools_integrations.Integrations.html +15 -15
  24. package/dist/docs/classes/tools_network.Network.html +1 -1
  25. package/dist/docs/classes/tools_plot.Plot.html +23 -21
  26. package/dist/docs/classes/tools_store.Store.html +1 -1
  27. package/dist/docs/classes/tools_tasks.Tasks.html +1 -1
  28. package/dist/docs/classes/tools_twists.Twists.html +3 -3
  29. package/dist/docs/classes/twist.Twist.html +1 -1
  30. package/dist/docs/documents/Building_Connectors.html +137 -0
  31. package/dist/docs/documents/Built-in_Tools.html +3 -3
  32. package/dist/docs/documents/Core_Concepts.html +5 -5
  33. package/dist/docs/documents/Getting_Started.html +1 -1
  34. package/dist/docs/enums/tools_ai.AIModel.html +2 -2
  35. package/dist/docs/enums/tools_integrations.AuthProvider.html +11 -11
  36. package/dist/docs/hierarchy.html +1 -1
  37. package/dist/docs/index.html +3 -3
  38. package/dist/docs/interfaces/tools_ai.AIRequest.html +11 -11
  39. package/dist/docs/interfaces/tools_ai.AIResponse.html +9 -9
  40. package/dist/docs/interfaces/tools_ai.FilePart.html +5 -5
  41. package/dist/docs/interfaces/tools_ai.ImagePart.html +4 -4
  42. package/dist/docs/interfaces/tools_ai.ReasoningPart.html +4 -4
  43. package/dist/docs/interfaces/tools_ai.RedactedReasoningPart.html +3 -3
  44. package/dist/docs/interfaces/tools_ai.TextPart.html +3 -3
  45. package/dist/docs/interfaces/tools_ai.ToolCallPart.html +5 -5
  46. package/dist/docs/interfaces/tools_ai.ToolExecutionOptions.html +4 -4
  47. package/dist/docs/interfaces/tools_ai.ToolResultPart.html +5 -5
  48. package/dist/docs/media/AGENTS.md +82 -65
  49. package/dist/docs/media/MULTI_USER_AUTH.md +1 -1
  50. package/dist/docs/media/SYNC_STRATEGIES.md +9 -9
  51. package/dist/docs/modules/index.html +1 -1
  52. package/dist/docs/modules/tools_ai.html +1 -1
  53. package/dist/docs/modules.html +1 -1
  54. package/dist/docs/types/tools_ai.AIAssistantMessage.html +2 -2
  55. package/dist/docs/types/tools_ai.AICapabilities.html +6 -0
  56. package/dist/docs/types/tools_ai.AIMessage.html +1 -1
  57. package/dist/docs/types/tools_ai.AIOptions.html +4 -0
  58. package/dist/docs/types/tools_ai.AISource.html +1 -1
  59. package/dist/docs/types/tools_ai.AISystemMessage.html +2 -2
  60. package/dist/docs/types/tools_ai.AITool.html +1 -1
  61. package/dist/docs/types/tools_ai.AIToolMessage.html +2 -2
  62. package/dist/docs/types/tools_ai.AIToolSet.html +1 -1
  63. package/dist/docs/types/tools_ai.AIUsage.html +5 -5
  64. package/dist/docs/types/tools_ai.AIUserMessage.html +2 -2
  65. package/dist/docs/types/tools_ai.DataContent.html +1 -1
  66. package/dist/docs/types/tools_ai.ModelPreferences.html +4 -4
  67. package/dist/docs/types/tools_integrations.ArchiveLinkFilter.html +5 -5
  68. package/dist/docs/types/tools_integrations.AuthToken.html +4 -4
  69. package/dist/docs/types/tools_integrations.Authorization.html +4 -4
  70. package/dist/docs/types/tools_integrations.Channel.html +5 -5
  71. package/dist/docs/types/tools_integrations.LinkTypeConfig.html +11 -8
  72. package/dist/index.d.ts +1 -1
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +1 -1
  75. package/dist/index.js.map +1 -1
  76. package/dist/llm-docs/connector.d.ts +9 -0
  77. package/dist/llm-docs/connector.d.ts.map +1 -0
  78. package/dist/llm-docs/connector.js +8 -0
  79. package/dist/llm-docs/connector.js.map +1 -0
  80. package/dist/llm-docs/index.js +2 -2
  81. package/dist/llm-docs/index.js.map +1 -1
  82. package/dist/llm-docs/tools/ai.d.ts +1 -1
  83. package/dist/llm-docs/tools/ai.d.ts.map +1 -1
  84. package/dist/llm-docs/tools/ai.js +1 -1
  85. package/dist/llm-docs/tools/ai.js.map +1 -1
  86. package/dist/llm-docs/tools/integrations.d.ts +1 -1
  87. package/dist/llm-docs/tools/integrations.d.ts.map +1 -1
  88. package/dist/llm-docs/tools/integrations.js +1 -1
  89. package/dist/llm-docs/tools/integrations.js.map +1 -1
  90. package/dist/llm-docs/tools/plot.d.ts +1 -1
  91. package/dist/llm-docs/tools/plot.d.ts.map +1 -1
  92. package/dist/llm-docs/tools/plot.js +1 -1
  93. package/dist/llm-docs/tools/plot.js.map +1 -1
  94. package/dist/llm-docs/twist-guide-template.d.ts +1 -1
  95. package/dist/llm-docs/twist-guide-template.d.ts.map +1 -1
  96. package/dist/llm-docs/twist-guide-template.js +1 -1
  97. package/dist/llm-docs/twist-guide-template.js.map +1 -1
  98. package/dist/tools/ai.d.ts +18 -0
  99. package/dist/tools/ai.d.ts.map +1 -1
  100. package/dist/tools/ai.js.map +1 -1
  101. package/dist/tools/integrations.d.ts +16 -11
  102. package/dist/tools/integrations.d.ts.map +1 -1
  103. package/dist/tools/integrations.js +3 -3
  104. package/dist/tools/integrations.js.map +1 -1
  105. package/dist/tools/plot.d.ts +4 -0
  106. package/dist/tools/plot.d.ts.map +1 -1
  107. package/dist/tools/plot.js.map +1 -1
  108. package/dist/twist-guide.d.ts +1 -1
  109. package/dist/twist-guide.d.ts.map +1 -1
  110. package/package.json +38 -38
  111. package/tsconfig.base.json +1 -1
  112. package/dist/docs/documents/Building_Sources.html +0 -137
  113. package/dist/llm-docs/source.d.ts +0 -9
  114. package/dist/llm-docs/source.d.ts.map +0 -1
  115. package/dist/llm-docs/source.js +0 -8
  116. package/dist/llm-docs/source.js.map +0 -1
  117. package/dist/source.d.ts.map +0 -1
  118. package/dist/source.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"plot.d.ts","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,YAAY,EACjB,KAAK,KAAK,EACV,KAAK,OAAO,EACZ,KAAK,EACL,KAAK,IAAI,EACT,KAAK,SAAS,EACd,KAAK,kBAAkB,EACvB,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,IAAI,EACT,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,IAAI,EACL,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,WAAW,EACjB,MAAM,aAAa,CAAC;AAErB,oBAAY,YAAY;IACtB;;;OAGG;IACH,OAAO,IAAA;IACP;;;;OAIG;IACH,MAAM,IAAA;CACP;AAED,oBAAY,cAAc;IACxB;;;OAGG;IACH,MAAM,IAAA;IACN;;;;OAIG;IACH,IAAI,IAAA;CACL;AAED,oBAAY,aAAa;IACvB,iFAAiF;IACjF,IAAI,IAAA;IACJ,kCAAkC;IAClC,KAAK,IAAA;CACN;AAED;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,6DAA6D;IAC7D,WAAW,EAAE,MAAM,CAAC;IACpB,uE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IAAI,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,IAAI,EAAE,CAAA;KAAE,CAAC,CAAC;IAErF;;;;;;;;OAQG;IAEH,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;CACjF"}
@@ -1 +1 @@
1
- {"version":3,"file":"plot.js","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,GAYN,MAAM,IAAI,CAAC;AAMZ,MAAM,CAAN,IAAY,YAYX;AAZD,WAAY,YAAY;IACtB;;;OAGG;IACH,qDAAO,CAAA;IACP;;;;OAIG;IACH,mDAAM,CAAA;AACR,CAAC,EAZW,YAAY,KAAZ,YAAY,QAYvB;AAED,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAM,CAAA;IACN;;;;OAIG;IACH,mDAAI,CAAA;AACN,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,iFAAiF;IACjF,iDAAI,CAAA;IACJ,kCAAkC;IAClC,mDAAK,CAAA;AACP,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAmDD,gDAAgD;AAChD,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AACvC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAWnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAgB,IAAK,SAAQ,KAAK;IACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2CG;IACH,MAAM,CAAU,OAAO,CAwCrB;CA6UH"}
1
+ {"version":3,"file":"plot.js","sourceRoot":"","sources":["../../src/tools/plot.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,GAYN,MAAM,IAAI,CAAC;AAMZ,MAAM,CAAN,IAAY,YAYX;AAZD,WAAY,YAAY;IACtB;;;OAGG;IACH,qDAAO,CAAA;IACP;;;;OAIG;IACH,mDAAM,CAAA;AACR,CAAC,EAZW,YAAY,KAAZ,YAAY,QAYvB;AAED,MAAM,CAAN,IAAY,cAYX;AAZD,WAAY,cAAc;IACxB;;;OAGG;IACH,uDAAM,CAAA;IACN;;;;OAIG;IACH,mDAAI,CAAA;AACN,CAAC,EAZW,cAAc,KAAd,cAAc,QAYzB;AAED,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,iFAAiF;IACjF,iDAAI,CAAA;IACJ,kCAAkC;IAClC,mDAAK,CAAA;AACP,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAmDD,gDAAgD;AAChD,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AACvC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAWnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAgB,IAAK,SAAQ,KAAK;IACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2CG;IACH,MAAM,CAAU,OAAO,CA4CrB;CA6UH"}
@@ -1,2 +1,2 @@
1
- export declare const TWIST_GUIDE = "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited 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 Threads and Notes\n\n**CRITICAL CONCEPT**: A **Thread** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that thread.\n\n**Think of a Thread as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Threads with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Threads for updates** - Don't create a new Thread for each related message\n3. **Use Thread.source and Note.key for automatic upserts (Recommended)** - Set Thread.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 threads per external item (see SYNC_STRATEGIES.md)\n5. **Most Threads should be `ThreadType.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 Thread.source to the canonical URL/ID\n \u2502 Create Thread (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 threads 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 threads from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Thread with that UUID\n \u2502 Store mapping: external_id \u2192 thread_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 Thread using stored UUID\n \u2514\u2500 Not found \u2192 Create new Thread with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Thread,\n type NewThreadWithNotes,\n type ThreadFilter,\n type Priority,\n type ToolBuilder,\n Twist,\n ThreadType,\n} from \"@plotday/twister\";\nimport { ThreadAccess, Plot } from \"@plotday/twister/tools/plot\";\n// Import your sources or tools as needed\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot, {\n thread: { access: ThreadAccess.Create },\n }),\n };\n }\n\n async activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection handled in the twist edit modal.\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## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Auth and resource selection are handled automatically via the twist edit modal when using external tools with Integrations.\n\nMost twists have an empty or minimal `activate()`:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection are handled in the twist edit modal.\n // Only add custom initialization here if needed.\n}\n```\n\n**Store Parent Thread for Later (optional):**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const threadId = await this.tools.plot.createThread({\n type: ThreadType.Note,\n title: \"Setup complete\",\n notes: [{\n content: \"Your twist is ready. Threads will appear as they sync.\",\n }],\n });\n await this.set(\"setup_thread_id\", threadId);\n}\n```\n\n### Event Callbacks (via build options)\n\nTwists respond to events through callbacks declared in `build()`:\n\n**React to thread changes (for two-way sync):**\n\n```typescript\nplot: build(Plot, {\n thread: {\n access: ThreadAccess.Create,\n updated: this.onThreadUpdated,\n },\n note: {\n created: this.onNoteCreated,\n },\n}),\n\nasync onThreadUpdated(thread: Thread, changes: { tagsAdded, tagsRemoved }): Promise<void> {\n const tool = this.getToolForThread(thread);\n if (tool?.updateIssue) await tool.updateIssue(thread);\n}\n\nasync onNoteCreated(note: Note): Promise<void> {\n if (note.author.type === ActorType.Twist) return; // Prevent loops\n // Sync note to external service as a comment\n}\n```\n\n**Respond to mentions (AI twist pattern):**\n\n```typescript\nplot: build(Plot, {\n thread: { access: ThreadAccess.Respond },\n note: {\n intents: [{\n description: \"Respond to general questions\",\n examples: [\"What's the weather?\", \"Help me plan my week\"],\n handler: this.respond,\n }],\n },\n}),\n```\n\n## Actions\n\nActions enable user interaction:\n\n```typescript\nimport { type Action, ActionType } from \"@plotday/twister\";\n\n// External URL action\nconst urlAction: Action = {\n title: \"Open website\",\n type: ActionType.external,\n url: \"https://example.com\",\n};\n\n// Callback action (uses Callbacks tool \u2014 use linkCallback, not callback)\nconst token = await this.linkCallback(this.onActionClicked, \"context\");\nconst callbackAction: Action = {\n title: \"Click me\",\n type: ActionType.callback,\n callback: token,\n};\n\n// Add to thread note\nawait this.tools.plot.createThread({\n type: ThreadType.Note,\n title: \"Task with actions\",\n notes: [\n {\n content: \"Click the actions below to take action.\",\n actions: [urlAction, callbackAction],\n },\n ],\n});\n\n// Callback handler receives the Action as first argument\nasync onActionClicked(action: Action, context: string): Promise<void> {\n // Handle action click\n}\n```\n\n## Authentication Pattern\n\nAuth is handled automatically via the Integrations tool. Tools declare their OAuth provider in `build()`, and users connect in the twist edit modal. **You do not need to create auth activities manually.**\n\n```typescript\n// In your tool's build() method:\nbuild(build: ToolBuilder) {\n return {\n integrations: build(Integrations, {\n providers: [{\n provider: AuthProvider.Google,\n scopes: [\"https://www.googleapis.com/auth/calendar\"],\n getChannels: this.getChannels, // List available resources after auth\n onChannelEnabled: this.onChannelEnabled, // User enabled a resource\n onChannelDisabled: this.onChannelDisabled, // User disabled a resource\n }],\n }),\n // ...\n };\n}\n\n// Get a token for API calls:\nconst token = await this.tools.integrations.get(AuthProvider.Google, channelId);\nif (!token) throw new Error(\"No auth token available\");\nconst client = new ApiClient({ accessToken: token.token });\n```\n\nFor per-user write-backs (e.g., RSVP, comments attributed to the acting user):\n\n```typescript\nawait this.tools.integrations.actAs(\n AuthProvider.Google,\n actorId, // The user who performed the action\n threadId, // Thread to prompt for auth if needed\n this.performWriteBack,\n ...extraArgs\n);\n```\n\n## Sync Pattern\n\n### Upsert via Source/Key (Strategy 2)\n\nUse source/key for automatic upserts:\n\n```typescript\nasync handleEvent(event: ExternalEvent): Promise<void> {\n const thread: NewThreadWithNotes = {\n source: event.htmlLink, // Canonical URL for automatic deduplication\n type: ThreadType.Event,\n title: event.summary || \"(No title)\",\n notes: [],\n };\n\n if (event.description) {\n thread.notes.push({\n thread: { source: event.htmlLink },\n key: \"description\", // This key enables note-level upserts\n content: event.description,\n });\n }\n\n // Create or update \u2014 Plot handles deduplication automatically\n await this.tools.plot.createThread(thread);\n}\n```\n\n### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot threads 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 incomingThread: NewThreadWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingThread.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 existingThreadId = await this.get<Uuid>(mappingKey);\n\n if (existingThreadId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingThread.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n thread: { id: existingThreadId },\n content: incomingThread.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const threadId = Uuid.Generate();\n await this.set(mappingKey, threadId);\n\n // Create new Thread with initial Note (new thread with first message)\n await this.tools.plot.createThread({\n ...incomingThread,\n id: threadId,\n });\n}\n```\n\n## Resource Selection\n\nResource selection (calendars, projects, channels) is handled automatically in the twist edit modal via the Integrations tool. Users see a list of available resources returned by your tool's `getChannels()` method and toggle them on/off. You do **not** need to build custom selection UI.\n\n```typescript\n// In your tool:\nasync getChannels(_auth: Authorization, token: AuthToken): Promise<Channel[]> {\n const client = new ApiClient({ accessToken: token.token });\n const calendars = await client.listCalendars();\n return calendars.map(c => ({\n id: c.id,\n title: c.name,\n children: c.subCalendars?.map(sc => ({ id: sc.id, title: sc.name })),\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(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 createThread may make ~5-10 requests depending on notes/links\n await this.tools.plot.createThread({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ThreadType.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 ...(state.initialSync ? { unread: false } : {}), // false for initial, omit 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.createThread({\n type: ThreadType.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## Thread Sync Best Practices\n\nWhen syncing threads 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` | *omit* | Initial: mark read for all. Incremental: auto-mark read for author only |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst thread: NewThread = {\n type: ThreadType.Event,\n source: event.url,\n title: event.title,\n ...(initialSync ? { unread: false } : {}), // false for initial, omit 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 for all users, preventing spam from bulk historical imports\n- **Incremental sync**: Activities are auto-marked read for the author (twist owner), unread for everyone else. Archived state is preserved\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Thread/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Thread.id` / `Note.id` in the external item's metadata when creating it, and update `Thread.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes \u2014 that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\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.createThread({\n type: ThreadType.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 threads** - Other users may change a Thread created by the twist, resulting in a callback. Be sure to check the `changes === null` and/or `thread.author.id !== this.id` to avoid re-processing.\n- **Always create Threads with Notes** - See \"Understanding Threads and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Thread types** - Most should be `ThreadType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Thread.source and Note.key for automatic upserts (Recommended)** - Set Thread.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 Threads** - For source/key pattern, reference threads by source. For UUID pattern, look up stored mappings before creating new Threads. 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";
1
+ export declare const TWIST_GUIDE = "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited 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 Threads and Notes\n\n**CRITICAL CONCEPT**: A **Thread** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that thread.\n\n**Think of a Thread as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Threads with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Threads for updates** - Don't create a new Thread for each related message\n3. **Use Thread.source and Note.key for automatic upserts (Recommended)** - Set Thread.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 threads per external item (see SYNC_STRATEGIES.md)\n5. **Most Threads should be `ThreadType.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 Thread.source to the canonical URL/ID\n \u2502 Create Thread (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 threads 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 threads from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Thread with that UUID\n \u2502 Store mapping: external_id \u2192 thread_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 Thread using stored UUID\n \u2514\u2500 Not found \u2192 Create new Thread with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Thread,\n type NewThreadWithNotes,\n type ThreadFilter,\n type Priority,\n type ToolBuilder,\n Twist,\n ThreadType,\n} from \"@plotday/twister\";\nimport { ThreadAccess, Plot } from \"@plotday/twister/tools/plot\";\n// Import your sources or tools as needed\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot, {\n thread: { access: ThreadAccess.Create },\n }),\n };\n }\n\n async activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection handled in the twist edit modal.\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## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Auth and resource selection are handled automatically via the twist edit modal when using external tools with Integrations.\n\nMost twists have an empty or minimal `activate()`:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection are handled in the twist edit modal.\n // Only add custom initialization here if needed.\n}\n```\n\n**Store Parent Thread for Later (optional):**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const threadId = await this.tools.plot.createThread({\n type: ThreadType.Note,\n title: \"Setup complete\",\n notes: [{\n content: \"Your twist is ready. Threads will appear as they sync.\",\n }],\n });\n await this.set(\"setup_thread_id\", threadId);\n}\n```\n\n### Event Callbacks (via build options)\n\nTwists respond to events through callbacks declared in `build()`:\n\n**React to thread changes (for two-way sync):**\n\n```typescript\nplot: build(Plot, {\n thread: {\n access: ThreadAccess.Create,\n updated: this.onThreadUpdated,\n },\n note: {\n created: this.onNoteCreated,\n },\n}),\n\nasync onThreadUpdated(thread: Thread, changes: { tagsAdded, tagsRemoved }): Promise<void> {\n const tool = this.getToolForThread(thread);\n if (tool?.updateIssue) await tool.updateIssue(thread);\n}\n\nasync onNoteCreated(note: Note): Promise<void> {\n if (note.author.type === ActorType.Twist) return; // Prevent loops\n // Sync note to external service as a comment\n}\n```\n\n**Respond to mentions (AI twist pattern):**\n\n```typescript\nplot: build(Plot, {\n thread: { access: ThreadAccess.Respond },\n note: {\n intents: [{\n description: \"Respond to general questions\",\n examples: [\"What's the weather?\", \"Help me plan my week\"],\n handler: this.respond,\n }],\n },\n}),\n```\n\n**Default mention on replies:**\n\nWhen your twist processes replies (two-way comment sync or conversational AI), set `defaultMention: true` so the user doesn't have to manually re-mention your twist on every note:\n\n- `thread.defaultMention` \u2014 Auto-mention on replies to threads your twist created (e.g., synced issues, emails)\n- `note.defaultMention` \u2014 Auto-mention on follow-up notes in threads where your twist was @-mentioned (e.g., conversational agents)\n\n```typescript\n// Connector with two-way comment sync\nplot: build(Plot, {\n thread: {\n access: ThreadAccess.Create,\n defaultMention: true, // Users replying to synced threads will mention this twist by default\n updated: this.onThreadUpdated,\n },\n note: {\n created: this.onNoteCreated,\n },\n}),\n\n// Conversational AI twist\nplot: build(Plot, {\n thread: { access: ThreadAccess.Respond },\n note: {\n defaultMention: true, // Follow-up notes auto-mention this twist\n intents: [{ description: \"...\", examples: [...], handler: this.respond }],\n },\n}),\n```\n\nWithout `defaultMention`, the twist chip appears toggled OFF by default \u2014 the user can still enable it manually per-note.\n\n## Actions\n\nActions enable user interaction:\n\n```typescript\nimport { type Action, ActionType } from \"@plotday/twister\";\n\n// External URL action\nconst urlAction: Action = {\n title: \"Open website\",\n type: ActionType.external,\n url: \"https://example.com\",\n};\n\n// Callback action (uses Callbacks tool \u2014 use linkCallback, not callback)\nconst token = await this.linkCallback(this.onActionClicked, \"context\");\nconst callbackAction: Action = {\n title: \"Click me\",\n type: ActionType.callback,\n callback: token,\n};\n\n// Add to thread note\nawait this.tools.plot.createThread({\n type: ThreadType.Note,\n title: \"Task with actions\",\n notes: [\n {\n content: \"Click the actions below to take action.\",\n actions: [urlAction, callbackAction],\n },\n ],\n});\n\n// Callback handler receives the Action as first argument\nasync onActionClicked(action: Action, context: string): Promise<void> {\n // Handle action click\n}\n```\n\n## Authentication Pattern\n\nAuth is handled automatically via the Integrations tool. Tools declare their OAuth provider in `build()`, and users connect in the twist edit modal. **You do not need to create auth activities manually.**\n\n```typescript\n// In your tool's build() method:\nbuild(build: ToolBuilder) {\n return {\n integrations: build(Integrations, {\n providers: [{\n provider: AuthProvider.Google,\n scopes: [\"https://www.googleapis.com/auth/calendar\"],\n getChannels: this.getChannels, // List available resources after auth\n onChannelEnabled: this.onChannelEnabled, // User enabled a resource\n onChannelDisabled: this.onChannelDisabled, // User disabled a resource\n }],\n }),\n // ...\n };\n}\n\n// Get a token for API calls:\nconst token = await this.tools.integrations.get(AuthProvider.Google, channelId);\nif (!token) throw new Error(\"No auth token available\");\nconst client = new ApiClient({ accessToken: token.token });\n```\n\nFor per-user write-backs (e.g., RSVP, comments attributed to the acting user):\n\n```typescript\nawait this.tools.integrations.actAs(\n AuthProvider.Google,\n actorId, // The user who performed the action\n threadId, // Thread to prompt for auth if needed\n this.performWriteBack,\n ...extraArgs\n);\n```\n\n## Sync Pattern\n\n### Upsert via Source/Key (Strategy 2)\n\nUse source/key for automatic upserts:\n\n```typescript\nasync handleEvent(event: ExternalEvent): Promise<void> {\n const thread: NewThreadWithNotes = {\n source: event.htmlLink, // Canonical URL for automatic deduplication\n type: ThreadType.Event,\n title: event.summary || \"(No title)\",\n notes: [],\n };\n\n if (event.description) {\n thread.notes.push({\n thread: { source: event.htmlLink },\n key: \"description\", // This key enables note-level upserts\n content: event.description,\n });\n }\n\n // Create or update \u2014 Plot handles deduplication automatically\n await this.tools.plot.createThread(thread);\n}\n```\n\n### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot threads 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 incomingThread: NewThreadWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingThread.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 existingThreadId = await this.get<Uuid>(mappingKey);\n\n if (existingThreadId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingThread.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n thread: { id: existingThreadId },\n content: incomingThread.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const threadId = Uuid.Generate();\n await this.set(mappingKey, threadId);\n\n // Create new Thread with initial Note (new thread with first message)\n await this.tools.plot.createThread({\n ...incomingThread,\n id: threadId,\n });\n}\n```\n\n## Resource Selection\n\nResource selection (calendars, projects, channels) is handled automatically in the twist edit modal via the Integrations tool. Users see a list of available resources returned by your tool's `getChannels()` method and toggle them on/off. You do **not** need to build custom selection UI.\n\n```typescript\n// In your tool:\nasync getChannels(_auth: Authorization, token: AuthToken): Promise<Channel[]> {\n const client = new ApiClient({ accessToken: token.token });\n const calendars = await client.listCalendars();\n return calendars.map(c => ({\n id: c.id,\n title: c.name,\n children: c.subCalendars?.map(sc => ({ id: sc.id, title: sc.name })),\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(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 createThread may make ~5-10 requests depending on notes/links\n await this.tools.plot.createThread({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ThreadType.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 ...(state.initialSync ? { unread: false } : {}), // false for initial, omit 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.createThread({\n type: ThreadType.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## Thread Sync Best Practices\n\nWhen syncing threads 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` | *omit* | Initial: mark read for all. Incremental: auto-mark read for author only |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst thread: NewThread = {\n type: ThreadType.Event,\n source: event.url,\n title: event.title,\n ...(initialSync ? { unread: false } : {}), // false for initial, omit 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 for all users, preventing spam from bulk historical imports\n- **Incremental sync**: Activities are auto-marked read for the author (twist owner), unread for everyone else. Archived state is preserved\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Thread/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Thread.id` / `Note.id` in the external item's metadata when creating it, and update `Thread.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes \u2014 that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\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.createThread({\n type: ThreadType.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 threads** - Other users may change a Thread created by the twist, resulting in a callback. Be sure to check the `changes === null` and/or `thread.author.id !== this.id` to avoid re-processing.\n- **Always create Threads with Notes** - See \"Understanding Threads and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Thread types** - Most should be `ThreadType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Thread.source and Note.key for automatic upserts (Recommended)** - Set Thread.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 Threads** - For source/key pattern, reference threads by source. For UUID pattern, look up stored mappings before creating new Threads. 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";
2
2
  //# sourceMappingURL=twist-guide.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"twist-guide.d.ts","sourceRoot":"","sources":["../src/twist-guide.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,WAAW,yntBAAsB,CAAC"}
1
+ {"version":3,"file":"twist-guide.d.ts","sourceRoot":"","sources":["../src/twist-guide.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,WAAW,6yvBAAsB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plotday/twister",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "Plot Twist Creator - Build intelligent extensions that integrate and automate",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,172 +10,172 @@
10
10
  },
11
11
  "exports": {
12
12
  ".": {
13
- "@plotday/source": "./src/index.ts",
13
+ "@plotday/connector": "./src/index.ts",
14
14
  "types": "./dist/index.d.ts",
15
15
  "default": "./dist/index.js"
16
16
  },
17
17
  "./twist": {
18
- "@plotday/source": "./src/twist.ts",
18
+ "@plotday/connector": "./src/twist.ts",
19
19
  "types": "./dist/twist.d.ts",
20
20
  "default": "./dist/twist.js"
21
21
  },
22
22
  "./tool": {
23
- "@plotday/source": "./src/tool.ts",
23
+ "@plotday/connector": "./src/tool.ts",
24
24
  "types": "./dist/tool.d.ts",
25
25
  "default": "./dist/tool.js"
26
26
  },
27
- "./source": {
28
- "@plotday/source": "./src/source.ts",
29
- "types": "./dist/source.d.ts",
30
- "default": "./dist/source.js"
27
+ "./connector": {
28
+ "@plotday/connector": "./src/connector.ts",
29
+ "types": "./dist/connector.d.ts",
30
+ "default": "./dist/connector.js"
31
31
  },
32
32
  "./plot": {
33
- "@plotday/source": "./src/plot.ts",
33
+ "@plotday/connector": "./src/plot.ts",
34
34
  "types": "./dist/plot.d.ts",
35
35
  "default": "./dist/plot.js"
36
36
  },
37
37
  "./schedule": {
38
- "@plotday/source": "./src/schedule.ts",
38
+ "@plotday/connector": "./src/schedule.ts",
39
39
  "types": "./dist/schedule.d.ts",
40
40
  "default": "./dist/schedule.js"
41
41
  },
42
42
  "./tag": {
43
- "@plotday/source": "./src/tag.ts",
43
+ "@plotday/connector": "./src/tag.ts",
44
44
  "types": "./dist/tag.d.ts",
45
45
  "default": "./dist/tag.js"
46
46
  },
47
47
  "./options": {
48
- "@plotday/source": "./src/options.ts",
48
+ "@plotday/connector": "./src/options.ts",
49
49
  "types": "./dist/options.d.ts",
50
50
  "default": "./dist/options.js"
51
51
  },
52
52
  "./tools/twists": {
53
- "@plotday/source": "./src/tools/twists.ts",
53
+ "@plotday/connector": "./src/tools/twists.ts",
54
54
  "types": "./dist/tools/twists.d.ts",
55
55
  "default": "./dist/tools/twists.js"
56
56
  },
57
57
  "./tools/ai": {
58
- "@plotday/source": "./src/tools/ai.ts",
58
+ "@plotday/connector": "./src/tools/ai.ts",
59
59
  "types": "./dist/tools/ai.d.ts",
60
60
  "default": "./dist/tools/ai.js"
61
61
  },
62
62
  "./tools/integrations": {
63
- "@plotday/source": "./src/tools/integrations.ts",
63
+ "@plotday/connector": "./src/tools/integrations.ts",
64
64
  "types": "./dist/tools/integrations.d.ts",
65
65
  "default": "./dist/tools/integrations.js"
66
66
  },
67
67
  "./tools/callbacks": {
68
- "@plotday/source": "./src/tools/callbacks.ts",
68
+ "@plotday/connector": "./src/tools/callbacks.ts",
69
69
  "types": "./dist/tools/callbacks.d.ts",
70
70
  "default": "./dist/tools/callbacks.js"
71
71
  },
72
72
  "./tools/network": {
73
- "@plotday/source": "./src/tools/network.ts",
73
+ "@plotday/connector": "./src/tools/network.ts",
74
74
  "types": "./dist/tools/network.d.ts",
75
75
  "default": "./dist/tools/network.js"
76
76
  },
77
77
  "./tools/plot": {
78
- "@plotday/source": "./src/tools/plot.ts",
78
+ "@plotday/connector": "./src/tools/plot.ts",
79
79
  "types": "./dist/tools/plot.d.ts",
80
80
  "default": "./dist/tools/plot.js"
81
81
  },
82
82
  "./tools/tasks": {
83
- "@plotday/source": "./src/tools/tasks.ts",
83
+ "@plotday/connector": "./src/tools/tasks.ts",
84
84
  "types": "./dist/tools/tasks.d.ts",
85
85
  "default": "./dist/tools/tasks.js"
86
86
  },
87
87
  "./tools/store": {
88
- "@plotday/source": "./src/tools/store.ts",
88
+ "@plotday/connector": "./src/tools/store.ts",
89
89
  "types": "./dist/tools/store.d.ts",
90
90
  "default": "./dist/tools/store.js"
91
91
  },
92
92
  "./utils/types": {
93
- "@plotday/source": "./src/utils/types.ts",
93
+ "@plotday/connector": "./src/utils/types.ts",
94
94
  "types": "./dist/utils/types.d.ts",
95
95
  "default": "./dist/utils/types.js"
96
96
  },
97
97
  "./utils/hash": {
98
- "@plotday/source": "./src/utils/hash.ts",
98
+ "@plotday/connector": "./src/utils/hash.ts",
99
99
  "types": "./dist/utils/hash.d.ts",
100
100
  "default": "./dist/utils/hash.js"
101
101
  },
102
102
  "./utils/uuid": {
103
- "@plotday/source": "./src/utils/uuid.ts",
103
+ "@plotday/connector": "./src/utils/uuid.ts",
104
104
  "types": "./dist/utils/uuid.d.ts",
105
105
  "default": "./dist/utils/uuid.js"
106
106
  },
107
107
  "./twist-guide": {
108
- "@plotday/source": "./src/twist-guide.ts",
108
+ "@plotday/connector": "./src/twist-guide.ts",
109
109
  "types": "./dist/twist-guide.d.ts",
110
110
  "default": "./dist/twist-guide.js"
111
111
  },
112
112
  "./creator-docs": {
113
- "@plotday/source": "./src/creator-docs.ts",
113
+ "@plotday/connector": "./src/creator-docs.ts",
114
114
  "types": "./dist/creator-docs.d.ts",
115
115
  "default": "./dist/creator-docs.js"
116
116
  },
117
117
  "./llm-docs": {
118
- "@plotday/source": "./src/llm-docs/index.ts",
118
+ "@plotday/connector": "./src/llm-docs/index.ts",
119
119
  "types": "./dist/llm-docs/index.d.ts",
120
120
  "default": "./dist/llm-docs/index.js"
121
121
  },
122
122
  "./llm-docs/index": {
123
- "@plotday/source": "./src/llm-docs/index.ts",
123
+ "@plotday/connector": "./src/llm-docs/index.ts",
124
124
  "types": "./dist/llm-docs/index.d.ts",
125
125
  "default": "./dist/llm-docs/index.js"
126
126
  },
127
127
  "./llm-docs/twist": {
128
- "@plotday/source": "./src/llm-docs/twist.ts",
128
+ "@plotday/connector": "./src/llm-docs/twist.ts",
129
129
  "types": "./dist/llm-docs/twist.d.ts",
130
130
  "default": "./dist/llm-docs/twist.js"
131
131
  },
132
132
  "./llm-docs/plot": {
133
- "@plotday/source": "./src/llm-docs/plot.ts",
133
+ "@plotday/connector": "./src/llm-docs/plot.ts",
134
134
  "types": "./dist/llm-docs/plot.d.ts",
135
135
  "default": "./dist/llm-docs/plot.js"
136
136
  },
137
137
  "./llm-docs/tag": {
138
- "@plotday/source": "./src/llm-docs/tag.ts",
138
+ "@plotday/connector": "./src/llm-docs/tag.ts",
139
139
  "types": "./dist/llm-docs/tag.d.ts",
140
140
  "default": "./dist/llm-docs/tag.js"
141
141
  },
142
142
  "./llm-docs/tools/twists": {
143
- "@plotday/source": "./src/llm-docs/tools/twists.ts",
143
+ "@plotday/connector": "./src/llm-docs/tools/twists.ts",
144
144
  "types": "./dist/llm-docs/tools/twists.d.ts",
145
145
  "default": "./dist/llm-docs/tools/twists.js"
146
146
  },
147
147
  "./llm-docs/tools/ai": {
148
- "@plotday/source": "./src/llm-docs/tools/ai.ts",
148
+ "@plotday/connector": "./src/llm-docs/tools/ai.ts",
149
149
  "types": "./dist/llm-docs/tools/ai.d.ts",
150
150
  "default": "./dist/llm-docs/tools/ai.js"
151
151
  },
152
152
  "./llm-docs/tools/integrations": {
153
- "@plotday/source": "./src/llm-docs/tools/integrations.ts",
153
+ "@plotday/connector": "./src/llm-docs/tools/integrations.ts",
154
154
  "types": "./dist/llm-docs/tools/integrations.d.ts",
155
155
  "default": "./dist/llm-docs/tools/integrations.js"
156
156
  },
157
157
  "./llm-docs/tools/callbacks": {
158
- "@plotday/source": "./src/llm-docs/tools/callbacks.ts",
158
+ "@plotday/connector": "./src/llm-docs/tools/callbacks.ts",
159
159
  "types": "./dist/llm-docs/tools/callbacks.d.ts",
160
160
  "default": "./dist/llm-docs/tools/callbacks.js"
161
161
  },
162
162
  "./llm-docs/tools/network": {
163
- "@plotday/source": "./src/llm-docs/tools/network.ts",
163
+ "@plotday/connector": "./src/llm-docs/tools/network.ts",
164
164
  "types": "./dist/llm-docs/tools/network.d.ts",
165
165
  "default": "./dist/llm-docs/tools/network.js"
166
166
  },
167
167
  "./llm-docs/tools/plot": {
168
- "@plotday/source": "./src/llm-docs/tools/plot.ts",
168
+ "@plotday/connector": "./src/llm-docs/tools/plot.ts",
169
169
  "types": "./dist/llm-docs/tools/plot.d.ts",
170
170
  "default": "./dist/llm-docs/tools/plot.js"
171
171
  },
172
172
  "./llm-docs/tools/tasks": {
173
- "@plotday/source": "./src/llm-docs/tools/tasks.ts",
173
+ "@plotday/connector": "./src/llm-docs/tools/tasks.ts",
174
174
  "types": "./dist/llm-docs/tools/tasks.d.ts",
175
175
  "default": "./dist/llm-docs/tools/tasks.js"
176
176
  },
177
177
  "./llm-docs/tools/store": {
178
- "@plotday/source": "./src/llm-docs/tools/store.ts",
178
+ "@plotday/connector": "./src/llm-docs/tools/store.ts",
179
179
  "types": "./dist/llm-docs/tools/store.d.ts",
180
180
  "default": "./dist/llm-docs/tools/store.js"
181
181
  },
@@ -6,7 +6,7 @@
6
6
  "lib": ["ES2020", "ES2021", "ES2022.error", "WebWorker"],
7
7
  "module": "ESNext",
8
8
  "moduleResolution": "bundler",
9
- "customConditions": ["@plotday/source"],
9
+ "customConditions": ["@plotday/connector"],
10
10
  "resolveJsonModule": true,
11
11
  "allowJs": true,
12
12
  "checkJs": false,