@plotday/twister 0.35.0 → 0.36.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/bin/templates/AGENTS.template.md +187 -182
- package/cli/templates/AGENTS.template.md +187 -182
- 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/index.Options.html +10 -0
- package/dist/docs/classes/tool.ITool.html +1 -1
- package/dist/docs/classes/tools_integrations.Integrations.html +4 -4
- package/dist/docs/classes/tools_network.Network.html +1 -1
- package/dist/docs/classes/tools_plot.Plot.html +1 -1
- package/dist/docs/classes/tools_store.Store.html +1 -1
- package/dist/docs/classes/tools_tasks.Tasks.html +1 -1
- package/dist/docs/enums/tools_integrations.AuthProvider.html +11 -11
- package/dist/docs/hierarchy.html +1 -1
- package/dist/docs/interfaces/utils_types.ToolShed.html +5 -5
- package/dist/docs/modules/index.html +1 -1
- package/dist/docs/types/index.BooleanDef.html +7 -0
- package/dist/docs/types/index.NumberDef.html +9 -0
- package/dist/docs/types/index.OptionDef.html +2 -0
- package/dist/docs/types/index.OptionsSchema.html +3 -0
- package/dist/docs/types/index.ResolvedOptions.html +4 -0
- package/dist/docs/types/index.SelectDef.html +8 -0
- package/dist/docs/types/index.TextDef.html +8 -0
- 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_integrations.IntegrationOptions.html +2 -2
- package/dist/docs/types/tools_integrations.IntegrationProviderConfig.html +6 -6
- package/dist/docs/types/tools_integrations.Syncable.html +4 -2
- package/dist/docs/types/utils_types.BuiltInTools.html +2 -2
- 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 +1 -1
- package/dist/docs/types/utils_types.PromiseValues.html +1 -1
- package/dist/docs/types/utils_types.ToolBuilder.html +2 -2
- 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/index.d.ts.map +1 -1
- package/dist/llm-docs/index.js +2 -0
- package/dist/llm-docs/index.js.map +1 -1
- package/dist/llm-docs/options.d.ts +9 -0
- package/dist/llm-docs/options.d.ts.map +1 -0
- package/dist/llm-docs/options.js +8 -0
- package/dist/llm-docs/options.js.map +1 -0
- package/dist/llm-docs/tools/integrations.d.ts +1 -1
- package/dist/llm-docs/tools/integrations.d.ts.map +1 -1
- package/dist/llm-docs/tools/integrations.js +1 -1
- package/dist/llm-docs/tools/integrations.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/options.d.ts +104 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/options.js +40 -0
- package/dist/options.js.map +1 -0
- package/dist/tools/integrations.d.ts +2 -0
- package/dist/tools/integrations.d.ts.map +1 -1
- package/dist/tools/integrations.js.map +1 -1
- package/dist/twist-guide.d.ts +1 -1
- package/dist/twist-guide.d.ts.map +1 -1
- package/dist/utils/types.d.ts +5 -1
- package/dist/utils/types.d.ts.map +1 -1
- package/package.json +6 -1
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/llm-docs/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/llm-docs/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoBH,QAAA,MAAM,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAkBnC,CAAC;AAEF,eAAe,OAAO,CAAC"}
|
package/dist/llm-docs/index.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Provides a mapping of Twister import paths to their source code documentation.
|
|
8
8
|
*/
|
|
9
|
+
import options from "./options.js";
|
|
9
10
|
import plot from "./plot.js";
|
|
10
11
|
import tag from "./tag.js";
|
|
11
12
|
import tool from "./tool.js";
|
|
@@ -23,6 +24,7 @@ import tools_store from "./tools/store.js";
|
|
|
23
24
|
import tools_tasks from "./tools/tasks.js";
|
|
24
25
|
import tools_twists from "./tools/twists.js";
|
|
25
26
|
const llmDocs = {
|
|
27
|
+
"@plotday/twister/options": options,
|
|
26
28
|
"@plotday/twister/plot": plot,
|
|
27
29
|
"@plotday/twister/tag": tag,
|
|
28
30
|
"@plotday/twister/tool": tool,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/llm-docs/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,kBAAkB,MAAM,yBAAyB,CAAC;AACzD,OAAO,aAAa,MAAM,oBAAoB,CAAC;AAC/C,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,YAAY,MAAM,mBAAmB,CAAC;AAE7C,MAAM,OAAO,GAA2B;IACtC,uBAAuB,EAAE,IAAI;IAC7B,sBAAsB,EAAE,GAAG;IAC3B,uBAAuB,EAAE,IAAI;IAC7B,wBAAwB,EAAE,KAAK;IAC/B,kCAAkC,EAAE,eAAe;IACnD,mCAAmC,EAAE,gBAAgB;IACrD,mCAAmC,EAAE,gBAAgB;IACrD,kCAAkC,EAAE,eAAe;IACnD,2BAA2B,EAAE,QAAQ;IACrC,kCAAkC,EAAE,eAAe;IACnD,qCAAqC,EAAE,kBAAkB;IACzD,gCAAgC,EAAE,aAAa;IAC/C,6BAA6B,EAAE,UAAU;IACzC,8BAA8B,EAAE,WAAW;IAC3C,8BAA8B,EAAE,WAAW;IAC3C,+BAA+B,EAAE,YAAY;CAC9C,CAAC;AAEF,eAAe,OAAO,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/llm-docs/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,eAAe,MAAM,sBAAsB,CAAC;AACnD,OAAO,kBAAkB,MAAM,yBAAyB,CAAC;AACzD,OAAO,aAAa,MAAM,oBAAoB,CAAC;AAC/C,OAAO,UAAU,MAAM,iBAAiB,CAAC;AACzC,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,WAAW,MAAM,kBAAkB,CAAC;AAC3C,OAAO,YAAY,MAAM,mBAAmB,CAAC;AAE7C,MAAM,OAAO,GAA2B;IACtC,0BAA0B,EAAE,OAAO;IACnC,uBAAuB,EAAE,IAAI;IAC7B,sBAAsB,EAAE,GAAG;IAC3B,uBAAuB,EAAE,IAAI;IAC7B,wBAAwB,EAAE,KAAK;IAC/B,kCAAkC,EAAE,eAAe;IACnD,mCAAmC,EAAE,gBAAgB;IACrD,mCAAmC,EAAE,gBAAgB;IACrD,kCAAkC,EAAE,eAAe;IACnD,2BAA2B,EAAE,QAAQ;IACrC,kCAAkC,EAAE,eAAe;IACnD,qCAAqC,EAAE,kBAAkB;IACzD,gCAAgC,EAAE,aAAa;IAC/C,6BAA6B,EAAE,UAAU;IACzC,8BAA8B,EAAE,WAAW;IAC3C,8BAA8B,EAAE,WAAW;IAC3C,+BAA+B,EAAE,YAAY;CAC9C,CAAC;AAEF,eAAe,OAAO,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated LLM documentation for @plotday/twister/options
|
|
3
|
+
*
|
|
4
|
+
* This file is auto-generated during build. Do not edit manually.
|
|
5
|
+
* Generated from: prebuild.ts
|
|
6
|
+
*/
|
|
7
|
+
declare const _default: "import { ITool } from \"./tool\";\n\n/**\n * A select option definition for twist configuration.\n * Renders as a dropdown in the Flutter UI.\n */\nexport type SelectDef = {\n type: \"select\";\n label: string;\n description?: string;\n choices: ReadonlyArray<{ value: string; label: string }>;\n default: string;\n};\n\n/**\n * A text input option definition for twist configuration.\n * Renders as a text field in the Flutter UI.\n */\nexport type TextDef = {\n type: \"text\";\n label: string;\n description?: string;\n default: string;\n placeholder?: string;\n};\n\n/**\n * A number input option definition for twist configuration.\n * Renders as a number field in the Flutter UI.\n */\nexport type NumberDef = {\n type: \"number\";\n label: string;\n description?: string;\n default: number;\n min?: number;\n max?: number;\n};\n\n/**\n * A boolean toggle option definition for twist configuration.\n * Renders as a switch in the Flutter UI.\n */\nexport type BooleanDef = {\n type: \"boolean\";\n label: string;\n description?: string;\n default: boolean;\n};\n\n/**\n * Union of all option definition types.\n */\nexport type OptionDef = SelectDef | TextDef | NumberDef | BooleanDef;\n\n/**\n * Schema defining all configurable options for a twist.\n * Each key maps to an option definition that describes its type, label, and default value.\n */\nexport type OptionsSchema = Record<string, OptionDef>;\n\n/**\n * Infers the resolved value types from an options schema.\n * Boolean options resolve to `boolean`, number options to `number`,\n * and select/text options to `string`.\n */\nexport type ResolvedOptions<T extends OptionsSchema> = {\n [K in keyof T]: T[K] extends BooleanDef\n ? boolean\n : T[K] extends NumberDef\n ? number\n : string;\n};\n\n/**\n * Built-in marker class for twist configuration options.\n *\n * Declare options in your twist's `build()` method to expose configurable\n * settings to users. The schema is introspected at deploy time and stored\n * alongside permissions. At runtime, user values are merged with defaults.\n *\n * @example\n * ```typescript\n * import { Options, type OptionsSchema } from \"@plotday/twister/options\";\n *\n * export default class MyTwist extends Twist<MyTwist> {\n * build(build: ToolBuilder) {\n * return {\n * options: build(Options, {\n * model: {\n * type: 'select',\n * label: 'AI Model',\n * choices: [\n * { value: 'fast', label: 'Fast' },\n * { value: 'smart', label: 'Smart' },\n * ],\n * default: 'fast',\n * },\n * }),\n * // ... other tools\n * };\n * }\n *\n * async respond(note: Note) {\n * const model = this.tools.options.model; // typed as string\n * }\n * }\n * ```\n */\nexport abstract class Options extends ITool {\n static readonly toolId = \"Options\";\n}\n";
|
|
8
|
+
export default _default;
|
|
9
|
+
//# sourceMappingURL=options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/llm-docs/options.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,w2FAAw2F;AAAv3F,wBAAw3F"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated LLM documentation for @plotday/twister/options
|
|
3
|
+
*
|
|
4
|
+
* This file is auto-generated during build. Do not edit manually.
|
|
5
|
+
* Generated from: prebuild.ts
|
|
6
|
+
*/
|
|
7
|
+
export default "import { ITool } from \"./tool\";\n\n/**\n * A select option definition for twist configuration.\n * Renders as a dropdown in the Flutter UI.\n */\nexport type SelectDef = {\n type: \"select\";\n label: string;\n description?: string;\n choices: ReadonlyArray<{ value: string; label: string }>;\n default: string;\n};\n\n/**\n * A text input option definition for twist configuration.\n * Renders as a text field in the Flutter UI.\n */\nexport type TextDef = {\n type: \"text\";\n label: string;\n description?: string;\n default: string;\n placeholder?: string;\n};\n\n/**\n * A number input option definition for twist configuration.\n * Renders as a number field in the Flutter UI.\n */\nexport type NumberDef = {\n type: \"number\";\n label: string;\n description?: string;\n default: number;\n min?: number;\n max?: number;\n};\n\n/**\n * A boolean toggle option definition for twist configuration.\n * Renders as a switch in the Flutter UI.\n */\nexport type BooleanDef = {\n type: \"boolean\";\n label: string;\n description?: string;\n default: boolean;\n};\n\n/**\n * Union of all option definition types.\n */\nexport type OptionDef = SelectDef | TextDef | NumberDef | BooleanDef;\n\n/**\n * Schema defining all configurable options for a twist.\n * Each key maps to an option definition that describes its type, label, and default value.\n */\nexport type OptionsSchema = Record<string, OptionDef>;\n\n/**\n * Infers the resolved value types from an options schema.\n * Boolean options resolve to `boolean`, number options to `number`,\n * and select/text options to `string`.\n */\nexport type ResolvedOptions<T extends OptionsSchema> = {\n [K in keyof T]: T[K] extends BooleanDef\n ? boolean\n : T[K] extends NumberDef\n ? number\n : string;\n};\n\n/**\n * Built-in marker class for twist configuration options.\n *\n * Declare options in your twist's `build()` method to expose configurable\n * settings to users. The schema is introspected at deploy time and stored\n * alongside permissions. At runtime, user values are merged with defaults.\n *\n * @example\n * ```typescript\n * import { Options, type OptionsSchema } from \"@plotday/twister/options\";\n *\n * export default class MyTwist extends Twist<MyTwist> {\n * build(build: ToolBuilder) {\n * return {\n * options: build(Options, {\n * model: {\n * type: 'select',\n * label: 'AI Model',\n * choices: [\n * { value: 'fast', label: 'Fast' },\n * { value: 'smart', label: 'Smart' },\n * ],\n * default: 'fast',\n * },\n * }),\n * // ... other tools\n * };\n * }\n *\n * async respond(note: Note) {\n * const model = this.tools.options.model; // typed as string\n * }\n * }\n * ```\n */\nexport abstract class Options extends ITool {\n static readonly toolId = \"Options\";\n}\n";
|
|
8
|
+
//# sourceMappingURL=options.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/llm-docs/options.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,w2FAAw2F,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 { type Actor, type ActorId, ITool, Serializable } from \"..\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getSyncables() and managed by users in the twist setup/edit modal.\n */\nexport type Syncable = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n};\n\n/**\n * Configuration for an OAuth provider in a tool's build options.\n * Declares the provider, scopes, and lifecycle callbacks.\n */\nexport type IntegrationProviderConfig = {\n /** The OAuth provider */\n provider: AuthProvider;\n /** OAuth scopes to request */\n scopes: string[];\n /** Returns available syncables for the authorized actor. Must not use Plot tool. */\n getSyncables: (auth: Authorization, token: AuthToken) => Promise<Syncable[]>;\n /** Called when a syncable resource is enabled for syncing */\n onSyncEnabled: (syncable: Syncable) => Promise<void>;\n /** Called when a syncable resource is disabled */\n onSyncDisabled: (syncable: Syncable) => Promise<void>;\n};\n\n/**\n * Options passed to Integrations in the build() method.\n */\nexport type IntegrationOptions = {\n /** Provider configurations with lifecycle callbacks */\n providers: IntegrationProviderConfig[];\n};\n\n/**\n * Built-in tool for managing OAuth authentication and syncable resources.\n *\n * The redesigned Integrations tool:\n * 1. Declares providers/scopes in build options with lifecycle callbacks\n * 2. Manages syncable resources (calendars, projects, etc.) per actor\n * 3. Returns tokens for the user who enabled sync on a syncable\n * 4. Supports per-actor auth via actAs() for write-back operations\n *\n * Auth and syncable management is handled in the twist edit modal in Flutter,\n * removing the need for tools to create auth activities or selection UIs.\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool<CalendarTool> {\n * static readonly PROVIDER = AuthProvider.Google;\n * static readonly SCOPES = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations, {\n * providers: [{\n * provider: AuthProvider.Google,\n * scopes: CalendarTool.SCOPES,\n * getSyncables: this.getSyncables,\n * onSyncEnabled: this.onSyncEnabled,\n * onSyncDisabled: this.onSyncDisabled,\n * }]\n * }),\n * };\n * }\n *\n * async getSyncables(auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a syncable resource.\n *\n * Returns the token of the user who enabled sync on the given syncable.\n * If the syncable is not enabled or the token is expired/invalid, returns null.\n *\n * @param provider - The OAuth provider\n * @param syncableId - The syncable resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, syncableId: string): Promise<AuthToken | null>;\n\n /**\n * Execute a callback as a specific actor, requesting auth if needed.\n *\n * If the actor has a valid token, calls the callback immediately with it.\n * If the actor has no token, creates a private auth note in the specified\n * activity prompting them to connect. Once they authorize, this callback fires.\n *\n * @param provider - The OAuth provider\n * @param actorId - The actor to act as\n * @param activityId - The activity to create an auth note in (if needed)\n * @param callback - Function to call with the token\n * @param extraArgs - Additional arguments to pass to the callback\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract actAs<\n TArgs extends Serializable[],\n TCallback extends (token: AuthToken, ...args: TArgs) => any\n >(\n provider: AuthProvider,\n actorId: ActorId,\n activityId: Uuid,\n callback: TCallback,\n ...extraArgs: TArgs\n ): Promise<void>;\n\n}\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
|
|
7
|
+
declare const _default: "import { type Actor, type ActorId, ITool, Serializable } from \"..\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getSyncables() and managed by users in the twist setup/edit modal.\n */\nexport type Syncable = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n /** Optional nested syncable resources (e.g., subfolders) */\n children?: Syncable[];\n};\n\n/**\n * Configuration for an OAuth provider in a tool's build options.\n * Declares the provider, scopes, and lifecycle callbacks.\n */\nexport type IntegrationProviderConfig = {\n /** The OAuth provider */\n provider: AuthProvider;\n /** OAuth scopes to request */\n scopes: string[];\n /** Returns available syncables for the authorized actor. Must not use Plot tool. */\n getSyncables: (auth: Authorization, token: AuthToken) => Promise<Syncable[]>;\n /** Called when a syncable resource is enabled for syncing */\n onSyncEnabled: (syncable: Syncable) => Promise<void>;\n /** Called when a syncable resource is disabled */\n onSyncDisabled: (syncable: Syncable) => Promise<void>;\n};\n\n/**\n * Options passed to Integrations in the build() method.\n */\nexport type IntegrationOptions = {\n /** Provider configurations with lifecycle callbacks */\n providers: IntegrationProviderConfig[];\n};\n\n/**\n * Built-in tool for managing OAuth authentication and syncable resources.\n *\n * The redesigned Integrations tool:\n * 1. Declares providers/scopes in build options with lifecycle callbacks\n * 2. Manages syncable resources (calendars, projects, etc.) per actor\n * 3. Returns tokens for the user who enabled sync on a syncable\n * 4. Supports per-actor auth via actAs() for write-back operations\n *\n * Auth and syncable management is handled in the twist edit modal in Flutter,\n * removing the need for tools to create auth activities or selection UIs.\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool<CalendarTool> {\n * static readonly PROVIDER = AuthProvider.Google;\n * static readonly SCOPES = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations, {\n * providers: [{\n * provider: AuthProvider.Google,\n * scopes: CalendarTool.SCOPES,\n * getSyncables: this.getSyncables,\n * onSyncEnabled: this.onSyncEnabled,\n * onSyncDisabled: this.onSyncDisabled,\n * }]\n * }),\n * };\n * }\n *\n * async getSyncables(auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a syncable resource.\n *\n * Returns the token of the user who enabled sync on the given syncable.\n * If the syncable is not enabled or the token is expired/invalid, returns null.\n *\n * @param provider - The OAuth provider\n * @param syncableId - The syncable resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, syncableId: string): Promise<AuthToken | null>;\n\n /**\n * Execute a callback as a specific actor, requesting auth if needed.\n *\n * If the actor has a valid token, calls the callback immediately with it.\n * If the actor has no token, creates a private auth note in the specified\n * activity prompting them to connect. Once they authorize, this callback fires.\n *\n * @param provider - The OAuth provider\n * @param actorId - The actor to act as\n * @param activityId - The activity to create an auth note in (if needed)\n * @param callback - Function to call with the token\n * @param extraArgs - Additional arguments to pass to the callback\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract actAs<\n TArgs extends Serializable[],\n TCallback extends (token: AuthToken, ...args: TArgs) => any\n >(\n provider: AuthProvider,\n actorId: ActorId,\n activityId: Uuid,\n callback: TCallback,\n ...extraArgs: TArgs\n ): Promise<void>;\n\n}\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
|
|
8
8
|
export default _default;
|
|
9
9
|
//# sourceMappingURL=integrations.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrations.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/integrations.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,
|
|
1
|
+
{"version":3,"file":"integrations.d.ts","sourceRoot":"","sources":["../../../src/llm-docs/tools/integrations.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,o2NAAo2N;AAAn3N,wBAAo3N"}
|
|
@@ -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 Actor, type ActorId, ITool, Serializable } from \"..\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getSyncables() and managed by users in the twist setup/edit modal.\n */\nexport type Syncable = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n};\n\n/**\n * Configuration for an OAuth provider in a tool's build options.\n * Declares the provider, scopes, and lifecycle callbacks.\n */\nexport type IntegrationProviderConfig = {\n /** The OAuth provider */\n provider: AuthProvider;\n /** OAuth scopes to request */\n scopes: string[];\n /** Returns available syncables for the authorized actor. Must not use Plot tool. */\n getSyncables: (auth: Authorization, token: AuthToken) => Promise<Syncable[]>;\n /** Called when a syncable resource is enabled for syncing */\n onSyncEnabled: (syncable: Syncable) => Promise<void>;\n /** Called when a syncable resource is disabled */\n onSyncDisabled: (syncable: Syncable) => Promise<void>;\n};\n\n/**\n * Options passed to Integrations in the build() method.\n */\nexport type IntegrationOptions = {\n /** Provider configurations with lifecycle callbacks */\n providers: IntegrationProviderConfig[];\n};\n\n/**\n * Built-in tool for managing OAuth authentication and syncable resources.\n *\n * The redesigned Integrations tool:\n * 1. Declares providers/scopes in build options with lifecycle callbacks\n * 2. Manages syncable resources (calendars, projects, etc.) per actor\n * 3. Returns tokens for the user who enabled sync on a syncable\n * 4. Supports per-actor auth via actAs() for write-back operations\n *\n * Auth and syncable management is handled in the twist edit modal in Flutter,\n * removing the need for tools to create auth activities or selection UIs.\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool<CalendarTool> {\n * static readonly PROVIDER = AuthProvider.Google;\n * static readonly SCOPES = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations, {\n * providers: [{\n * provider: AuthProvider.Google,\n * scopes: CalendarTool.SCOPES,\n * getSyncables: this.getSyncables,\n * onSyncEnabled: this.onSyncEnabled,\n * onSyncDisabled: this.onSyncDisabled,\n * }]\n * }),\n * };\n * }\n *\n * async getSyncables(auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a syncable resource.\n *\n * Returns the token of the user who enabled sync on the given syncable.\n * If the syncable is not enabled or the token is expired/invalid, returns null.\n *\n * @param provider - The OAuth provider\n * @param syncableId - The syncable resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, syncableId: string): Promise<AuthToken | null>;\n\n /**\n * Execute a callback as a specific actor, requesting auth if needed.\n *\n * If the actor has a valid token, calls the callback immediately with it.\n * If the actor has no token, creates a private auth note in the specified\n * activity prompting them to connect. Once they authorize, this callback fires.\n *\n * @param provider - The OAuth provider\n * @param actorId - The actor to act as\n * @param activityId - The activity to create an auth note in (if needed)\n * @param callback - Function to call with the token\n * @param extraArgs - Additional arguments to pass to the callback\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract actAs<\n TArgs extends Serializable[],\n TCallback extends (token: AuthToken, ...args: TArgs) => any\n >(\n provider: AuthProvider,\n actorId: ActorId,\n activityId: Uuid,\n callback: TCallback,\n ...extraArgs: TArgs\n ): Promise<void>;\n\n}\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
|
|
7
|
+
export default "import { type Actor, type ActorId, ITool, Serializable } from \"..\";\nimport type { Uuid } from \"../utils/uuid\";\n\n/**\n * A resource that can be synced (e.g., a calendar, project, channel).\n * Returned by getSyncables() and managed by users in the twist setup/edit modal.\n */\nexport type Syncable = {\n /** External ID shared across users (e.g., Google calendar ID) */\n id: string;\n /** Display name shown in the UI */\n title: string;\n /** Optional nested syncable resources (e.g., subfolders) */\n children?: Syncable[];\n};\n\n/**\n * Configuration for an OAuth provider in a tool's build options.\n * Declares the provider, scopes, and lifecycle callbacks.\n */\nexport type IntegrationProviderConfig = {\n /** The OAuth provider */\n provider: AuthProvider;\n /** OAuth scopes to request */\n scopes: string[];\n /** Returns available syncables for the authorized actor. Must not use Plot tool. */\n getSyncables: (auth: Authorization, token: AuthToken) => Promise<Syncable[]>;\n /** Called when a syncable resource is enabled for syncing */\n onSyncEnabled: (syncable: Syncable) => Promise<void>;\n /** Called when a syncable resource is disabled */\n onSyncDisabled: (syncable: Syncable) => Promise<void>;\n};\n\n/**\n * Options passed to Integrations in the build() method.\n */\nexport type IntegrationOptions = {\n /** Provider configurations with lifecycle callbacks */\n providers: IntegrationProviderConfig[];\n};\n\n/**\n * Built-in tool for managing OAuth authentication and syncable resources.\n *\n * The redesigned Integrations tool:\n * 1. Declares providers/scopes in build options with lifecycle callbacks\n * 2. Manages syncable resources (calendars, projects, etc.) per actor\n * 3. Returns tokens for the user who enabled sync on a syncable\n * 4. Supports per-actor auth via actAs() for write-back operations\n *\n * Auth and syncable management is handled in the twist edit modal in Flutter,\n * removing the need for tools to create auth activities or selection UIs.\n *\n * @example\n * ```typescript\n * class CalendarTool extends Tool<CalendarTool> {\n * static readonly PROVIDER = AuthProvider.Google;\n * static readonly SCOPES = [\"https://www.googleapis.com/auth/calendar\"];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations, {\n * providers: [{\n * provider: AuthProvider.Google,\n * scopes: CalendarTool.SCOPES,\n * getSyncables: this.getSyncables,\n * onSyncEnabled: this.onSyncEnabled,\n * onSyncDisabled: this.onSyncDisabled,\n * }]\n * }),\n * };\n * }\n *\n * async getSyncables(auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n * const calendars = await this.listCalendars(token);\n * return calendars.map(c => ({ id: c.id, title: c.name }));\n * }\n * }\n * ```\n */\nexport abstract class Integrations extends ITool {\n /**\n * Merge scopes from multiple tools, deduplicating.\n *\n * @param scopeArrays - Arrays of scopes to merge\n * @returns Deduplicated array of scopes\n */\n static MergeScopes(...scopeArrays: string[][]): string[] {\n return Array.from(new Set(scopeArrays.flat()));\n }\n\n /**\n * Retrieves an access token for a syncable resource.\n *\n * Returns the token of the user who enabled sync on the given syncable.\n * If the syncable is not enabled or the token is expired/invalid, returns null.\n *\n * @param provider - The OAuth provider\n * @param syncableId - The syncable resource ID (e.g., calendar ID)\n * @returns Promise resolving to the access token or null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract get(provider: AuthProvider, syncableId: string): Promise<AuthToken | null>;\n\n /**\n * Execute a callback as a specific actor, requesting auth if needed.\n *\n * If the actor has a valid token, calls the callback immediately with it.\n * If the actor has no token, creates a private auth note in the specified\n * activity prompting them to connect. Once they authorize, this callback fires.\n *\n * @param provider - The OAuth provider\n * @param actorId - The actor to act as\n * @param activityId - The activity to create an auth note in (if needed)\n * @param callback - Function to call with the token\n * @param extraArgs - Additional arguments to pass to the callback\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abstract actAs<\n TArgs extends Serializable[],\n TCallback extends (token: AuthToken, ...args: TArgs) => any\n >(\n provider: AuthProvider,\n actorId: ActorId,\n activityId: Uuid,\n callback: TCallback,\n ...extraArgs: TArgs\n ): Promise<void>;\n\n}\n\n/**\n * Enumeration of supported OAuth providers.\n *\n * Each provider has different OAuth endpoints, scopes, and token formats.\n * The Integrations tool handles the provider-specific implementation details.\n */\nexport enum AuthProvider {\n /** Google OAuth provider for Google Workspace services */\n Google = \"google\",\n /** Microsoft OAuth provider for Microsoft 365 services */\n Microsoft = \"microsoft\",\n /** Notion OAuth provider for Notion workspaces */\n Notion = \"notion\",\n /** Slack OAuth provider for Slack workspaces */\n Slack = \"slack\",\n /** Atlassian OAuth provider for Jira and Confluence */\n Atlassian = \"atlassian\",\n /** Linear OAuth provider for Linear workspaces */\n Linear = \"linear\",\n /** Monday.com OAuth provider */\n Monday = \"monday\",\n /** GitHub OAuth provider for GitHub repositories and organizations */\n GitHub = \"github\",\n /** Asana OAuth provider for Asana workspaces */\n Asana = \"asana\",\n /** HubSpot OAuth provider for HubSpot CRM */\n HubSpot = \"hubspot\",\n}\n\n/**\n * Represents a completed authorization from an OAuth flow.\n *\n * Contains the provider, granted scopes, and the actor (contact) that was authorized.\n * Tokens are looked up by (provider, actorId) rather than a random ID.\n */\nexport type Authorization = {\n /** The OAuth provider this authorization is for */\n provider: AuthProvider;\n /** Array of OAuth scopes this authorization covers */\n scopes: string[];\n /** The external account that was authorized (e.g., the Google account) */\n actor: Actor;\n};\n\n/**\n * Represents a stored OAuth authentication token.\n *\n * Contains the actual access token and the scopes it was granted,\n * which may be a subset of the originally requested scopes.\n */\nexport type AuthToken = {\n /** The OAuth access token */\n token: string;\n /** Array of granted OAuth scopes */\n scopes: string[];\n /**\n * Provider-specific metadata as key-value pairs.\n *\n * For Slack (AuthProvider.Slack):\n * - authed_user_id: The authenticated user's Slack ID\n * - bot_user_id: The bot user's Slack ID\n * - team_name: The Slack workspace/team name\n */\n provider?: Record<string, string>;\n};\n";
|
|
8
8
|
//# sourceMappingURL=integrations.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/integrations.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,
|
|
1
|
+
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/llm-docs/tools/integrations.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,o2NAAo2N,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 requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n \u251C\u2500 Has stable URL or ID?\n \u2502 \u2514\u2500 Yes \u2192 Set Activity.source to the canonical URL/ID\n \u2502 Create Activity (Plot handles deduplication automatically)\n \u2502 Use Note.key for different note types:\n \u2502 - \"description\" for main content\n \u2502 - \"metadata\" for status/priority/assignee\n \u2502 - \"comment-{id}\" for individual comments\n \u2502\n \u2514\u2500 No stable identifier OR need multiple Plot activities per external item?\n \u2514\u2500 Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Activity with that UUID\n \u2502 Store mapping: external_id \u2192 activity_uuid\n \u2502\n \u2514\u2500 No (update/reply/comment) \u2192 Look up mapping by external_id\n \u251C\u2500 Found \u2192 Add Note to existing Activity using stored UUID\n \u2514\u2500 Not found \u2192 Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot),\n };\n }\n\n async activate(priority: Pick<Priority, \"id\">) {\n // Called when twist is enabled for a priority\n // Common actions: request auth, create setup activities\n }\n\n async activity(activity: Activity) {\n // Called when an activity is routed to this twist\n // Common actions: process external events, update activities\n }\n}\n```\n\n## Tool System\n\n### Accessing Tools\n\nAll tools are declared in the `build` method:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n toolName: build(ToolClass),\n };\n}\n```\n\nAll `build()` calls must occur in the `build` method as they are used for dependency analysis.\n\nIMPORTANT: HTTP access is restricted to URLs requested via `build(Network, { urls: [url1, url2, ...] })` in the `build` method. Wildcards are supported. Use `build(Network, { urls: ['*'] })` if full access is needed.\n\n### Built-in Tools (Always Available)\n\nFor complete API documentation of built-in tools including all methods, types, and detailed examples, see the TypeScript definitions in your installed package at `node_modules/@plotday/twister/src/tools/*.ts`. Each tool file contains comprehensive JSDoc documentation.\n\n**Quick reference - Available tools:**\n\n- `@plotday/twister/tools/plot` - Core data layer (create/update activities, priorities, contacts)\n- `@plotday/twister/tools/ai` - LLM integration (text generation, structured output, reasoning)\n - Use ModelPreferences to specify `speed` (fast/balanced/capable) and `cost` (low/medium/high)\n- `@plotday/twister/tools/store` - Persistent key-value storage (also via `this.set()`, `this.get()`)\n- `@plotday/twister/tools/tasks` - Queue batched work (also via `this.run()`)\n- `@plotday/twister/tools/callbacks` - Persistent function references (also via `this.callback()`)\n- `@plotday/twister/tools/integrations` - OAuth2 authentication flows\n- `@plotday/twister/tools/network` - HTTP access permissions and webhook management\n- `@plotday/twister/tools/twists` - Manage other Twists\n\n**Critical**: Never use instance variables for state. They are lost after function execution. Always use Store methods.\n\n### External Tools (Add to package.json)\n\nAdd tool dependencies to `package.json`:\n\n```json\n{\n \"dependencies\": {\n \"@plotday/twister\": \"workspace:^\",\n \"@plotday/tool-google-calendar\": \"workspace:^\"\n }\n}\n```\n\n#### Common External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar integration\n- `@plotday/tool-outlook-calendar`: Outlook Calendar integration\n- `@plotday/tool-google-contacts`: Google Contacts integration\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Common patterns:\n\n**Request Authentication:**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const authLink = await this.tools.externalTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\n});\n\nawait this.set(\"setup_activity_id\", activity.id);\n```\n\n### activity(activity: Activity)\n\nCalled when an activity is routed to the twist. Common patterns:\n\n**Create Activities from External Events:**\n\n```typescript\nasync activity(activity: Activity) {\n await this.tools.plot.createActivity(activity);\n}\n```\n\n**Update Based on User Action:**\n\n```typescript\nasync activity(activity: Activity) {\n if (activity.completed) {\n await this.handleCompletion(activity);\n }\n}\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.url,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool)\nconst token = await this.callback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n token: token,\n};\n\n// Add to activity note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\n});\n```\n\n## Authentication Pattern\n\nCommon pattern for OAuth authentication:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Request auth link from tool with callback\n const authLink = await this.tools.googleTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n // Create activity with auth link\n const activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n\n // Store for later use\n await this.set(\"auth_activity_id\", activity.id);\n}\n\nasync onAuthComplete(authResult: { authToken: string }, provider: string) {\n // Store auth token\n await this.set(`${provider}_auth`, authResult.authToken);\n\n // Continue setup flow\n await this.setupSyncOptions(authResult.authToken);\n}\n```\n\n## Sync Pattern\n\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\n\n```typescript\nasync startSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n\n await this.tools.calendarTool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n calendarId\n );\n}\n\nasync handleEvent(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\n await this.tools.plot.createActivity(activity);\n}\n\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `\uD83D\uDCC5 ${calendar.name}${calendar.primary ? \" (Primary)\" : \"\"}`,\n type: ActivityLinkType.callback,\n token: token,\n });\n }\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Which calendars would you like to connect?\",\n notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\n });\n}\n\nasync onCalendarSelected(\n link: ActivityLink,\n provider: string,\n calendarId: string,\n calendarName: string,\n authToken: string\n): Promise<void> {\n // Start sync for selected calendar\n await this.tools.tool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n provider,\n calendarId\n );\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\n await this.runTask(callback);\n}\n\nasync syncBatch(args: any, resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size \u2264 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n unread: !state.initialSync, // false for initial sync, true for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | `true` | Avoid notification overload from historical items |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n unread: !initialSync, // false for initial, true for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read, preventing spam from bulk historical imports\n- **Incremental sync**: New activities appear as unread, and archived state is preserved (respects user's archiving decisions)\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Activity/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Activity.id` / `Note.id` in the external item's metadata when creating it, and update `Activity.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes \u2014 that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\n });\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
|
|
7
|
+
declare const _default: "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n \u251C\u2500 Has stable URL or ID?\n \u2502 \u2514\u2500 Yes \u2192 Set Activity.source to the canonical URL/ID\n \u2502 Create Activity (Plot handles deduplication automatically)\n \u2502 Use Note.key for different note types:\n \u2502 - \"description\" for main content\n \u2502 - \"metadata\" for status/priority/assignee\n \u2502 - \"comment-{id}\" for individual comments\n \u2502\n \u2514\u2500 No stable identifier OR need multiple Plot activities per external item?\n \u2514\u2500 Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n \u251C\u2500 Yes \u2192 Generate UUID with Uuid.Generate()\n \u2502 Create new Activity with that UUID\n \u2502 Store mapping: external_id \u2192 activity_uuid\n \u2502\n \u2514\u2500 No (update/reply/comment) \u2192 Look up mapping by external_id\n \u251C\u2500 Found \u2192 Add Note to existing Activity using stored UUID\n \u2514\u2500 Not found \u2192 Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type NewActivityWithNotes,\n type ActivityFilter,\n type Priority,\n type ToolBuilder,\n Twist,\n ActivityType,\n} from \"@plotday/twister\";\nimport { ActivityAccess, Plot } from \"@plotday/twister/tools/plot\";\n// Import your tools:\n// import { GoogleCalendar } from \"@plotday/tool-google-calendar\";\n// import { Linear } from \"@plotday/tool-linear\";\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n // myTool: build(MyTool, {\n // onItem: this.handleItem,\n // onSyncableDisabled: this.onSyncableDisabled,\n // }),\n plot: build(Plot, {\n activity: { access: ActivityAccess.Create },\n }),\n };\n }\n\n async activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection handled in the twist edit modal.\n }\n\n async handleItem(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n }\n\n async onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\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#### Available External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar sync (CalendarTool)\n- `@plotday/tool-outlook-calendar`: Outlook Calendar sync (CalendarTool)\n- `@plotday/tool-google-contacts`: Google Contacts sync (supporting tool)\n- `@plotday/tool-google-drive`: Google Drive sync (DocumentTool)\n- `@plotday/tool-gmail`: Gmail sync (MessagingTool)\n- `@plotday/tool-slack`: Slack sync (MessagingTool)\n- `@plotday/tool-linear`: Linear sync (ProjectTool)\n- `@plotday/tool-jira`: Jira sync (ProjectTool)\n- `@plotday/tool-asana`: Asana sync (ProjectTool)\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Auth and resource selection are handled automatically via the twist edit modal when using external tools with Integrations.\n\nMost twists have an empty or minimal `activate()`:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection are handled in the twist edit modal.\n // Only add custom initialization here if needed.\n}\n```\n\n**Store Parent Activity for Later (optional):**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const activityId = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup complete\",\n notes: [{\n content: \"Your twist is ready. Activities will appear as they sync.\",\n }],\n });\n await this.set(\"setup_activity_id\", activityId);\n}\n```\n\n### Event Callbacks (via build options)\n\nTwists respond to events through callbacks declared in `build()`:\n\n**Receive synced items from a tool (most common):**\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n myTool: build(MyTool, {\n onItem: this.handleItem,\n onSyncableDisabled: this.onSyncableDisabled,\n }),\n plot: build(Plot, { activity: { access: ActivityAccess.Create } }),\n };\n}\n\nasync handleItem(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n}\n\nasync onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\n}\n```\n\n**React to activity changes (for two-way sync):**\n\n```typescript\nplot: build(Plot, {\n activity: {\n access: ActivityAccess.Create,\n updated: this.onActivityUpdated,\n },\n note: {\n created: this.onNoteCreated,\n },\n}),\n\nasync onActivityUpdated(activity: Activity, changes: { tagsAdded, tagsRemoved }): Promise<void> {\n const tool = this.getToolForActivity(activity);\n if (tool?.updateIssue) await tool.updateIssue(activity);\n}\n\nasync onNoteCreated(note: Note): Promise<void> {\n if (note.author.type === ActorType.Twist) return; // Prevent loops\n // Sync note to external service as a comment\n}\n```\n\n**Respond to mentions (AI twist pattern):**\n\n```typescript\nplot: build(Plot, {\n activity: { access: ActivityAccess.Respond },\n note: {\n intents: [{\n description: \"Respond to general questions\",\n examples: [\"What's the weather?\", \"Help me plan my week\"],\n handler: this.respond,\n }],\n },\n}),\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// External URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.external,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool \u2014 use linkCallback, not callback)\nconst token = await this.linkCallback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n callback: 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// Callback handler receives the ActivityLink as first argument\nasync onLinkClicked(link: ActivityLink, context: string): Promise<void> {\n // Handle link click\n}\n```\n\n## Authentication Pattern\n\nAuth is handled automatically via the Integrations tool. Tools declare their OAuth provider in `build()`, and users connect in the twist edit modal. **You do not need to create auth activities manually.**\n\n```typescript\n// In your tool's build() method:\nbuild(build: ToolBuilder) {\n return {\n integrations: build(Integrations, {\n providers: [{\n provider: AuthProvider.Google,\n scopes: [\"https://www.googleapis.com/auth/calendar\"],\n getSyncables: this.getSyncables, // List available resources after auth\n onSyncEnabled: this.onSyncEnabled, // User enabled a resource\n onSyncDisabled: this.onSyncDisabled, // User disabled a resource\n }],\n }),\n // ...\n };\n}\n\n// Get a token for API calls:\nconst token = await this.tools.integrations.get(AuthProvider.Google, syncableId);\nif (!token) throw new Error(\"No auth token available\");\nconst client = new ApiClient({ accessToken: token.token });\n```\n\nFor per-user write-backs (e.g., RSVP, comments attributed to the acting user):\n\n```typescript\nawait this.tools.integrations.actAs(\n AuthProvider.Google,\n actorId, // The user who performed the action\n activityId, // Activity to prompt for auth if needed\n this.performWriteBack,\n ...extraArgs\n);\n```\n\n## Sync Pattern\n\n### Recommended: Using External Tools with SyncToolOptions\n\nMost twists use external tools (CalendarTool, ProjectTool, etc.) that handle sync internally. The twist just receives `NewActivityWithNotes` objects and saves them:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n calendarTool: build(GoogleCalendar, {\n onItem: this.handleEvent, // Receives synced items\n onSyncableDisabled: this.onSyncableDisabled, // Clean up when disabled\n }),\n plot: build(Plot, { activity: { access: ActivityAccess.Create } }),\n };\n}\n\n// Tools deliver NewActivityWithNotes \u2014 twist saves them\nasync handleEvent(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n}\n\nasync onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\n}\n```\n\n### Custom Sync: Upsert via Source/Key (Strategy 2)\n\nFor direct API integration without an external tool, use source/key for automatic upserts:\n\n```typescript\nasync handleEvent(event: ExternalEvent): Promise<void> {\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // Canonical URL for automatic deduplication\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 if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables note-level upserts\n content: event.description,\n });\n }\n\n // Create or update \u2014 Plot handles deduplication automatically\n await this.tools.plot.createActivity(activity);\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## Resource Selection\n\nResource selection (calendars, projects, channels) is handled automatically in the twist edit modal via the Integrations tool. Users see a list of available resources returned by your tool's `getSyncables()` method and toggle them on/off. You do **not** need to build custom selection UI.\n\n```typescript\n// In your tool:\nasync getSyncables(_auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n const client = new ApiClient({ accessToken: token.token });\n const calendars = await client.listCalendars();\n return calendars.map(c => ({\n id: c.id,\n title: c.name,\n children: c.subCalendars?.map(sc => ({ id: sc.id, title: sc.name })),\n }));\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\n await this.runTask(callback);\n}\n\nasync syncBatch(resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size \u2264 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n ...(state.initialSync ? { unread: false } : {}), // false for initial, omit for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | *omit* | Initial: mark read for all. Incremental: auto-mark read for author only |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n ...(initialSync ? { unread: false } : {}), // false for initial, omit for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read for all users, preventing spam from bulk historical imports\n- **Incremental sync**: Activities are auto-marked read for the author (twist owner), unread for everyone else. Archived state is preserved\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Activity/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Activity.id` / `Note.id` in the external item's metadata when creating it, and update `Activity.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes \u2014 that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\n });\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
|
|
8
8
|
export default _default;
|
|
9
9
|
//# sourceMappingURL=twist-guide-template.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"twist-guide-template.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,
|
|
1
|
+
{"version":3,"file":"twist-guide-template.d.ts","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;wBAEY,02zBAAirzB;AAAhszB,wBAAiszB"}
|
|
@@ -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 requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n ├─ Has stable URL or ID?\n │ └─ Yes → Set Activity.source to the canonical URL/ID\n │ Create Activity (Plot handles deduplication automatically)\n │ Use Note.key for different note types:\n │ - \"description\" for main content\n │ - \"metadata\" for status/priority/assignee\n │ - \"comment-{id}\" for individual comments\n │\n └─ No stable identifier OR need multiple Plot activities per external item?\n └─ Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n ├─ Yes → Generate UUID with Uuid.Generate()\n │ Create new Activity with that UUID\n │ Store mapping: external_id → activity_uuid\n │\n └─ No (update/reply/comment) → Look up mapping by external_id\n ├─ Found → Add Note to existing Activity using stored UUID\n └─ Not found → Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type Priority,\n type ToolBuilder,\n twist,\n} from \"@plotday/twister\";\nimport { Plot } from \"@plotday/twister/tools/plot\";\nimport { Uuid } from \"@plotday/twister/utils/uuid\";\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n plot: build(Plot),\n };\n }\n\n async activate(priority: Pick<Priority, \"id\">) {\n // Called when twist is enabled for a priority\n // Common actions: request auth, create setup activities\n }\n\n async activity(activity: Activity) {\n // Called when an activity is routed to this twist\n // Common actions: process external events, update activities\n }\n}\n```\n\n## Tool System\n\n### Accessing Tools\n\nAll tools are declared in the `build` method:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n toolName: build(ToolClass),\n };\n}\n```\n\nAll `build()` calls must occur in the `build` method as they are used for dependency analysis.\n\nIMPORTANT: HTTP access is restricted to URLs requested via `build(Network, { urls: [url1, url2, ...] })` in the `build` method. Wildcards are supported. Use `build(Network, { urls: ['*'] })` if full access is needed.\n\n### Built-in Tools (Always Available)\n\nFor complete API documentation of built-in tools including all methods, types, and detailed examples, see the TypeScript definitions in your installed package at `node_modules/@plotday/twister/src/tools/*.ts`. Each tool file contains comprehensive JSDoc documentation.\n\n**Quick reference - Available tools:**\n\n- `@plotday/twister/tools/plot` - Core data layer (create/update activities, priorities, contacts)\n- `@plotday/twister/tools/ai` - LLM integration (text generation, structured output, reasoning)\n - Use ModelPreferences to specify `speed` (fast/balanced/capable) and `cost` (low/medium/high)\n- `@plotday/twister/tools/store` - Persistent key-value storage (also via `this.set()`, `this.get()`)\n- `@plotday/twister/tools/tasks` - Queue batched work (also via `this.run()`)\n- `@plotday/twister/tools/callbacks` - Persistent function references (also via `this.callback()`)\n- `@plotday/twister/tools/integrations` - OAuth2 authentication flows\n- `@plotday/twister/tools/network` - HTTP access permissions and webhook management\n- `@plotday/twister/tools/twists` - Manage other Twists\n\n**Critical**: Never use instance variables for state. They are lost after function execution. Always use Store methods.\n\n### External Tools (Add to package.json)\n\nAdd tool dependencies to `package.json`:\n\n```json\n{\n \"dependencies\": {\n \"@plotday/twister\": \"workspace:^\",\n \"@plotday/tool-google-calendar\": \"workspace:^\"\n }\n}\n```\n\n#### Common External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar integration\n- `@plotday/tool-outlook-calendar`: Outlook Calendar integration\n- `@plotday/tool-google-contacts`: Google Contacts integration\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Common patterns:\n\n**Request Authentication:**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const authLink = await this.tools.externalTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Connect your account\",\n notes: [\n {\n content: \"Click the link below to connect your account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n}\n```\n\n**Store Parent Activity for Later:**\n\n```typescript\nconst activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup\",\n notes: [\n {\n content: \"Your twist is being set up. Configuration steps will appear here.\",\n },\n ],\n});\n\nawait this.set(\"setup_activity_id\", activity.id);\n```\n\n### activity(activity: Activity)\n\nCalled when an activity is routed to the twist. Common patterns:\n\n**Create Activities from External Events:**\n\n```typescript\nasync activity(activity: Activity) {\n await this.tools.plot.createActivity(activity);\n}\n```\n\n**Update Based on User Action:**\n\n```typescript\nasync activity(activity: Activity) {\n if (activity.completed) {\n await this.handleCompletion(activity);\n }\n}\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.url,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool)\nconst token = await this.callback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n token: token,\n};\n\n// Add to activity note\nawait this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Task with links\",\n notes: [\n {\n content: \"Click the links below to take action.\",\n links: [urlLink, callbackLink],\n },\n ],\n});\n```\n\n## Authentication Pattern\n\nCommon pattern for OAuth authentication:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Request auth link from tool with callback\n const authLink = await this.tools.googleTool.requestAuth(\n this.onAuthComplete,\n \"google\"\n );\n\n // Create activity with auth link\n const activity = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Connect Google account\",\n notes: [\n {\n content: \"Click below to connect your Google account and start syncing.\",\n links: [authLink],\n },\n ],\n });\n\n // Store for later use\n await this.set(\"auth_activity_id\", activity.id);\n}\n\nasync onAuthComplete(authResult: { authToken: string }, provider: string) {\n // Store auth token\n await this.set(`${provider}_auth`, authResult.authToken);\n\n // Continue setup flow\n await this.setupSyncOptions(authResult.authToken);\n}\n```\n\n## Sync Pattern\n\n### Recommended: Upsert via Source/Key (Strategy 2)\n\nPattern for syncing external data using automatic upserts - **no manual ID tracking needed**:\n\n```typescript\nasync startSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n\n await this.tools.calendarTool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n calendarId\n );\n}\n\nasync handleEvent(\n event: ExternalEvent,\n calendarId: string\n): Promise<void> {\n // Use the event's canonical URL as the source for automatic deduplication\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // or event.url, depending on your external system\n type: ActivityType.Event,\n title: event.summary || \"(No title)\",\n start: event.start?.dateTime || event.start?.date || null,\n end: event.end?.dateTime || event.end?.date || null,\n notes: [],\n };\n\n // Add description as an upsertable note\n if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables upserts - same key updates the note\n content: event.description,\n });\n }\n\n // Add attendees as an upsertable note\n if (event.attendees?.length) {\n const attendeeList = event.attendees\n .map(a => `- ${a.email}${a.displayName ? ` (${a.displayName})` : ''}`)\n .join('\\n');\n\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"attendees\", // Different key for different note types\n content: `## Attendees\\n${attendeeList}`,\n });\n }\n\n // Create or update - Plot automatically handles deduplication based on source\n await this.tools.plot.createActivity(activity);\n}\n\nasync stopSync(calendarId: string): Promise<void> {\n const authToken = await this.get<string>(\"auth_token\");\n await this.tools.calendarTool.stopSync(authToken, calendarId);\n}\n```\n\n### Advanced: Generate and Store IDs (Strategy 3)\n\nOnly use this pattern when you need to create multiple Plot activities from a single external item, or when the external system doesn't provide stable identifiers. See SYNC_STRATEGIES.md for details.\n\n```typescript\nasync handleEventAdvanced(\n incomingActivity: NewActivityWithNotes,\n calendarId: string\n): Promise<void> {\n // Extract external event ID from meta (adapt based on your tool's data)\n const externalId = incomingActivity.meta?.eventId;\n\n if (!externalId) {\n console.error(\"Event missing external ID\");\n return;\n }\n\n // Check if we've already synced this event\n const mappingKey = `event_mapping:${calendarId}:${externalId}`;\n const existingActivityId = await this.get<Uuid>(mappingKey);\n\n if (existingActivityId) {\n // Event already exists - add update as a Note (add message to thread)\n if (incomingActivity.notes?.[0]?.content) {\n await this.tools.plot.createNote({\n activity: { id: existingActivityId },\n content: incomingActivity.notes[0].content,\n });\n }\n return;\n }\n\n // New event - generate UUID and store mapping\n const activityId = Uuid.Generate();\n await this.set(mappingKey, activityId);\n\n // Create new Activity with initial Note (new thread with first message)\n await this.tools.plot.createActivity({\n ...incomingActivity,\n id: activityId,\n });\n}\n```\n\n## Calendar Selection Pattern\n\nPattern for letting users select from multiple calendars/accounts:\n\n```typescript\nprivate async createCalendarSelectionActivity(\n provider: string,\n calendars: Calendar[],\n authToken: string\n): Promise<void> {\n const links: ActivityLink[] = [];\n\n for (const calendar of calendars) {\n const token = await this.callback(\n this.onCalendarSelected,\n provider,\n calendar.id,\n calendar.name,\n authToken\n );\n\n links.push({\n title: `📅 ${calendar.name}${calendar.primary ? \" (Primary)\" : \"\"}`,\n type: ActivityLinkType.callback,\n token: token,\n });\n }\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Which calendars would you like to connect?\",\n notes: [\n {\n content: \"Select the calendars you want to sync:\",\n links,\n },\n ],\n });\n}\n\nasync onCalendarSelected(\n link: ActivityLink,\n provider: string,\n calendarId: string,\n calendarName: string,\n authToken: string\n): Promise<void> {\n // Start sync for selected calendar\n await this.tools.tool.startSync(\n authToken,\n calendarId,\n this.handleEvent,\n provider,\n calendarId\n );\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\n await this.runTask(callback);\n}\n\nasync syncBatch(args: any, resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size ≤ 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n unread: !state.initialSync, // false for initial sync, true for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | `true` | Avoid notification overload from historical items |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n unread: !initialSync, // false for initial, true for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read, preventing spam from bulk historical imports\n- **Incremental sync**: New activities appear as unread, and archived state is preserved (respects user's archiving decisions)\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Activity/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Activity.id` / `Note.id` in the external item's metadata when creating it, and update `Activity.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes — that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\n });\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
|
|
7
|
+
export default "# Twist Implementation Guide for LLMs\n\nThis document provides context for AI assistants generating or modifying twists.\n\n## Architecture Overview\n\nPlot Twists are TypeScript classes that extend the `Twist` base class. Twists interact with external services and Plot's core functionality through a tool-based architecture.\n\n### Runtime Environment\n\n**Critical**: All Twists and tool functions are executed in a sandboxed, ephemeral environment with limited resources:\n\n- **Memory is temporary**: Anything stored in memory (e.g. as a variable in the twist/tool object) is lost after the function completes. Use the Store tool instead. Only use memory for temporary caching.\n- **Limited requests per execution**: Each execution has ~1000 requests (HTTP requests, tool calls, database operations)\n- **Limited CPU time**: Each execution has limited CPU time (typically ~60 seconds) and memory (128MB)\n- **Use tasks to get fresh request limits**: `this.runTask()` creates a NEW execution with a fresh ~1000 request limit\n- **Calling callbacks continues same execution**: `this.run()` continues the same execution and shares the request count\n- **Break long loops**: Split large operations into batches that each stay under the ~1000 request limit\n- **Store intermediate state**: Use the Store tool to persist state between batches\n- **Examples**: Syncing large datasets, processing many API calls, or performing batch operations\n\n## Understanding Activities and Notes\n\n**CRITICAL CONCEPT**: An **Activity** represents something done or to be done (a task, event, or conversation), while **Notes** represent the updates and details on that activity.\n\n**Think of an Activity as a thread** on a messaging platform, and **Notes as the messages in that thread**.\n\n### Key Guidelines\n\n1. **Always create Activities with an initial Note** - The title is just a summary; detailed content goes in Notes\n2. **Add Notes to existing Activities for updates** - Don't create a new Activity for each related message\n3. **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for deduplication, and use Note.key for upsertable note content. No manual ID tracking needed.\n4. **For advanced cases, use generated UUIDs** - Only when you need multiple Plot activities per external item (see SYNC_STRATEGIES.md)\n5. **Most Activities should be `ActivityType.Note`** - Use `Action` only for tasks with `done`, use `Event` only for items with `start`/`end`\n\n### Recommended Decision Tree (Strategy 2: Upsert via Source/Key)\n\n```\nNew event/task/conversation from external system?\n ├─ Has stable URL or ID?\n │ └─ Yes → Set Activity.source to the canonical URL/ID\n │ Create Activity (Plot handles deduplication automatically)\n │ Use Note.key for different note types:\n │ - \"description\" for main content\n │ - \"metadata\" for status/priority/assignee\n │ - \"comment-{id}\" for individual comments\n │\n └─ No stable identifier OR need multiple Plot activities per external item?\n └─ Use Advanced Pattern (Strategy 3: Generate and Store IDs)\n See SYNC_STRATEGIES.md for details\n```\n\n### Advanced Decision Tree (Strategy 3: Generate and Store IDs)\n\nOnly use when source/key upserts aren't sufficient (e.g., creating multiple activities from one external item):\n\n```\nNew event/task/conversation?\n ├─ Yes → Generate UUID with Uuid.Generate()\n │ Create new Activity with that UUID\n │ Store mapping: external_id → activity_uuid\n │\n └─ No (update/reply/comment) → Look up mapping by external_id\n ├─ Found → Add Note to existing Activity using stored UUID\n └─ Not found → Create new Activity with UUID + store mapping\n```\n\n## Twist Structure Pattern\n\n```typescript\nimport {\n type Activity,\n type NewActivityWithNotes,\n type ActivityFilter,\n type Priority,\n type ToolBuilder,\n Twist,\n ActivityType,\n} from \"@plotday/twister\";\nimport { ActivityAccess, Plot } from \"@plotday/twister/tools/plot\";\n// Import your tools:\n// import { GoogleCalendar } from \"@plotday/tool-google-calendar\";\n// import { Linear } from \"@plotday/tool-linear\";\n\nexport default class MyTwist extends Twist<MyTwist> {\n build(build: ToolBuilder) {\n return {\n // myTool: build(MyTool, {\n // onItem: this.handleItem,\n // onSyncableDisabled: this.onSyncableDisabled,\n // }),\n plot: build(Plot, {\n activity: { access: ActivityAccess.Create },\n }),\n };\n }\n\n async activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection handled in the twist edit modal.\n }\n\n async handleItem(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n }\n\n async onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\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#### Available External Tools\n\n- `@plotday/tool-google-calendar`: Google Calendar sync (CalendarTool)\n- `@plotday/tool-outlook-calendar`: Outlook Calendar sync (CalendarTool)\n- `@plotday/tool-google-contacts`: Google Contacts sync (supporting tool)\n- `@plotday/tool-google-drive`: Google Drive sync (DocumentTool)\n- `@plotday/tool-gmail`: Gmail sync (MessagingTool)\n- `@plotday/tool-slack`: Slack sync (MessagingTool)\n- `@plotday/tool-linear`: Linear sync (ProjectTool)\n- `@plotday/tool-jira`: Jira sync (ProjectTool)\n- `@plotday/tool-asana`: Asana sync (ProjectTool)\n\n## Lifecycle Methods\n\n### activate(priority: Pick<Priority, \"id\">)\n\nCalled when the twist is enabled for a priority. Auth and resource selection are handled automatically via the twist edit modal when using external tools with Integrations.\n\nMost twists have an empty or minimal `activate()`:\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n // Auth and resource selection are handled in the twist edit modal.\n // Only add custom initialization here if needed.\n}\n```\n\n**Store Parent Activity for Later (optional):**\n\n```typescript\nasync activate(_priority: Pick<Priority, \"id\">) {\n const activityId = await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Setup complete\",\n notes: [{\n content: \"Your twist is ready. Activities will appear as they sync.\",\n }],\n });\n await this.set(\"setup_activity_id\", activityId);\n}\n```\n\n### Event Callbacks (via build options)\n\nTwists respond to events through callbacks declared in `build()`:\n\n**Receive synced items from a tool (most common):**\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n myTool: build(MyTool, {\n onItem: this.handleItem,\n onSyncableDisabled: this.onSyncableDisabled,\n }),\n plot: build(Plot, { activity: { access: ActivityAccess.Create } }),\n };\n}\n\nasync handleItem(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n}\n\nasync onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\n}\n```\n\n**React to activity changes (for two-way sync):**\n\n```typescript\nplot: build(Plot, {\n activity: {\n access: ActivityAccess.Create,\n updated: this.onActivityUpdated,\n },\n note: {\n created: this.onNoteCreated,\n },\n}),\n\nasync onActivityUpdated(activity: Activity, changes: { tagsAdded, tagsRemoved }): Promise<void> {\n const tool = this.getToolForActivity(activity);\n if (tool?.updateIssue) await tool.updateIssue(activity);\n}\n\nasync onNoteCreated(note: Note): Promise<void> {\n if (note.author.type === ActorType.Twist) return; // Prevent loops\n // Sync note to external service as a comment\n}\n```\n\n**Respond to mentions (AI twist pattern):**\n\n```typescript\nplot: build(Plot, {\n activity: { access: ActivityAccess.Respond },\n note: {\n intents: [{\n description: \"Respond to general questions\",\n examples: [\"What's the weather?\", \"Help me plan my week\"],\n handler: this.respond,\n }],\n },\n}),\n```\n\n## Activity Links\n\nActivity links enable user interaction:\n\n```typescript\nimport { type ActivityLink, ActivityLinkType } from \"@plotday/twister\";\n\n// External URL link\nconst urlLink: ActivityLink = {\n title: \"Open website\",\n type: ActivityLinkType.external,\n url: \"https://example.com\",\n};\n\n// Callback link (uses Callbacks tool — use linkCallback, not callback)\nconst token = await this.linkCallback(this.onLinkClicked, \"context\");\nconst callbackLink: ActivityLink = {\n title: \"Click me\",\n type: ActivityLinkType.callback,\n callback: 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// Callback handler receives the ActivityLink as first argument\nasync onLinkClicked(link: ActivityLink, context: string): Promise<void> {\n // Handle link click\n}\n```\n\n## Authentication Pattern\n\nAuth is handled automatically via the Integrations tool. Tools declare their OAuth provider in `build()`, and users connect in the twist edit modal. **You do not need to create auth activities manually.**\n\n```typescript\n// In your tool's build() method:\nbuild(build: ToolBuilder) {\n return {\n integrations: build(Integrations, {\n providers: [{\n provider: AuthProvider.Google,\n scopes: [\"https://www.googleapis.com/auth/calendar\"],\n getSyncables: this.getSyncables, // List available resources after auth\n onSyncEnabled: this.onSyncEnabled, // User enabled a resource\n onSyncDisabled: this.onSyncDisabled, // User disabled a resource\n }],\n }),\n // ...\n };\n}\n\n// Get a token for API calls:\nconst token = await this.tools.integrations.get(AuthProvider.Google, syncableId);\nif (!token) throw new Error(\"No auth token available\");\nconst client = new ApiClient({ accessToken: token.token });\n```\n\nFor per-user write-backs (e.g., RSVP, comments attributed to the acting user):\n\n```typescript\nawait this.tools.integrations.actAs(\n AuthProvider.Google,\n actorId, // The user who performed the action\n activityId, // Activity to prompt for auth if needed\n this.performWriteBack,\n ...extraArgs\n);\n```\n\n## Sync Pattern\n\n### Recommended: Using External Tools with SyncToolOptions\n\nMost twists use external tools (CalendarTool, ProjectTool, etc.) that handle sync internally. The twist just receives `NewActivityWithNotes` objects and saves them:\n\n```typescript\nbuild(build: ToolBuilder) {\n return {\n calendarTool: build(GoogleCalendar, {\n onItem: this.handleEvent, // Receives synced items\n onSyncableDisabled: this.onSyncableDisabled, // Clean up when disabled\n }),\n plot: build(Plot, { activity: { access: ActivityAccess.Create } }),\n };\n}\n\n// Tools deliver NewActivityWithNotes — twist saves them\nasync handleEvent(activity: NewActivityWithNotes): Promise<void> {\n await this.tools.plot.createActivity(activity);\n}\n\nasync onSyncableDisabled(filter: ActivityFilter): Promise<void> {\n await this.tools.plot.updateActivity({ match: filter, archived: true });\n}\n```\n\n### Custom Sync: Upsert via Source/Key (Strategy 2)\n\nFor direct API integration without an external tool, use source/key for automatic upserts:\n\n```typescript\nasync handleEvent(event: ExternalEvent): Promise<void> {\n const activity: NewActivityWithNotes = {\n source: event.htmlLink, // Canonical URL for automatic deduplication\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 if (event.description) {\n activity.notes.push({\n activity: { source: event.htmlLink },\n key: \"description\", // This key enables note-level upserts\n content: event.description,\n });\n }\n\n // Create or update — Plot handles deduplication automatically\n await this.tools.plot.createActivity(activity);\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## Resource Selection\n\nResource selection (calendars, projects, channels) is handled automatically in the twist edit modal via the Integrations tool. Users see a list of available resources returned by your tool's `getSyncables()` method and toggle them on/off. You do **not** need to build custom selection UI.\n\n```typescript\n// In your tool:\nasync getSyncables(_auth: Authorization, token: AuthToken): Promise<Syncable[]> {\n const client = new ApiClient({ accessToken: token.token });\n const calendars = await client.listCalendars();\n return calendars.map(c => ({\n id: c.id,\n title: c.name,\n children: c.subCalendars?.map(sc => ({ id: sc.id, title: sc.name })),\n }));\n}\n```\n\n## Batch Processing Pattern\n\n**Important**: Because Twists run in an ephemeral environment with limited requests per execution (~1000 requests), you must break long operations into batches. Each batch runs independently in a new execution context with its own fresh request limit.\n\n### Key Principles\n\n1. **Stay under request limits**: Each execution has ~1000 requests. Size batches accordingly.\n2. **Use runTask() for fresh limits**: Each call to `this.runTask()` creates a NEW execution with fresh ~1000 requests\n3. **Store state between batches**: Use the Store tool to persist progress\n4. **Calculate safe batch sizes**: Determine requests per item to size batches (e.g., ~10 requests per item = ~100 items per batch)\n5. **Clean up when done**: Delete stored state after completion\n6. **Handle failures**: Store enough state to resume if a batch fails\n\n### Example Implementation\n\n```typescript\nasync startSync(resourceId: string): Promise<void> {\n // Initialize state in Store (persists between executions)\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: null,\n batchNumber: 1,\n itemsProcessed: 0,\n initialSync: true, // Track whether this is the first sync\n });\n\n // Queue first batch using runTask method\n const callback = await this.callback(this.syncBatch, resourceId);\n // runTask creates NEW execution with fresh ~1000 request limit\n await this.runTask(callback);\n}\n\nasync syncBatch(resourceId: string): Promise<void> {\n // Load state from Store (set by previous execution)\n const state = await this.get(`sync_state_${resourceId}`);\n\n // Process one batch (size to stay under ~1000 request limit)\n const result = await this.fetchBatch(state.nextPageToken);\n\n // Process results using source/key pattern (automatic upserts, no manual tracking)\n // If each item makes ~10 requests, keep batch size ≤ 100 items to stay under limit\n for (const item of result.items) {\n // Each createActivity may make ~5-10 requests depending on notes/links\n await this.tools.plot.createActivity({\n source: item.url, // Use item's canonical URL for automatic deduplication\n type: ActivityType.Note,\n title: item.title,\n notes: [{\n activity: { source: item.url },\n key: \"description\", // Use key for upsertable notes\n content: item.description,\n }],\n ...(state.initialSync ? { unread: false } : {}), // false for initial, omit for incremental\n ...(state.initialSync ? { archived: false } : {}), // unarchive on initial only\n });\n }\n\n if (result.nextPageToken) {\n // Update state in Store for next batch\n await this.set(`sync_state_${resourceId}`, {\n nextPageToken: result.nextPageToken,\n batchNumber: state.batchNumber + 1,\n itemsProcessed: state.itemsProcessed + result.items.length,\n initialSync: state.initialSync, // Preserve initialSync flag across batches\n });\n\n // Queue next batch - creates NEW execution with fresh request limit\n const nextCallback = await this.callback(this.syncBatch, resourceId);\n await this.runTask(nextCallback);\n } else {\n // Cleanup when complete\n await this.clear(`sync_state_${resourceId}`);\n\n // Optionally notify user of completion\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Sync complete\",\n notes: [\n {\n content: `Successfully processed ${state.itemsProcessed + result.items.length} items.`,\n },\n ],\n });\n }\n}\n```\n\n## Activity Sync Best Practices\n\nWhen syncing activities from external systems, follow these patterns for optimal user experience:\n\n### The `initialSync` Flag\n\nAll sync-based tools should distinguish between initial sync (first import) and incremental sync (ongoing updates):\n\n| Field | Initial Sync | Incremental Sync | Reason |\n|-------|--------------|------------------|---------|\n| `unread` | `false` | *omit* | Initial: mark read for all. Incremental: auto-mark read for author only |\n| `archived` | `false` | *omit* | Unarchive on install, preserve user choice on updates |\n\n**Example:**\n```typescript\nconst activity: NewActivity = {\n type: ActivityType.Event,\n source: event.url,\n title: event.title,\n ...(initialSync ? { unread: false } : {}), // false for initial, omit for incremental\n ...(initialSync ? { archived: false } : {}), // unarchive on initial only\n};\n```\n\n**Why this matters:**\n- **Initial sync**: Activities are unarchived and marked as read for all users, preventing spam from bulk historical imports\n- **Incremental sync**: Activities are auto-marked read for the author (twist owner), unread for everyone else. Archived state is preserved\n- **Reinstall**: Acts as initial sync, so previously archived activities are unarchived (fresh start)\n\n### Two-Way Sync: Avoiding Race Conditions\n\nWhen implementing two-way sync where items created in Plot are pushed to an external system (e.g. Notes becoming comments), a race condition can occur: the external system may send a webhook for the newly created item before you've updated the Activity/Note with the external key. The webhook handler won't find the item by external key and may create a duplicate.\n\n**Solution:** Embed the Plot `Activity.id` / `Note.id` in the external item's metadata when creating it, and update `Activity.source` / `Note.key` after creation. When processing webhooks, check for the Plot ID in metadata first.\n\n```typescript\nasync pushNoteAsComment(note: Note, externalItemId: string): Promise<void> {\n // Create external item with Plot ID in metadata for webhook correlation\n const externalComment = await externalApi.createComment(externalItemId, {\n body: note.content,\n metadata: { plotNoteId: note.id },\n });\n\n // Update Note with external key AFTER creation\n // A webhook may arrive before this completes — that's OK (see onWebhook below)\n await this.tools.plot.updateNote({\n id: note.id,\n key: `comment-${externalComment.id}`,\n });\n}\n\nasync onWebhook(payload: WebhookPayload): Promise<void> {\n const comment = payload.comment;\n\n // Use Plot ID from metadata if present (handles race condition),\n // otherwise fall back to upserting by activity source and key\n await this.tools.plot.createNote({\n ...(comment.metadata?.plotNoteId\n ? { id: comment.metadata.plotNoteId }\n : { activity: { source: payload.itemUrl } }),\n key: `comment-${comment.id}`,\n content: comment.body,\n });\n}\n```\n\n## Error Handling\n\nAlways handle errors gracefully and communicate them to users:\n\n```typescript\ntry {\n await this.externalOperation();\n} catch (error) {\n console.error(\"Operation failed:\", error);\n\n await this.tools.plot.createActivity({\n type: ActivityType.Note,\n title: \"Operation failed\",\n notes: [\n {\n content: `Failed to complete operation: ${error.message}`,\n },\n ],\n });\n}\n```\n\n## Common Pitfalls\n\n- **Don't use instance variables for state** - Anything stored in memory is lost after function execution. Always use the Store tool for data that needs to persist.\n- **Processing self-created activities** - Other users may change an Activity created by the twist, resulting in an \\`activity\\` call. Be sure to check the \\`changes === null\\` and/or \\`activity.author.id !== this.id\\` to avoid re-processing.\n- **Always create Activities with Notes** - See \"Understanding Activities and Notes\" section above for the thread/message pattern and decision tree.\n- **Use correct Activity types** - Most should be `ActivityType.Note`. Only use `Action` for tasks with `done`, and `Event` for items with `start`/`end`.\n- **Use Activity.source and Note.key for automatic upserts (Recommended)** - Set Activity.source to the external item's URL for automatic deduplication. Only use UUID generation and storage for advanced cases (see SYNC_STRATEGIES.md).\n- **Add Notes to existing Activities** - For source/key pattern, reference activities by source. For UUID pattern, look up stored mappings before creating new Activities. Think thread replies, not new threads.\n- Tools are declared in the `build` method and accessed via `this.tools.toolName` in twist methods.\n- **Don't forget request limits** - Each execution has ~1000 requests (HTTP requests, tool calls). Break long loops into batches with `this.runTask()` to get fresh request limits. Calculate requests per item to determine safe batch size (e.g., if each item needs ~10 requests, batch size = ~100 items).\n- **Always use Callbacks tool for persistent references** - Direct function references don't survive worker restarts.\n- **Store auth tokens** - Don't re-request authentication unnecessarily.\n- **Clean up callbacks and stored state** - Delete callbacks and Store entries when no longer needed.\n- **Handle missing auth gracefully** - Check for stored auth before operations.\n- **CRITICAL: Maintain callback backward compatibility** - All callbacks (webhooks, tasks, batch operations) automatically upgrade to new twist versions. You **must** maintain backward compatibility in callback method signatures. Only add optional parameters at the end, never remove or reorder parameters. For breaking changes, implement migration logic in the `upgrade()` lifecycle method to recreate affected callbacks.\n\n## Testing\n\nBefore deploying, verify:\n\n1. Linting passes: `{{packageManager}} lint`\n2. All dependencies are in package.json\n3. Authentication flow works end-to-end\n4. Batch operations handle pagination correctly\n5. Error cases are handled gracefully\n";
|
|
8
8
|
//# sourceMappingURL=twist-guide-template.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"twist-guide-template.js","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,
|
|
1
|
+
{"version":3,"file":"twist-guide-template.js","sourceRoot":"","sources":["../../src/llm-docs/twist-guide-template.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAe,irzBAAirzB,CAAC"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { ITool } from "./tool";
|
|
2
|
+
/**
|
|
3
|
+
* A select option definition for twist configuration.
|
|
4
|
+
* Renders as a dropdown in the Flutter UI.
|
|
5
|
+
*/
|
|
6
|
+
export type SelectDef = {
|
|
7
|
+
type: "select";
|
|
8
|
+
label: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
choices: ReadonlyArray<{
|
|
11
|
+
value: string;
|
|
12
|
+
label: string;
|
|
13
|
+
}>;
|
|
14
|
+
default: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* A text input option definition for twist configuration.
|
|
18
|
+
* Renders as a text field in the Flutter UI.
|
|
19
|
+
*/
|
|
20
|
+
export type TextDef = {
|
|
21
|
+
type: "text";
|
|
22
|
+
label: string;
|
|
23
|
+
description?: string;
|
|
24
|
+
default: string;
|
|
25
|
+
placeholder?: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A number input option definition for twist configuration.
|
|
29
|
+
* Renders as a number field in the Flutter UI.
|
|
30
|
+
*/
|
|
31
|
+
export type NumberDef = {
|
|
32
|
+
type: "number";
|
|
33
|
+
label: string;
|
|
34
|
+
description?: string;
|
|
35
|
+
default: number;
|
|
36
|
+
min?: number;
|
|
37
|
+
max?: number;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* A boolean toggle option definition for twist configuration.
|
|
41
|
+
* Renders as a switch in the Flutter UI.
|
|
42
|
+
*/
|
|
43
|
+
export type BooleanDef = {
|
|
44
|
+
type: "boolean";
|
|
45
|
+
label: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
default: boolean;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Union of all option definition types.
|
|
51
|
+
*/
|
|
52
|
+
export type OptionDef = SelectDef | TextDef | NumberDef | BooleanDef;
|
|
53
|
+
/**
|
|
54
|
+
* Schema defining all configurable options for a twist.
|
|
55
|
+
* Each key maps to an option definition that describes its type, label, and default value.
|
|
56
|
+
*/
|
|
57
|
+
export type OptionsSchema = Record<string, OptionDef>;
|
|
58
|
+
/**
|
|
59
|
+
* Infers the resolved value types from an options schema.
|
|
60
|
+
* Boolean options resolve to `boolean`, number options to `number`,
|
|
61
|
+
* and select/text options to `string`.
|
|
62
|
+
*/
|
|
63
|
+
export type ResolvedOptions<T extends OptionsSchema> = {
|
|
64
|
+
[K in keyof T]: T[K] extends BooleanDef ? boolean : T[K] extends NumberDef ? number : string;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Built-in marker class for twist configuration options.
|
|
68
|
+
*
|
|
69
|
+
* Declare options in your twist's `build()` method to expose configurable
|
|
70
|
+
* settings to users. The schema is introspected at deploy time and stored
|
|
71
|
+
* alongside permissions. At runtime, user values are merged with defaults.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* import { Options, type OptionsSchema } from "@plotday/twister/options";
|
|
76
|
+
*
|
|
77
|
+
* export default class MyTwist extends Twist<MyTwist> {
|
|
78
|
+
* build(build: ToolBuilder) {
|
|
79
|
+
* return {
|
|
80
|
+
* options: build(Options, {
|
|
81
|
+
* model: {
|
|
82
|
+
* type: 'select',
|
|
83
|
+
* label: 'AI Model',
|
|
84
|
+
* choices: [
|
|
85
|
+
* { value: 'fast', label: 'Fast' },
|
|
86
|
+
* { value: 'smart', label: 'Smart' },
|
|
87
|
+
* ],
|
|
88
|
+
* default: 'fast',
|
|
89
|
+
* },
|
|
90
|
+
* }),
|
|
91
|
+
* // ... other tools
|
|
92
|
+
* };
|
|
93
|
+
* }
|
|
94
|
+
*
|
|
95
|
+
* async respond(note: Note) {
|
|
96
|
+
* const model = this.tools.options.model; // typed as string
|
|
97
|
+
* }
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export declare abstract class Options extends ITool {
|
|
102
|
+
static readonly toolId = "Options";
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAE/B;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,EAAE,QAAQ,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,aAAa,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACzD,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,EAAE,QAAQ,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,UAAU,CAAC;AAErE;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAEtD;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,aAAa,IAAI;KACpD,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,UAAU,GACnC,OAAO,GACP,CAAC,CAAC,CAAC,CAAC,SAAS,SAAS,GACpB,MAAM,GACN,MAAM;CACb,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,8BAAsB,OAAQ,SAAQ,KAAK;IACzC,MAAM,CAAC,QAAQ,CAAC,MAAM,aAAa;CACpC"}
|