@plotday/twister 0.27.0 → 0.29.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.
- package/README.md +10 -4
- package/bin/templates/AGENTS.template.md +91 -29
- package/cli/templates/AGENTS.template.md +91 -29
- package/dist/common/calendar.d.ts +35 -28
- package/dist/common/calendar.d.ts.map +1 -1
- package/dist/common/messaging.d.ts +24 -10
- package/dist/common/messaging.d.ts.map +1 -1
- package/dist/common/projects.d.ts +30 -15
- package/dist/common/projects.d.ts.map +1 -1
- package/dist/common/serializable.d.ts +40 -0
- package/dist/common/serializable.d.ts.map +1 -0
- package/dist/common/serializable.js +2 -0
- package/dist/common/serializable.js.map +1 -0
- package/dist/docs/assets/hierarchy.js +1 -1
- package/dist/docs/assets/navigation.js +1 -1
- package/dist/docs/assets/search.js +1 -1
- package/dist/docs/classes/tool.ITool.html +1 -1
- package/dist/docs/classes/tool.Tool.html +32 -28
- package/dist/docs/classes/tools_ai.AI.html +2 -2
- package/dist/docs/classes/tools_callbacks.Callbacks.html +6 -6
- package/dist/docs/classes/tools_integrations.Integrations.html +3 -3
- package/dist/docs/classes/tools_network.Network.html +12 -12
- package/dist/docs/classes/tools_plot.Plot.html +41 -31
- package/dist/docs/classes/tools_store.Store.html +31 -11
- package/dist/docs/classes/tools_tasks.Tasks.html +8 -8
- package/dist/docs/classes/tools_twists.Twists.html +5 -5
- package/dist/docs/classes/twist.Twist.html +28 -24
- package/dist/docs/documents/Building_Custom_Tools.html +8 -2
- package/dist/docs/documents/Built-in_Tools.html +19 -8
- package/dist/docs/documents/Core_Concepts.html +14 -6
- package/dist/docs/documents/Getting_Started.html +11 -4
- package/dist/docs/enums/plot.ActivityLinkType.html +5 -5
- package/dist/docs/enums/plot.ActivityType.html +4 -4
- package/dist/docs/enums/plot.ActorType.html +4 -4
- package/dist/docs/enums/plot.ConferencingProvider.html +6 -6
- package/dist/docs/enums/tag.Tag.html +2 -2
- package/dist/docs/enums/tools_ai.AIModel.html +2 -2
- package/dist/docs/enums/tools_integrations.AuthLevel.html +3 -3
- package/dist/docs/enums/tools_integrations.AuthProvider.html +11 -11
- package/dist/docs/enums/tools_plot.ActivityAccess.html +3 -3
- package/dist/docs/enums/tools_plot.ContactAccess.html +4 -4
- package/dist/docs/enums/tools_plot.PriorityAccess.html +3 -3
- package/dist/docs/functions/index.Uuid.Generate.html +1 -1
- package/dist/docs/functions/utils_hash.quickHash.html +1 -1
- package/dist/docs/hierarchy.html +1 -1
- package/dist/docs/index.html +10 -0
- package/dist/docs/interfaces/common_calendar.Calendar.html +5 -5
- package/dist/docs/interfaces/common_calendar.CalendarTool.html +29 -15
- package/dist/docs/interfaces/common_calendar.SyncOptions.html +3 -3
- package/dist/docs/interfaces/index.SerializableArray.html +2 -0
- package/dist/docs/interfaces/index.SerializableMap.html +2 -0
- package/dist/docs/interfaces/index.SerializableObject.html +2 -0
- package/dist/docs/interfaces/index.SerializableSet.html +2 -0
- package/dist/docs/interfaces/tools_ai.AIRequest.html +11 -11
- package/dist/docs/interfaces/tools_ai.AIResponse.html +9 -9
- package/dist/docs/interfaces/tools_ai.FilePart.html +5 -5
- package/dist/docs/interfaces/tools_ai.ImagePart.html +4 -4
- package/dist/docs/interfaces/tools_ai.ReasoningPart.html +4 -4
- package/dist/docs/interfaces/tools_ai.RedactedReasoningPart.html +3 -3
- package/dist/docs/interfaces/tools_ai.TextPart.html +3 -3
- package/dist/docs/interfaces/tools_ai.ToolCallPart.html +5 -5
- package/dist/docs/interfaces/tools_ai.ToolExecutionOptions.html +4 -4
- package/dist/docs/interfaces/tools_ai.ToolResultPart.html +5 -5
- package/dist/docs/interfaces/tools_twists.TwistSource.html +3 -3
- package/dist/docs/interfaces/utils_types.ToolShed.html +5 -5
- package/dist/docs/media/SYNC_STRATEGIES.md +651 -0
- package/dist/docs/modules/index.html +1 -1
- package/dist/docs/modules/plot.html +1 -1
- package/dist/docs/modules/utils_types.html +1 -1
- package/dist/docs/types/common_calendar.CalendarAuth.html +2 -2
- package/dist/docs/types/index.Serializable.html +17 -0
- package/dist/docs/types/index.Uuid.html +1 -1
- package/dist/docs/types/plot.Activity.html +17 -8
- package/dist/docs/types/plot.ActivityCommon.html +10 -10
- package/dist/docs/types/plot.ActivityLink.html +1 -1
- package/dist/docs/types/plot.ActivityMeta.html +5 -3
- package/dist/docs/types/plot.ActivityUpdate.html +4 -2
- package/dist/docs/types/plot.ActivityWithNotes.html +1 -1
- package/dist/docs/types/plot.Actor.html +15 -5
- package/dist/docs/types/plot.ActorId.html +1 -1
- package/dist/docs/types/plot.ContentType.html +1 -1
- package/dist/docs/types/plot.NewActivity.html +26 -12
- package/dist/docs/types/plot.NewActivityWithNotes.html +1 -1
- package/dist/docs/types/plot.NewActor.html +1 -1
- package/dist/docs/types/plot.NewContact.html +4 -4
- package/dist/docs/types/plot.NewNote.html +9 -4
- package/dist/docs/types/plot.NewPriority.html +15 -5
- package/dist/docs/types/plot.NewTags.html +1 -1
- package/dist/docs/types/plot.Note.html +6 -3
- package/dist/docs/types/plot.NoteUpdate.html +4 -3
- package/dist/docs/types/plot.PickPriorityConfig.html +3 -3
- package/dist/docs/types/plot.Priority.html +9 -4
- package/dist/docs/types/plot.PriorityUpdate.html +3 -0
- package/dist/docs/types/plot.SyncUpdate.html +1 -1
- package/dist/docs/types/plot.Tags.html +1 -1
- package/dist/docs/types/tools_ai.AIAssistantMessage.html +2 -2
- package/dist/docs/types/tools_ai.AIMessage.html +1 -1
- package/dist/docs/types/tools_ai.AISource.html +1 -1
- package/dist/docs/types/tools_ai.AISystemMessage.html +2 -2
- package/dist/docs/types/tools_ai.AITool.html +1 -1
- package/dist/docs/types/tools_ai.AIToolMessage.html +2 -2
- package/dist/docs/types/tools_ai.AIToolSet.html +1 -1
- package/dist/docs/types/tools_ai.AIUsage.html +5 -5
- package/dist/docs/types/tools_ai.AIUserMessage.html +2 -2
- package/dist/docs/types/tools_ai.DataContent.html +1 -1
- package/dist/docs/types/tools_ai.ModelPreferences.html +4 -4
- package/dist/docs/types/tools_callbacks.Callback.html +1 -1
- package/dist/docs/types/tools_integrations.AuthToken.html +4 -4
- package/dist/docs/types/tools_integrations.Authorization.html +4 -4
- package/dist/docs/types/tools_network.WebhookRequest.html +6 -6
- package/dist/docs/types/tools_plot.NoteIntentHandler.html +4 -4
- package/dist/docs/types/tools_twists.Log.html +2 -2
- package/dist/docs/types/tools_twists.TwistPermissions.html +1 -1
- package/dist/docs/types/utils_types.BuiltInTools.html +2 -2
- package/dist/docs/types/utils_types.CallbackMethods.html +1 -1
- package/dist/docs/types/utils_types.ExtractBuildReturn.html +1 -1
- package/dist/docs/types/utils_types.InferOptions.html +1 -1
- package/dist/docs/types/utils_types.InferTools.html +1 -1
- package/dist/docs/types/utils_types.JSONValue.html +7 -0
- package/dist/docs/types/utils_types.NoFunctions.html +1 -1
- package/dist/docs/types/utils_types.NonFunction.html +1 -1
- package/dist/docs/types/utils_types.PromiseValues.html +1 -1
- package/dist/docs/types/utils_types.ToolBuilder.html +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/llm-docs/common/calendar.d.ts +1 -1
- package/dist/llm-docs/common/calendar.d.ts.map +1 -1
- package/dist/llm-docs/common/calendar.js +1 -1
- package/dist/llm-docs/common/calendar.js.map +1 -1
- package/dist/llm-docs/common/messaging.d.ts +1 -1
- package/dist/llm-docs/common/messaging.d.ts.map +1 -1
- package/dist/llm-docs/common/messaging.js +1 -1
- package/dist/llm-docs/common/messaging.js.map +1 -1
- package/dist/llm-docs/common/projects.d.ts +1 -1
- package/dist/llm-docs/common/projects.d.ts.map +1 -1
- package/dist/llm-docs/common/projects.js +1 -1
- package/dist/llm-docs/common/projects.js.map +1 -1
- package/dist/llm-docs/plot.d.ts +1 -1
- package/dist/llm-docs/plot.d.ts.map +1 -1
- package/dist/llm-docs/plot.js +1 -1
- package/dist/llm-docs/plot.js.map +1 -1
- package/dist/llm-docs/tool.d.ts +1 -1
- package/dist/llm-docs/tool.d.ts.map +1 -1
- package/dist/llm-docs/tool.js +1 -1
- package/dist/llm-docs/tool.js.map +1 -1
- package/dist/llm-docs/tools/network.d.ts +1 -1
- package/dist/llm-docs/tools/network.d.ts.map +1 -1
- package/dist/llm-docs/tools/network.js +1 -1
- package/dist/llm-docs/tools/network.js.map +1 -1
- package/dist/llm-docs/tools/plot.d.ts +1 -1
- package/dist/llm-docs/tools/plot.d.ts.map +1 -1
- package/dist/llm-docs/tools/plot.js +1 -1
- package/dist/llm-docs/tools/plot.js.map +1 -1
- package/dist/llm-docs/tools/store.d.ts +1 -1
- package/dist/llm-docs/tools/store.d.ts.map +1 -1
- package/dist/llm-docs/tools/store.js +1 -1
- package/dist/llm-docs/tools/store.js.map +1 -1
- package/dist/llm-docs/tools/tasks.d.ts +1 -1
- package/dist/llm-docs/tools/tasks.d.ts.map +1 -1
- package/dist/llm-docs/tools/tasks.js +1 -1
- package/dist/llm-docs/tools/tasks.js.map +1 -1
- package/dist/llm-docs/twist-guide-template.d.ts +1 -1
- package/dist/llm-docs/twist-guide-template.d.ts.map +1 -1
- package/dist/llm-docs/twist-guide-template.js +1 -1
- package/dist/llm-docs/twist-guide-template.js.map +1 -1
- package/dist/llm-docs/twist.d.ts +1 -1
- package/dist/llm-docs/twist.d.ts.map +1 -1
- package/dist/llm-docs/twist.js +1 -1
- package/dist/llm-docs/twist.js.map +1 -1
- package/dist/plot.d.ts +232 -56
- package/dist/plot.d.ts.map +1 -1
- package/dist/plot.js.map +1 -1
- package/dist/tool.d.ts +30 -8
- package/dist/tool.d.ts.map +1 -1
- package/dist/tool.js +29 -7
- package/dist/tool.js.map +1 -1
- package/dist/tools/network.d.ts +19 -16
- package/dist/tools/network.d.ts.map +1 -1
- package/dist/tools/network.js +6 -4
- package/dist/tools/network.js.map +1 -1
- package/dist/tools/plot.d.ts +93 -24
- package/dist/tools/plot.d.ts.map +1 -1
- package/dist/tools/plot.js +46 -1
- package/dist/tools/plot.js.map +1 -1
- package/dist/tools/store.d.ts +49 -8
- package/dist/tools/store.d.ts.map +1 -1
- package/dist/tools/store.js +12 -1
- package/dist/tools/store.js.map +1 -1
- package/dist/tools/tasks.d.ts +4 -4
- package/dist/tools/tasks.js +4 -4
- package/dist/twist-guide.d.ts +1 -1
- package/dist/twist-guide.d.ts.map +1 -1
- package/dist/twist.d.ts +24 -10
- package/dist/twist.d.ts.map +1 -1
- package/dist/twist.js +19 -5
- package/dist/twist.js.map +1 -1
- package/dist/utils/types.d.ts +19 -0
- package/dist/utils/types.d.ts.map +1 -1
- 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 \"..\";\n\n/**\n * Built-in tool for persistent key-value storage.\n *\n * The Store tool provides twists and tools with a simple, persistent storage\n * mechanism that survives worker restarts and invocations. Each twist/tool\n * instance gets its own isolated storage namespace.\n *\n * **Note:** Store methods are also available directly on Twist and Tool classes\n * via `this.get()`, `this.set()`, `this.clear()`, and `this.clearAll()`.\n * This is the recommended approach for most use cases.\n *\n * **Storage Characteristics:**\n * - Persistent across worker restarts\n * - Isolated per twist/tool instance\n * - Supports
|
|
7
|
+
declare const _default: "import { ITool, type Serializable } from \"..\";\n\n/**\n * Built-in tool for persistent key-value storage.\n *\n * The Store tool provides twists and tools with a simple, persistent storage\n * mechanism that survives worker restarts and invocations. Each twist/tool\n * instance gets its own isolated storage namespace.\n *\n * **Note:** Store methods are also available directly on Twist and Tool classes\n * via `this.get()`, `this.set()`, `this.clear()`, and `this.clearAll()`.\n * This is the recommended approach for most use cases.\n *\n * **Storage Characteristics:**\n * - Persistent across worker restarts\n * - Isolated per twist/tool instance\n * - Supports SuperJSON-serializable data (see below)\n * - Async operations for scalability\n *\n * **Supported Data Types (via SuperJSON):**\n * - Primitives: string, number, boolean, null, undefined\n * - Complex types: Date, RegExp, Map, Set, Error, URL, BigInt\n * - Collections: Arrays and objects (recursively)\n *\n * **NOT Supported (will throw validation errors):**\n * - Functions (use callback tokens instead - see Callbacks tool)\n * - Symbols\n * - Circular references\n * - Custom class instances\n *\n * **Use Cases:**\n * - Storing authentication tokens\n * - Caching configuration data\n * - Maintaining sync state\n * - Persisting user preferences\n * - Tracking processing checkpoints\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool {\n * async saveAuthToken(provider: string, token: string) {\n * // Using built-in set method (recommended)\n * await this.set(`auth_token_${provider}`, token);\n * }\n *\n * async getAuthToken(provider: string): Promise<string | null> {\n * // Using built-in get method (recommended)\n * return await this.get<string>(`auth_token_${provider}`);\n * }\n *\n * async clearAllTokens() {\n * // Using built-in clearAll method (recommended)\n * await this.clearAll();\n * }\n * }\n * ```\n */\nexport abstract class Store extends ITool {\n /**\n * Retrieves a value from storage by key.\n *\n * Returns the stored value deserialized to the specified type,\n * or null if the key doesn't exist or the value is null.\n *\n * Values are automatically deserialized using SuperJSON, which\n * properly restores Date objects, Maps, Sets, and other complex types.\n *\n * @template T - The expected type of the stored value (must be Serializable)\n * @param key - The storage key to retrieve\n * @returns Promise resolving to the stored value or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get<T extends Serializable>(key: string): Promise<T | null>;\n\n /**\n * Stores a value in persistent storage.\n *\n * The value will be serialized using SuperJSON and stored persistently.\n * Any existing value at the same key will be overwritten.\n *\n * SuperJSON automatically handles Date objects, Maps, Sets, undefined values,\n * and other complex types that standard JSON doesn't support.\n *\n * @template T - The type of value being stored (must be Serializable)\n * @param key - The storage key to use\n * @param value - The value to store (must be SuperJSON-serializable)\n * @returns Promise that resolves when the value is stored\n *\n * @example\n * ```typescript\n * // Date objects are preserved\n * await this.set('sync_state', {\n * lastSync: new Date(),\n * minDate: new Date(2024, 0, 1)\n * });\n *\n * // undefined is now supported\n * await this.set('data', { name: 'test', optional: undefined }); // \u2705 Works\n *\n * // Arrays with undefined are supported\n * await this.set('items', [1, undefined, 3]); // \u2705 Works\n * await this.set('items', [1, null, 3]); // \u2705 Also works\n *\n * // Maps and Sets are supported\n * await this.set('mapping', new Map([['key', 'value']])); // \u2705 Works\n * await this.set('tags', new Set(['tag1', 'tag2'])); // \u2705 Works\n *\n * // Functions are NOT supported - use callback tokens instead\n * const token = await this.callback(this.myFunction);\n * await this.set('callback_ref', token); // \u2705 Use callback token\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract set<T extends Serializable>(key: string, value: T): Promise<void>;\n\n /**\n * Removes a specific key from storage.\n *\n * After this operation, get() calls for this key will return null.\n * No error is thrown if the key doesn't exist.\n *\n * @param key - The storage key to remove\n * @returns Promise that resolves when the key is removed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract clear(key: string): Promise<void>;\n\n /**\n * Removes all keys from this storage instance.\n *\n * This operation clears all data stored by this twist/tool instance\n * but does not affect storage for other twists or tools.\n *\n * @returns Promise that resolves when all keys are removed\n */\n abstract clearAll(): Promise<void>;\n}\n";
|
|
8
8
|
export default _default;
|
|
9
9
|
//# sourceMappingURL=store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,s9JAAw7J;AAAv8J,wBAAw8J"}
|
|
@@ -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 \"..\";\n\n/**\n * Built-in tool for persistent key-value storage.\n *\n * The Store tool provides twists and tools with a simple, persistent storage\n * mechanism that survives worker restarts and invocations. Each twist/tool\n * instance gets its own isolated storage namespace.\n *\n * **Note:** Store methods are also available directly on Twist and Tool classes\n * via `this.get()`, `this.set()`, `this.clear()`, and `this.clearAll()`.\n * This is the recommended approach for most use cases.\n *\n * **Storage Characteristics:**\n * - Persistent across worker restarts\n * - Isolated per twist/tool instance\n * - Supports
|
|
7
|
+
export default "import { ITool, type Serializable } from \"..\";\n\n/**\n * Built-in tool for persistent key-value storage.\n *\n * The Store tool provides twists and tools with a simple, persistent storage\n * mechanism that survives worker restarts and invocations. Each twist/tool\n * instance gets its own isolated storage namespace.\n *\n * **Note:** Store methods are also available directly on Twist and Tool classes\n * via `this.get()`, `this.set()`, `this.clear()`, and `this.clearAll()`.\n * This is the recommended approach for most use cases.\n *\n * **Storage Characteristics:**\n * - Persistent across worker restarts\n * - Isolated per twist/tool instance\n * - Supports SuperJSON-serializable data (see below)\n * - Async operations for scalability\n *\n * **Supported Data Types (via SuperJSON):**\n * - Primitives: string, number, boolean, null, undefined\n * - Complex types: Date, RegExp, Map, Set, Error, URL, BigInt\n * - Collections: Arrays and objects (recursively)\n *\n * **NOT Supported (will throw validation errors):**\n * - Functions (use callback tokens instead - see Callbacks tool)\n * - Symbols\n * - Circular references\n * - Custom class instances\n *\n * **Use Cases:**\n * - Storing authentication tokens\n * - Caching configuration data\n * - Maintaining sync state\n * - Persisting user preferences\n * - Tracking processing checkpoints\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool {\n * async saveAuthToken(provider: string, token: string) {\n * // Using built-in set method (recommended)\n * await this.set(`auth_token_${provider}`, token);\n * }\n *\n * async getAuthToken(provider: string): Promise<string | null> {\n * // Using built-in get method (recommended)\n * return await this.get<string>(`auth_token_${provider}`);\n * }\n *\n * async clearAllTokens() {\n * // Using built-in clearAll method (recommended)\n * await this.clearAll();\n * }\n * }\n * ```\n */\nexport abstract class Store extends ITool {\n /**\n * Retrieves a value from storage by key.\n *\n * Returns the stored value deserialized to the specified type,\n * or null if the key doesn't exist or the value is null.\n *\n * Values are automatically deserialized using SuperJSON, which\n * properly restores Date objects, Maps, Sets, and other complex types.\n *\n * @template T - The expected type of the stored value (must be Serializable)\n * @param key - The storage key to retrieve\n * @returns Promise resolving to the stored value or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get<T extends Serializable>(key: string): Promise<T | null>;\n\n /**\n * Stores a value in persistent storage.\n *\n * The value will be serialized using SuperJSON and stored persistently.\n * Any existing value at the same key will be overwritten.\n *\n * SuperJSON automatically handles Date objects, Maps, Sets, undefined values,\n * and other complex types that standard JSON doesn't support.\n *\n * @template T - The type of value being stored (must be Serializable)\n * @param key - The storage key to use\n * @param value - The value to store (must be SuperJSON-serializable)\n * @returns Promise that resolves when the value is stored\n *\n * @example\n * ```typescript\n * // Date objects are preserved\n * await this.set('sync_state', {\n * lastSync: new Date(),\n * minDate: new Date(2024, 0, 1)\n * });\n *\n * // undefined is now supported\n * await this.set('data', { name: 'test', optional: undefined }); // ✅ Works\n *\n * // Arrays with undefined are supported\n * await this.set('items', [1, undefined, 3]); // ✅ Works\n * await this.set('items', [1, null, 3]); // ✅ Also works\n *\n * // Maps and Sets are supported\n * await this.set('mapping', new Map([['key', 'value']])); // ✅ Works\n * await this.set('tags', new Set(['tag1', 'tag2'])); // ✅ Works\n *\n * // Functions are NOT supported - use callback tokens instead\n * const token = await this.callback(this.myFunction);\n * await this.set('callback_ref', token); // ✅ Use callback token\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract set<T extends Serializable>(key: string, value: T): Promise<void>;\n\n /**\n * Removes a specific key from storage.\n *\n * After this operation, get() calls for this key will return null.\n * No error is thrown if the key doesn't exist.\n *\n * @param key - The storage key to remove\n * @returns Promise that resolves when the key is removed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract clear(key: string): Promise<void>;\n\n /**\n * Removes all keys from this storage instance.\n *\n * This operation clears all data stored by this twist/tool instance\n * but does not affect storage for other twists or tools.\n *\n * @returns Promise that resolves when all keys are removed\n */\n abstract clearAll(): Promise<void>;\n}\n";
|
|
8
8
|
//# sourceMappingURL=store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,w7JAAw7J,CAAC"}
|
|
@@ -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
|
|
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";
|
|
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,
|
|
1
|
+
{"version":3,"file":"tasks.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,gqHAAgqH;AAA/qH,wBAAgrH"}
|
|
@@ -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
|
|
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";
|
|
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,
|
|
1
|
+
{"version":3,"file":"tasks.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/tasks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,gqHAAgqH,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. **Track external items using generated UUIDs** - Store mappings between external IDs and Plot UUIDs for deduplication\n4. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `doneAt`, use `Event` only for items with `start`/`end`\n\n### Decision Tree\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\nPattern for syncing external data - demonstrates adding Notes to existing Activities:\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 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\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `\uD83D\uDCC5 ${calendar.name}${calendar.primary ? \" (Primary)\" : \"\"}`,\n type: ActivityLinkType.callback,\n token: token,\n });\n }\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Which calendars would you like to connect?\",\n 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 (create activities with Notes)\n for (const item of result.items) {\n // Check if already synced\n const mappingKey = `item_mapping:${resourceId}:${item.id}`;\n const existingId = await this.get<Uuid>(mappingKey);\n\n if (!existingId) {\n // New item - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n await this.tools.plot.createActivity({\n id: activityId,\n type: ActivityType.Note,\n title: item.title,\n notes: [{ id: Uuid.Generate(), 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 `doneAt`, and `Event` for items with `start`/`end`.\n- **Track external items with UUID mappings** - Generate UUIDs with `Uuid.Generate()` and store mappings (`external_id \u2192 uuid`) for deduplication. Never rely on the `source` field.\n- **Add Notes to existing Activities** - Look up stored UUID 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 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";
|
|
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
|
|
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"}
|
|
@@ -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. **Track external items using generated UUIDs** - Store mappings between external IDs and Plot UUIDs for deduplication\n4. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `doneAt`, use `Event` only for items with `start`/`end`\n\n### Decision Tree\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\nPattern for syncing external data - demonstrates adding Notes to existing Activities:\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 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\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `📅 ${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 (create activities with Notes)\n for (const item of result.items) {\n // Check if already synced\n const mappingKey = `item_mapping:${resourceId}:${item.id}`;\n const existingId = await this.get<Uuid>(mappingKey);\n\n if (!existingId) {\n // New item - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n await this.tools.plot.createActivity({\n id: activityId,\n type: ActivityType.Note,\n title: item.title,\n notes: [{ id: Uuid.Generate(), 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 `doneAt`, and `Event` for items with `start`/`end`.\n- **Track external items with UUID mappings** - Generate UUIDs with `Uuid.Generate()` and store mappings (`external_id → uuid`) for deduplication. Never rely on the `source` field.\n- **Add Notes to existing Activities** - Look up stored UUID 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 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";
|
|
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,
|
|
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"}
|
package/dist/llm-docs/twist.d.ts
CHANGED
|
@@ -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 { type Priority } from \"./plot\";\nimport { type ITool } from \"./tool\";\nimport type { Callback } from \"./tools/callbacks\";\nimport type { InferTools, ToolBuilder, ToolShed } from \"./utils/types\";\n\n/**\n * Base class for all twists.\n *\n * Twists are activated in a Plot priority and have access to that priority and all\n * its descendants.\n *\n * Override build() to declare tool dependencies and lifecycle methods to handle events.\n *\n * @example\n * ```typescript\n * class FlatteringTwist extends Twist<FlatteringTwist> {\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * };\n * }\n *\n * async activate(priority: Pick<Priority, \"id\">) {\n * // Initialize twist for the given priority\n * await this.tools.plot.createActivity({\n * type: ActivityType.Note,\n * note: \"Hello, good looking!\",\n * });\n * }\n * }\n * ```\n */\nexport abstract class Twist<TSelf> {\n constructor(protected id:
|
|
7
|
+
declare const _default: "import { type Priority, Uuid } from \"./plot\";\nimport { type ITool } from \"./tool\";\nimport type { Callback } from \"./tools/callbacks\";\nimport type { InferTools, ToolBuilder, ToolShed } from \"./utils/types\";\n\n/**\n * Base class for all twists.\n *\n * Twists are activated in a Plot priority and have access to that priority and all\n * its descendants.\n *\n * Override build() to declare tool dependencies and lifecycle methods to handle events.\n *\n * @example\n * ```typescript\n * class FlatteringTwist extends Twist<FlatteringTwist> {\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * };\n * }\n *\n * async activate(priority: Pick<Priority, \"id\">) {\n * // Initialize twist for the given priority\n * await this.tools.plot.createActivity({\n * type: ActivityType.Note,\n * note: \"Hello, good looking!\",\n * });\n * }\n * }\n * ```\n */\nexport abstract class Twist<TSelf> {\n constructor(protected id: Uuid, private toolShed: ToolShed) {}\n\n /**\n * Gets the initialized tools for this twist.\n * @throws Error if called before initialization is complete\n */\n protected get tools(): InferTools<TSelf> {\n return this.toolShed.getTools<InferTools<TSelf>>();\n }\n\n /**\n * Declares tool dependencies for this twist.\n * Return an object mapping tool names to build() promises.\n *\n * @param build - The build function to use for declaring dependencies\n * @returns Object mapping tool names to tool promises\n *\n * @example\n * ```typescript\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * calendar: build(GoogleCalendar, { apiKey: \"...\" }),\n * };\n * }\n * ```\n */\n abstract build(build: ToolBuilder): Record<string, Promise<ITool>>;\n\n /**\n * Creates a persistent callback to a method on this twist.\n *\n * ExtraArgs are strongly typed to match the method's signature after the first argument.\n *\n * @param fn - The method to callback\n * @param extraArgs - Additional arguments to pass (type-checked, must be serializable)\n * @returns Promise resolving to a persistent callback token\n *\n * @example\n * ```typescript\n * const callback = await this.callback(this.onWebhook, \"calendar\", 123);\n * ```\n */\n protected async callback(\n fn: Function,\n ...extraArgs: any[]\n ): Promise<Callback> {\n return this.tools.callbacks.create(fn as any, ...extraArgs);\n }\n\n /**\n * Deletes a specific callback by its token.\n *\n * @param token - The callback token to delete\n * @returns Promise that resolves when the callback is deleted\n */\n protected async deleteCallback(token: Callback): Promise<void> {\n return this.tools.callbacks.delete(token);\n }\n\n /**\n * Deletes all callbacks for this twist.\n *\n * @returns Promise that resolves when all callbacks are deleted\n */\n protected async deleteAllCallbacks(): Promise<void> {\n return this.tools.callbacks.deleteAll();\n }\n\n /**\n * Executes a callback by its token.\n *\n * @param token - The callback token to execute\n * @param args - Optional arguments to pass to the callback\n * @returns Promise resolving to the callback result\n */\n protected async run(token: Callback, ...args: []): Promise<any> {\n return this.tools.callbacks.run(token, ...args);\n }\n\n /**\n * Retrieves a value from persistent storage by key.\n *\n * Values are automatically deserialized using SuperJSON, which\n * properly restores Date objects, Maps, Sets, and other complex types.\n *\n * @template T - The expected type of the stored value (must be Serializable)\n * @param key - The storage key to retrieve\n * @returns Promise resolving to the stored value or null\n */\n protected async get<T extends import(\"./index\").Serializable>(\n key: string\n ): Promise<T | null> {\n return this.tools.store.get(key);\n }\n\n /**\n * Stores a value in persistent storage.\n *\n * The value will be serialized using SuperJSON and stored persistently.\n * SuperJSON automatically handles Date objects, Maps, Sets, undefined values,\n * and other complex types that standard JSON doesn't support.\n *\n * **Important**: Functions and Symbols cannot be stored.\n * **For function references**: Use callbacks instead of storing functions directly.\n *\n * @example\n * ```typescript\n * // \u2705 Date objects are preserved\n * await this.set(\"sync_state\", {\n * lastSync: new Date(),\n * minDate: new Date(2024, 0, 1)\n * });\n *\n * // \u2705 undefined is now supported\n * await this.set(\"data\", { name: \"test\", optional: undefined });\n *\n * // \u274C WRONG: Cannot store functions directly\n * await this.set(\"handler\", this.myHandler);\n *\n * // \u2705 CORRECT: Create a callback token first\n * const token = await this.callback(this.myHandler, \"arg1\", \"arg2\");\n * await this.set(\"handler_token\", token);\n *\n * // Later, execute the callback\n * const token = await this.get<string>(\"handler_token\");\n * await this.run(token, args);\n * ```\n *\n * @template T - The type of value being stored (must be Serializable)\n * @param key - The storage key to use\n * @param value - The value to store (must be SuperJSON-serializable)\n * @returns Promise that resolves when the value is stored\n */\n protected async set<T extends import(\"./index\").Serializable>(\n key: string,\n value: T\n ): Promise<void> {\n return this.tools.store.set(key, value);\n }\n\n /**\n * Removes a specific key from persistent storage.\n *\n * @param key - The storage key to remove\n * @returns Promise that resolves when the key is removed\n */\n protected async clear(key: string): Promise<void> {\n return this.tools.store.clear(key);\n }\n\n /**\n * Removes all keys from this twist's storage.\n *\n * @returns Promise that resolves when all keys are removed\n */\n protected async clearAll(): Promise<void> {\n return this.tools.store.clearAll();\n }\n\n /**\n * Queues a callback to execute in a separate worker context.\n *\n * @param callback - The callback token 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 protected async runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void> {\n return this.tools.tasks.runTask(callback, options);\n }\n\n /**\n * Cancels a previously scheduled execution.\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 protected async cancelTask(token: string): Promise<void> {\n return this.tools.tasks.cancelTask(token);\n }\n\n /**\n * Cancels all scheduled executions for this twist.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n protected async cancelAllTasks(): Promise<void> {\n return this.tools.tasks.cancelAllTasks();\n }\n\n /**\n * Called when the twist is activated for a specific priority.\n *\n * This method should contain initialization logic such as setting up\n * initial activities, configuring webhooks, or establishing external connections.\n *\n * @param priority - The priority context containing the priority ID\n * @returns Promise that resolves when activation is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n activate(priority: Pick<Priority, \"id\">): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a new version of the twist is deployed to an existing priority.\n *\n * This method should contain migration logic for updating old data structures\n * or setting up new resources that weren't needed by the previous version.\n * It is called with the new version for each active priorityTwist.\n *\n * @returns Promise that resolves when upgrade is complete\n */\n upgrade(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when the twist is removed from a priority.\n *\n * This method should contain cleanup logic such as removing webhooks,\n * cleaning up external resources, or performing final data operations.\n *\n * @returns Promise that resolves when deactivation is complete\n */\n deactivate(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Waits for tool initialization to complete.\n * Called automatically by the entrypoint before lifecycle methods.\n * @internal\n */\n async waitForReady(): Promise<void> {\n await this.toolShed.waitForReady();\n }\n}\n";
|
|
8
8
|
export default _default;
|
|
9
9
|
//# sourceMappingURL=twist.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"twist.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,
|
|
1
|
+
{"version":3,"file":"twist.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,swRAAkvR;AAAjwR,wBAAkwR"}
|
package/dist/llm-docs/twist.js
CHANGED
|
@@ -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 { type Priority } from \"./plot\";\nimport { type ITool } from \"./tool\";\nimport type { Callback } from \"./tools/callbacks\";\nimport type { InferTools, ToolBuilder, ToolShed } from \"./utils/types\";\n\n/**\n * Base class for all twists.\n *\n * Twists are activated in a Plot priority and have access to that priority and all\n * its descendants.\n *\n * Override build() to declare tool dependencies and lifecycle methods to handle events.\n *\n * @example\n * ```typescript\n * class FlatteringTwist extends Twist<FlatteringTwist> {\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * };\n * }\n *\n * async activate(priority: Pick<Priority, \"id\">) {\n * // Initialize twist for the given priority\n * await this.tools.plot.createActivity({\n * type: ActivityType.Note,\n * note: \"Hello, good looking!\",\n * });\n * }\n * }\n * ```\n */\nexport abstract class Twist<TSelf> {\n constructor(protected id:
|
|
7
|
+
export default "import { type Priority, Uuid } from \"./plot\";\nimport { type ITool } from \"./tool\";\nimport type { Callback } from \"./tools/callbacks\";\nimport type { InferTools, ToolBuilder, ToolShed } from \"./utils/types\";\n\n/**\n * Base class for all twists.\n *\n * Twists are activated in a Plot priority and have access to that priority and all\n * its descendants.\n *\n * Override build() to declare tool dependencies and lifecycle methods to handle events.\n *\n * @example\n * ```typescript\n * class FlatteringTwist extends Twist<FlatteringTwist> {\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * };\n * }\n *\n * async activate(priority: Pick<Priority, \"id\">) {\n * // Initialize twist for the given priority\n * await this.tools.plot.createActivity({\n * type: ActivityType.Note,\n * note: \"Hello, good looking!\",\n * });\n * }\n * }\n * ```\n */\nexport abstract class Twist<TSelf> {\n constructor(protected id: Uuid, private toolShed: ToolShed) {}\n\n /**\n * Gets the initialized tools for this twist.\n * @throws Error if called before initialization is complete\n */\n protected get tools(): InferTools<TSelf> {\n return this.toolShed.getTools<InferTools<TSelf>>();\n }\n\n /**\n * Declares tool dependencies for this twist.\n * Return an object mapping tool names to build() promises.\n *\n * @param build - The build function to use for declaring dependencies\n * @returns Object mapping tool names to tool promises\n *\n * @example\n * ```typescript\n * build(build: ToolBuilder) {\n * return {\n * plot: build(Plot),\n * calendar: build(GoogleCalendar, { apiKey: \"...\" }),\n * };\n * }\n * ```\n */\n abstract build(build: ToolBuilder): Record<string, Promise<ITool>>;\n\n /**\n * Creates a persistent callback to a method on this twist.\n *\n * ExtraArgs are strongly typed to match the method's signature after the first argument.\n *\n * @param fn - The method to callback\n * @param extraArgs - Additional arguments to pass (type-checked, must be serializable)\n * @returns Promise resolving to a persistent callback token\n *\n * @example\n * ```typescript\n * const callback = await this.callback(this.onWebhook, \"calendar\", 123);\n * ```\n */\n protected async callback(\n fn: Function,\n ...extraArgs: any[]\n ): Promise<Callback> {\n return this.tools.callbacks.create(fn as any, ...extraArgs);\n }\n\n /**\n * Deletes a specific callback by its token.\n *\n * @param token - The callback token to delete\n * @returns Promise that resolves when the callback is deleted\n */\n protected async deleteCallback(token: Callback): Promise<void> {\n return this.tools.callbacks.delete(token);\n }\n\n /**\n * Deletes all callbacks for this twist.\n *\n * @returns Promise that resolves when all callbacks are deleted\n */\n protected async deleteAllCallbacks(): Promise<void> {\n return this.tools.callbacks.deleteAll();\n }\n\n /**\n * Executes a callback by its token.\n *\n * @param token - The callback token to execute\n * @param args - Optional arguments to pass to the callback\n * @returns Promise resolving to the callback result\n */\n protected async run(token: Callback, ...args: []): Promise<any> {\n return this.tools.callbacks.run(token, ...args);\n }\n\n /**\n * Retrieves a value from persistent storage by key.\n *\n * Values are automatically deserialized using SuperJSON, which\n * properly restores Date objects, Maps, Sets, and other complex types.\n *\n * @template T - The expected type of the stored value (must be Serializable)\n * @param key - The storage key to retrieve\n * @returns Promise resolving to the stored value or null\n */\n protected async get<T extends import(\"./index\").Serializable>(\n key: string\n ): Promise<T | null> {\n return this.tools.store.get(key);\n }\n\n /**\n * Stores a value in persistent storage.\n *\n * The value will be serialized using SuperJSON and stored persistently.\n * SuperJSON automatically handles Date objects, Maps, Sets, undefined values,\n * and other complex types that standard JSON doesn't support.\n *\n * **Important**: Functions and Symbols cannot be stored.\n * **For function references**: Use callbacks instead of storing functions directly.\n *\n * @example\n * ```typescript\n * // ✅ Date objects are preserved\n * await this.set(\"sync_state\", {\n * lastSync: new Date(),\n * minDate: new Date(2024, 0, 1)\n * });\n *\n * // ✅ undefined is now supported\n * await this.set(\"data\", { name: \"test\", optional: undefined });\n *\n * // ❌ WRONG: Cannot store functions directly\n * await this.set(\"handler\", this.myHandler);\n *\n * // ✅ CORRECT: Create a callback token first\n * const token = await this.callback(this.myHandler, \"arg1\", \"arg2\");\n * await this.set(\"handler_token\", token);\n *\n * // Later, execute the callback\n * const token = await this.get<string>(\"handler_token\");\n * await this.run(token, args);\n * ```\n *\n * @template T - The type of value being stored (must be Serializable)\n * @param key - The storage key to use\n * @param value - The value to store (must be SuperJSON-serializable)\n * @returns Promise that resolves when the value is stored\n */\n protected async set<T extends import(\"./index\").Serializable>(\n key: string,\n value: T\n ): Promise<void> {\n return this.tools.store.set(key, value);\n }\n\n /**\n * Removes a specific key from persistent storage.\n *\n * @param key - The storage key to remove\n * @returns Promise that resolves when the key is removed\n */\n protected async clear(key: string): Promise<void> {\n return this.tools.store.clear(key);\n }\n\n /**\n * Removes all keys from this twist's storage.\n *\n * @returns Promise that resolves when all keys are removed\n */\n protected async clearAll(): Promise<void> {\n return this.tools.store.clearAll();\n }\n\n /**\n * Queues a callback to execute in a separate worker context.\n *\n * @param callback - The callback token 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 protected async runTask(\n callback: Callback,\n options?: { runAt?: Date }\n ): Promise<string | void> {\n return this.tools.tasks.runTask(callback, options);\n }\n\n /**\n * Cancels a previously scheduled execution.\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 protected async cancelTask(token: string): Promise<void> {\n return this.tools.tasks.cancelTask(token);\n }\n\n /**\n * Cancels all scheduled executions for this twist.\n *\n * @returns Promise that resolves when all cancellations are processed\n */\n protected async cancelAllTasks(): Promise<void> {\n return this.tools.tasks.cancelAllTasks();\n }\n\n /**\n * Called when the twist is activated for a specific priority.\n *\n * This method should contain initialization logic such as setting up\n * initial activities, configuring webhooks, or establishing external connections.\n *\n * @param priority - The priority context containing the priority ID\n * @returns Promise that resolves when activation is complete\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n activate(priority: Pick<Priority, \"id\">): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a new version of the twist is deployed to an existing priority.\n *\n * This method should contain migration logic for updating old data structures\n * or setting up new resources that weren't needed by the previous version.\n * It is called with the new version for each active priorityTwist.\n *\n * @returns Promise that resolves when upgrade is complete\n */\n upgrade(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when the twist is removed from a priority.\n *\n * This method should contain cleanup logic such as removing webhooks,\n * cleaning up external resources, or performing final data operations.\n *\n * @returns Promise that resolves when deactivation is complete\n */\n deactivate(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Waits for tool initialization to complete.\n * Called automatically by the entrypoint before lifecycle methods.\n * @internal\n */\n async waitForReady(): Promise<void> {\n await this.toolShed.waitForReady();\n }\n}\n";
|
|
8
8
|
//# sourceMappingURL=twist.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"twist.js","sourceRoot":"","sources":["../../src/llm-docs/twist.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,
|
|
1
|
+
{"version":3,"file":"twist.js","sourceRoot":"","sources":["../../src/llm-docs/twist.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,kvRAAkvR,CAAC"}
|