### Create and Start Dibbla Agents SDK Server Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt This TypeScript code demonstrates the main entry point for a Dibbla Agents SDK worker. It initializes the SDK server, loads environment variables for configuration, registers all modular functions exported from the 'functions' directory, and starts the server to begin processing requests. Error handling for the server start process is included. ```typescript // main.ts import 'dotenv/config'; import * as sdk from '@dibbla-agents/sdk-ts'; import * as functions from './functions'; async function main() { const server = sdk.create({ serverName: process.env.SERVER_NAME || 'modular-worker', serverApiToken: process.env.SERVER_API_TOKEN, }); server.registerFunctions(functions.all); console.log(`Starting worker with ${functions.all.length} functions...`); await server.start(); } main().catch(console.error); ``` -------------------------------- ### Install Dibbla SDK for TypeScript Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Installs the Dibbla SDK for TypeScript using npm. This command should be run in your project directory. ```bash npm install @dibbla-agents/sdk-ts ``` -------------------------------- ### Register and Run Dibbla SDK Server (TypeScript) Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Demonstrates how to create and start a Dibbla SDK server in TypeScript. It involves initializing the server with an API token, registering previously defined functions, and starting the server to listen for incoming requests. This code is typically the entry point for a worker process. ```typescript async function main() { const server = sdk.create({ serverName: 'sheets-worker', serverApiToken: process.env.SERVER_API_TOKEN, }); server.registerFunction(readGoogleSheetsFn); console.log('Starting Google Sheets worker...'); await server.start(); } main().catch(console.error); ``` -------------------------------- ### Minimal Entry Point (`main.ts`) with SDK Initialization Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md This snippet demonstrates the basic structure of an application's entry point using the @dibbla-agents/sdk-ts. It initializes the SDK server with configuration from environment variables and registers all available functions. This setup promotes separation of concerns and scalability by centralizing server creation and function registration. ```typescript import 'dotenv/config'; import * as sdk from '@dibbla-agents/sdk-ts'; import * as functions from './functions'; async function main() { const server = sdk.create({ serverName: process.env.SERVER_NAME || 'my-worker', serverApiToken: process.env.SERVER_API_TOKEN, }); // Register all functions at once server.registerFunctions(functions.all); console.log(`Starting worker with ${functions.all.length} functions...`); await server.start(); } main().catch(console.error); ``` -------------------------------- ### Register Multiple Functions at Once with TypeScript SDK Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Shows how to define and register multiple functions simultaneously with the Dibbla Agents SDK server. This example defines three simple functions with different input/output types and registers them in a single call to `server.registerFunctions`. ```typescript import * as sdk from '@dibbla-agents/sdk-ts'; import { z } from 'zod'; // Define multiple functions const fn1 = sdk.newSimpleFunction({ name: 'function_1', version: '1.0.0', description: 'First function', input: z.object({ input: z.string() }), output: z.object({ output: z.string() }), handler: (input) => ({ output: input.input }), }); const fn2 = sdk.newSimpleFunction({ name: 'function_2', version: '1.0.0', description: 'Second function', input: z.object({ value: z.number() }), output: z.object({ result: z.number() }), handler: (input) => ({ result: input.value * 2 }), }); const fn3 = sdk.newSimpleFunction({ name: 'function_3', version: '1.0.0', description: 'Third function', input: z.object({ text: z.string() }), output: z.object({ length: z.number() }), handler: (input) => ({ length: input.text.length }), }); // Register all at once const server = sdk.create({ serverName: 'multi-function-worker', serverApiToken: process.env.SERVER_API_TOKEN, }); server.registerFunctions([fn1, fn2, fn3]); console.log('Starting worker with 3 functions...'); await server.start(); ``` -------------------------------- ### Create a Basic Worker with a Simple Function Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Demonstrates creating a minimal gRPC worker using the Dibbla SDK. It defines input/output schemas with Zod, registers a simple greeting function, and starts the server. ```typescript import * as sdk from '@dibbla-agents/sdk-ts'; import { z } from 'zod'; // Define input/output schemas with Zod const GreetingInput = z.object({ name: z.string(), }); const GreetingOutput = z.object({ message: z.string(), }); async function main() { // Create server with minimal configuration // (defaults to grpc.dibbla.com:443 with TLS enabled) const server = sdk.create({ serverName: 'my-custom-worker', serverApiToken: process.env.SERVER_API_TOKEN, }); // Register a simple function const greetingFn = sdk.newSimpleFunction({ name: 'greeting', version: '1.0.0', description: 'Generate a greeting message', input: GreetingInput, output: GreetingOutput, handler: (input) => ({ message: `Hello, ${input.name}!`, }), // tags: ['utility', 'greeting'], // Optional - not used in most cases }); server.registerFunction(greetingFn); // Or register multiple functions at once: // server.registerFunctions([greetingFn, otherFn, anotherFn]); // Start server (blocks forever) console.log('Starting worker...'); await server.start(); } main().catch(console.error); ``` -------------------------------- ### Key-Value Store Operations using TypeScript SDK Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Demonstrates storing and retrieving string data from a workflow-scoped key-value store using the Dibbla Agents SDK. It defines input and output schemas for both operations and includes handlers for storing and getting data, along with status event reporting. ```typescript const StoreDataInput = z.object({ key: z.string(), value: z.string(), }); const StoreDataOutput = z.object({ success: z.boolean(), }); const storeDataFn = sdk.newFunction({ name: 'store_data', version: '1.0.0', description: 'Store data in workflow-scoped key-value store', input: StoreDataInput, output: StoreDataOutput, handler: async (input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Storing data...', { key: input.key }); // Store data scoped to workflow await state.store?.setString(event.workflow, input.key, input.value); await state.rpc?.sendStatusEvent(event, 'Data stored successfully'); return { success: true }; }, }); const GetDataInput = z.object({ key: z.string(), }); const GetDataOutput = z.object({ value: z.string().nullable(), }); const getDataFn = sdk.newFunction({ name: 'get_data', version: '1.0.0', description: 'Retrieve data from workflow-scoped key-value store', input: GetDataInput, output: GetDataOutput, handler: async (input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Retrieving data...', { key: input.key }); // Retrieve data scoped to workflow const value = await state.store?.getString(event.workflow, input.key); await state.rpc?.sendStatusEvent(event, value ? 'Data retrieved' : 'Key not found'); return { value }; }, }); server.registerFunctions([storeDataFn, getDataFn]); ``` -------------------------------- ### Get OAuth Access Token in TypeScript Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Demonstrates how to retrieve an OAuth access token for a specified provider (e.g., 'google') using the globalState.oauth object. The token can then be used to make authenticated API calls on behalf of the user. It also includes a check to ensure the user has connected their account. ```typescript const fn = sdk.newFunction({ name: 'call_google_api', version: '1.0.0', description: 'Calls a Google API on behalf of the user', input: MyInputSchema, output: MyOutputSchema, handler: async (input, event, globalState) => { // Get an access token for Google const token = await globalState.oauth?.getAccessToken('google', event.run); if (!token) { throw new Error('Please connect your Google account first'); } // Use the token to call Google APIs // token.accessToken - the bearer token // token.tokenType - typically "Bearer" // token.expiresAt - Unix timestamp when token expires return output; }, }); ``` -------------------------------- ### Defining Functions with Optional Tags Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md This example shows how to add an optional `tags` array to a function definition using `sdk.newSimpleFunction`. While tags are not actively used by current workflow features, they are intended for future use cases such as function discovery, UI filtering, and access control policies. They are sent to the workflow server during registration. ```typescript const fn = sdk.newSimpleFunction({ // ... tags: ['utility', 'math'], }); ``` -------------------------------- ### Sending Real-time Status Updates in Function Handlers Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md This example illustrates how to send real-time status messages from a function handler using `globalState.rpc?.sendStatusEvent`. This is crucial for providing progress feedback to the user interface during long-running operations. It shows sending initial, intermediate, and completion status messages, optionally including structured payloads for detailed progress information. ```typescript const fn = sdk.newFunction({ name: 'process_data', version: '1.0.0', description: 'Process data with progress updates', input: MyInputSchema, output: MyOutputSchema, handler: async (input, event, globalState) => { // Send initial status await globalState.rpc?.sendStatusEvent(event, 'Starting data processing...', { progress: 0, }); // ... do some work ... // Send progress update with optional payload await globalState.rpc?.sendStatusEvent(event, 'Processing 50% complete', { progress: 50, itemsProcessed: 500, }); // ... do more work ... // Send completion status await globalState.rpc?.sendStatusEvent(event, 'Processing complete!', { progress: 100, totalItems: 1000, }); return output; }, }); ``` -------------------------------- ### Define Google Sheets Function Module (TypeScript) Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md An example of a TypeScript module file (`functions/sheets.ts`) that defines a Google Sheets related function using the Dibbla SDK. It includes input and output schema definitions using Zod and exports the function for use in other parts of the project. This promotes modularity and code organization. ```typescript import * as sdk from '@dibbla-agents/sdk-ts'; import { z } from 'zod'; const ReadSheetsInput = z.object({ url: z.string(), }); const ReadSheetsOutput = z.object({ data: z.array(z.array(z.string())), }); export const readSheetsFn = sdk.newFunction({ name: 'read_sheets', version: '1.0.0', description: 'Read from Google Sheets', input: ReadSheetsInput, output: ReadSheetsOutput, handler: async (input, event, state) => { // ... implementation }, }); ``` -------------------------------- ### Create Server Instance in TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Initializes the Dibbla Agents SDK server instance. Configures server name, API token, gRPC address, TLS settings, and concurrency/buffer options. This is the entry point for registering and running workflow functions. ```typescript import * as sdk from '@dibbla-agents/sdk-ts'; const server = sdk.create({ serverName: 'my-custom-worker', serverApiToken: process.env.SERVER_API_TOKEN, grpcServerAddress: 'grpc.dibbla.com:443', // optional, defaults to grpc.dibbla.com:443 useTLS: true, // optional, auto-detected based on address handlersConcurrency: 8, // optional, default: 8 incomingEventsBuffer: 100, // optional, default: 100 grpcReconnectIntervalSec: 5, // optional, default: 5 grpcHealthcheckIntervalSec: 30, // optional, default: 30 pingIntervalSec: 30, // optional, default: 30 }); ``` -------------------------------- ### Configure Dibbla SDK Server Connection Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Illustrates different ways to configure the Dibbla SDK server connection, including default TLS, local development without TLS, and forcing TLS. ```typescript // Minimal configuration - uses grpc.dibbla.com:443 with TLS (recommended) const server = sdk.create({ serverName: 'my-worker', serverApiToken: 'your-token', }); // Local development - uses localhost without TLS const server = sdk.create({ serverName: 'my-worker', grpcServerAddress: 'localhost:50051', }); // Force TLS on for localhost (advanced) const server = sdk.create({ serverName: 'my-worker', grpcServerAddress: 'localhost:9090', useTLS: true, }); ``` -------------------------------- ### Key-Value Store Operations for Workflow Data Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md This snippet demonstrates basic interaction with the key-value store provided by the SDK. It shows how to retrieve a string value using `globalState.store?.getString` and how to set a string value using `globalState.store?.setString`. The store is scoped to individual workflows, allowing for persistent data management associated with specific execution contexts. ```typescript // Get a value const value = await globalState.store?.getString(event.workflow, 'my-key'); // Set a value await globalState.store?.setString(event.workflow, 'my-key', 'my-value'); ``` -------------------------------- ### OAuth Token Access in TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Demonstrates how to access OAuth tokens within a workflow function to interact with external services like Google API. It shows how to request a token, handle potential errors, and use the token in an API request. Status events are sent during the process. ```typescript const CallGoogleAPIInput = z.object({ query: z.string(), }); const CallGoogleAPIOutput = z.object({ data: z.string(), }); const callGoogleAPIFn = sdk.newFunction({ name: 'call_google_api', version: '1.0.0', description: 'Call Google API on behalf of user', input: CallGoogleAPIInput, output: CallGoogleAPIOutput, handler: async (input, event, state) => { // Send status update await state.rpc?.sendStatusEvent(event, 'Requesting Google OAuth token...'); // Get access token (automatically refreshed if expired) const token = await state.oauth?.getAccessToken('google', event.run); if (!token) { throw new Error('Please connect your Google account first'); } // Use token with Google APIs await state.rpc?.sendStatusEvent(event, 'Calling Google API...'); const response = await fetch('https://www.googleapis.com/drive/v3/files', { headers: { 'Authorization': `Bearer ${token.accessToken}`, }, }); if (!response.ok) { throw new Error(`API request failed: ${response.status}`); } const data = await response.json(); await state.rpc?.sendStatusEvent(event, 'Google API call completed'); return { data: JSON.stringify(data), }; }, }); server.registerFunction(callGoogleAPIFn); ``` -------------------------------- ### Define a Simple Dibbla Function Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Shows how to define a 'simple' function in the Dibbla SDK, suitable for basic input-to-output transformations. It requires name, version, description, input/output schemas, and a handler. ```typescript const fn = sdk.newSimpleFunction({ name: 'my-function', version: '1.0.0', description: 'A simple function', input: MyInputSchema, output: MyOutputSchema, handler: (input) => { // Your logic here return output; }, tags: ['tag1', 'tag2'], // Optional - see note below }); ``` -------------------------------- ### Check Connected OAuth Providers in TypeScript Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Shows how to check which OAuth providers a user has connected using `globalState.oauth?.getConnectedProviders(event.run)`. This is useful for validating user connections before attempting to retrieve access tokens. ```typescript const providers = await globalState.oauth?.getConnectedProviders(event.run); // Returns: { google: { connected: true, email: "user@gmail.com", ... }, ... } if (!providers?.google?.connected) { throw new Error('Please connect your Google account to use this feature'); } ``` -------------------------------- ### Define Greeting Function with Zod Schema Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt This TypeScript code defines a simple greeting function using the Dibbla Agents SDK. It utilizes Zod for input and output schema validation, ensuring type safety and automatic data validation. The function takes a 'name' string and returns a 'message' string. ```typescript // functions/greeting.ts import * as sdk from '@dibbla-agents/sdk-ts'; import { z } from 'zod'; export const greetingFn = sdk.newSimpleFunction({ name: 'greeting', version: '1.0.0', description: 'Generate greeting', input: z.object({ name: z.string() }), output: z.object({ message: z.string() }), handler: (input) => ({ message: `Hello, ${input.name}!` }), }); ``` -------------------------------- ### Aggregate and Export Modular Functions Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt This TypeScript code acts as a barrel file, consolidating functions defined in separate modules (like greeting and math) into a single export point. It imports individual functions and then exports an array containing all registered functions, simplifying their import in other parts of the application. ```typescript // functions/index.ts export { greetingFn } from './greeting'; export { addFn } from './math'; import { greetingFn } from './greeting'; import { addFn } from './math'; export const all = [greetingFn, addFn]; ``` -------------------------------- ### Define Add Function with Zod Schema Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt This TypeScript code defines a simple addition function using the Dibbla Agents SDK. Similar to the greeting function, it employs Zod for robust input and output schema validation. The function accepts two numbers ('a' and 'b') and returns their sum. ```typescript // functions/math.ts export const addFn = sdk.newSimpleFunction({ name: 'add', version: '1.0.0', description: 'Add two numbers', input: z.object({ a: z.number(), b: z.number() }), output: z.object({ result: z.number() }), handler: (input) => ({ result: input.a + input.b }), }); ``` -------------------------------- ### Barrel File for Exporting Functions (TypeScript) Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Illustrates a barrel file (`functions/index.ts`) in TypeScript that re-exports functions from various module files within a project. It provides individual exports for specific functions and a convenience `all` array containing all exported functions for bulk registration. This pattern simplifies imports and manages the project's public API. ```typescript export { readSheetsFn, writeSheetsFn } from './sheets'; export { sendEmailFn } from './email'; export { formatDateFn, parseJsonFn } from './utils'; // Import for the `all` array import { readSheetsFn, writeSheetsFn } from './sheets'; import { sendEmailFn } from './email'; import { formatDateFn, parseJsonFn } from './utils'; // All functions for bulk registration export const all = [ readSheetsFn, writeSheetsFn, sendEmailFn, formatDateFn, parseJsonFn, ]; ``` -------------------------------- ### Check Connected OAuth Providers with TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Defines and registers a function to retrieve a list of connected OAuth providers for a user. It returns the provider name, email, last used timestamp, and scopes. This function requires the OAuth client to be available in the state. Dependencies include 'zod' for schema validation. ```typescript const CheckProvidersInput = z.object({}); const CheckProvidersOutput = z.object({ providers: z.array(z.object({ name: z.string(), email: z.string(), lastUsed: z.number().nullable(), scopes: z.string(), })), }); const checkProvidersFn = sdk.newFunction({ name: 'check_connected_providers', version: '1.0.0', description: 'Check which OAuth providers user has connected', input: CheckProvidersInput, output: CheckProvidersOutput, handler: async (_input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Checking connected OAuth providers...'); if (!state.oauth) { throw new Error('OAuth client not available'); } const providersMap = await state.oauth.getConnectedProviders(event.run); const providers = Object.entries(providersMap).map(([name, status]) => ({ name, email: status.email, lastUsed: status.lastUsed, scopes: status.scopes, })); await state.rpc?.sendStatusEvent(event, `Found ${providers.length} connected provider(s)`); return { providers }; }, }); server.registerFunction(checkProvidersFn); ``` -------------------------------- ### Read Google Sheets Data using TypeScript SDK Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt This function reads data from a Google Sheet using its URL. It requires authentication via OAuth with Google and fetches spreadsheet metadata and sheet contents. The output includes the spreadsheet title, ID, and detailed content of each sheet, with cell values mapped using A1 notation. It uses the Zod library for input/output validation and the `fetch` API for making requests to the Google Sheets API. ```typescript const ReadSheetsInput = z.object({ url: z.string().describe('Google Sheets URL'), }); const ReadSheetsOutput = z.object({ title: z.string(), spreadsheetId: z.string(), sheetContents: z.array(z.object({ sheetName: z.string(), cells: z.string(), // JSON mapping A1 notation to values rowCount: z.number(), colCount: z.number(), })), }); function parseSpreadsheetId(url: string): string { const match = url.match(//spreadsheets\/d\/([a-zA-Z0-9-_]+)/); if (!match) { throw new Error('Invalid Google Sheets URL'); } return match[1]; } const readSheetsFn = sdk.newFunction({ name: 'read_google_sheets', version: '1.0.0', description: 'Read data from Google Sheets', input: ReadSheetsInput, output: ReadSheetsOutput, handler: async (input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Reading Google Sheets...', { url: input.url }); const spreadsheetId = parseSpreadsheetId(input.url); const token = await state.oauth?.getAccessToken('google', event.run); if (!token) { throw new Error('Google account not connected'); } // Get spreadsheet metadata const metadataUrl = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}`; const metadataRes = await fetch(metadataUrl, { headers: { 'Authorization': `Bearer ${token.accessToken}` }, }); if (!metadataRes.ok) { throw new Error(`Failed to fetch spreadsheet: ${metadataRes.status}`); } const metadata = await metadataRes.json(); const sheetContents = []; // Read each sheet for (const sheet of metadata.sheets) { await state.rpc?.sendStatusEvent(event, `Reading sheet: ${sheet.properties.title}`); const valuesUrl = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${encodeURIComponent(sheet.properties.title)}`; const valuesRes = await fetch(valuesUrl, { headers: { 'Authorization': `Bearer ${token.accessToken}` }, }); const valuesData = await valuesRes.json(); const values = valuesData.values || []; // Convert to A1 notation const cells: Record = {}; values.forEach((row: string[], rowIdx: number) => { row.forEach((value: string, colIdx: number) => { if (value) { const col = String.fromCharCode(65 + colIdx); cells[`${col}${rowIdx + 1}`] = value; } }); }); sheetContents.push({ sheetName: sheet.properties.title, cells: JSON.stringify(cells), rowCount: values.length, colCount: values[0]?.length || 0, }); } await state.rpc?.sendStatusEvent(event, 'Finished reading Google Sheets'); return { title: metadata.properties.title, spreadsheetId, sheetContents, }; }, }); server.registerFunction(readSheetsFn); ``` -------------------------------- ### Register Advanced Functions with Context in TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Defines and registers an advanced workflow function that utilizes the workflow context, including state management for caching. The handler performs addition, checks cache, and updates cache if the value is not found. It demonstrates accessing event details and using the cache. ```typescript const AddWithCacheInput = z.object({ a: z.number(), b: z.number(), }); const AddWithCacheOutput = z.object({ result: z.number(), cached: z.boolean(), }); const addWithCacheFn = sdk.newFunction({ name: 'add_with_cache', version: '1.0.0', description: 'Add two numbers with caching', input: AddWithCacheInput, output: AddWithCacheOutput, handler: async (input, event, state) => { // Access event information console.log(`Workflow: ${event.workflow}, Run: ${event.run}`); // Use cache const cacheKey = `${input.a}+${input.b}`; const cached = await state.cache?.getByString(cacheKey); if (cached) { return { result: JSON.parse(cached.toString()).result, cached: true, }; } const result = input.a + input.b; await state.cache?.setByString(cacheKey, Buffer.from(JSON.stringify({ result })), 300); return { result, cached: false }; }, cacheTTLMs: 5 * 60 * 1000, // 5 minutes cache TTL }); server.registerFunction(addWithCacheFn); ``` -------------------------------- ### Define Schemas with Zod in TypeScript Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Defines input and output schemas for a function using Zod. The `ReadSheetsInput` schema expects a Google Sheets URL, and the `ReadSheetsOutput` schema defines the structure for returning spreadsheet data, including title, row count, and cell values. ```typescript import * as sdk from '@dibbla-agents/sdk-ts'; import { z } from 'zod'; // Input: just the Google Sheets URL const ReadSheetsInput = z.object({ url: z.string().describe('Google Sheets URL (e.g., https://docs.google.com/spreadsheets/d/1abc.../edit)'), }); // Output: the spreadsheet data const ReadSheetsOutput = z.object({ title: z.string().describe('Spreadsheet title'), data: z.array(z.array(z.string())).describe('2D array of cell values'), rowCount: z.number().describe('Number of rows'), }); ``` -------------------------------- ### Update Google Sheets with TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Defines and registers a function to update cells in a Google Sheet using the provided URL, sheet name, range, and values. It handles authentication via OAuth, makes a PUT request to the Google Sheets API, and returns the update status. Dependencies include 'zod' for schema validation and 'fetch' for API calls. ```typescript const UpdateSheetsInput = z.object({ url: z.string(), sheetName: z.string(), range: z.string().describe('A1 notation like "A1" or "A1:C3"'), values: z.string().describe('JSON 2D array like [["a", "b"], ["c", "d"]]'), }); const UpdateSheetsOutput = z.object({ updatedRange: z.string(), updatedRows: z.number(), updatedColumns: z.number(), updatedCells: z.number(), spreadsheetId: z.string(), }); const updateSheetsFn = sdk.newFunction({ name: 'update_google_sheets', version: '1.0.0', description: 'Update cells in Google Sheets', input: UpdateSheetsInput, output: UpdateSheetsOutput, handler: async (input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Updating Google Sheets...', { sheetName: input.sheetName, range: input.range, }); const spreadsheetId = parseSpreadsheetId(input.url); const token = await state.oauth?.getAccessToken('google', event.run); if (!token) { throw new Error('Google account not connected'); } // Parse values JSON let values: unknown[][]; try { values = JSON.parse(input.values); } catch { throw new Error('Invalid values JSON'); } // Update via API const fullRange = `${input.sheetName}!${input.range}`; const encodedRange = encodeURIComponent(fullRange); const apiUrl = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${encodedRange}?valueInputOption=USER_ENTERED`; const response = await fetch(apiUrl, { method: 'PUT', headers: { 'Authorization': `Bearer ${token.accessToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ range: fullRange, values }), }); if (!response.ok) { const error = await response.text(); throw new Error(`Update failed: ${error}`); } const result = await response.json(); await state.rpc?.sendStatusEvent(event, 'Google Sheets updated successfully', { updatedCells: result.updatedCells, }); return { updatedRange: result.updatedRange, updatedRows: result.updatedRows, updatedColumns: result.updatedColumns, updatedCells: result.updatedCells, spreadsheetId: result.spreadsheetId, }; }, }); server.registerFunction(updateSheetsFn); ``` -------------------------------- ### Register Simple Functions in TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Defines and registers a simple workflow function using Zod for input/output validation. The handler performs a basic string manipulation. This function type is suitable for straightforward transformations without needing workflow context. ```typescript import { z } from 'zod'; // Define schemas const GreetingInput = z.object({ name: z.string().describe('Name to greet'), }); const GreetingOutput = z.object({ message: z.string().describe('The greeting message'), }); // Create simple function const greetingFn = sdk.newSimpleFunction({ name: 'greeting', version: '1.0.0', description: 'Generate a greeting message', input: GreetingInput, output: GreetingOutput, handler: (input) => ({ message: `Hello, ${input.name}!`, }), tags: ['utility', 'greeting'], // optional }); // Register and start server.registerFunction(greetingFn); await server.start(); ``` -------------------------------- ### Define an Advanced Dibbla Function Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Demonstrates defining an 'advanced' function in the Dibbla SDK. This type of function provides access to workflow context, global state (cache, store), and OAuth. ```typescript const fn = sdk.newFunction({ name: 'my-function', version: '1.0.0', description: 'An advanced function', input: MyInputSchema, output: MyOutputSchema, handler: async (input, event, globalState) => { // Access workflow info: event.workflow, event.node, etc. // Use cache: globalState.cache?.get(key) // Use store: globalState.store?.get(workflowId, key) // Use OAuth: globalState.oauth?.getAccessToken('google', event.run) return output; }, cacheTTLMs: 5 * 60 * 1000, // 5 minutes }); ``` -------------------------------- ### Send Status Messages During Long Task in TypeScript Source: https://context7.com/dibbla-agents/sdk-ts/llms.txt Illustrates how to send status updates to the RPC client during a long-running operation using the Dibbla Agents SDK. This function takes the number of iterations as input and reports progress incrementally. ```typescript const LongRunningTaskInput = z.object({ iterations: z.number(), }); const LongRunningTaskOutput = z.object({ completed: z.number(), }); const longRunningTaskFn = sdk.newFunction({ name: 'long_running_task', version: '1.0.0', description: 'Demonstrates status messages during long operation', input: LongRunningTaskInput, output: LongRunningTaskOutput, handler: async (input, event, state) => { await state.rpc?.sendStatusEvent(event, 'Starting task...', { totalIterations: input.iterations, }); for (let i = 0; i < input.iterations; i++) { // Do some work await new Promise(resolve => setTimeout(resolve, 1000)); // Send progress update const progress = Math.round(((i + 1) / input.iterations) * 100); await state.rpc?.sendStatusEvent(event, `Processing: ${progress}%`, { progress, iteration: i + 1, total: input.iterations, }); } await state.rpc?.sendStatusEvent(event, 'Task completed!', { progress: 100, completed: input.iterations, }); return { completed: input.iterations }; }, }); server.registerFunction(longRunningTaskFn); ``` -------------------------------- ### Build Google Sheets Read Function (TypeScript) Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md Defines a TypeScript function `readGoogleSheetsFn` using the Dibbla SDK to read data from a Google Sheets spreadsheet. It handles OAuth authentication, API calls to Google Sheets, data extraction, and status updates via RPC events. Dependencies include the Dibbla SDK and potentially a `parseSpreadsheetId` utility function. ```typescript export const readGoogleSheetsFn = sdk.newFunction({ name: 'read_google_sheets', version: '1.0.0', description: 'Read data from a Google Sheets spreadsheet', input: ReadSheetsInput, output: ReadSheetsOutput, handler: async (input, event, state) => { // 1. Send initial status message await state.rpc?.sendStatusEvent(event, 'Connecting to Google Sheets...', { url: input.url, }); // 2. Check OAuth is available if (!state.oauth) { throw new Error('OAuth not available'); } // 3. Get the user's Google access token const token = await state.oauth.getAccessToken('google', event.run); // 4. Parse the spreadsheet ID from the URL const spreadsheetId = parseSpreadsheetId(input.url); // 5. Send progress update await state.rpc?.sendStatusEvent(event, 'Reading spreadsheet data...', { spreadsheetId, }); // 6. Call Google Sheets API const apiUrl = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}?includeGridData=true`; const response = await fetch(apiUrl, { headers: { 'Authorization': `Bearer ${token.accessToken}`, }, }); if (!response.ok) { const error = await response.text(); throw new Error(`Google Sheets API error: ${error}`); } const spreadsheet = await response.json(); // 7. Extract cell data from the first sheet const sheet = spreadsheet.sheets[0]; const rows = sheet.data[0].rowData || []; const data: string[][] = rows.map((row: any) => (row.values || []).map((cell: any) => cell.formattedValue || '') ); // 8. Send completion status await state.rpc?.sendStatusEvent(event, 'Successfully read spreadsheet', { title: spreadsheet.properties.title, rowCount: data.length, }); // 9. Return the result return { title: spreadsheet.properties.title, data, rowCount: data.length, }; }, }); ``` -------------------------------- ### Parse Google Sheets ID in TypeScript Source: https://github.com/dibbla-agents/sdk-ts/blob/main/README.md A utility function to extract the spreadsheet ID from a Google Sheets URL. It uses a regular expression to find the ID within the URL string, throwing an error if the URL format is invalid. ```typescript function parseSpreadsheetId(url: string): string { const match = url.match(/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/); if (!match) { throw new Error('Invalid Google Sheets URL'); } return match[1]; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.