# Actions, options and events Back to the skill: https://viasocket.com/docs/skill.md Contents: Find what to call; The tags on an action's keys; Flow or enabled app; Keys, versions and values; Options; Your own code with the user's connection; Events; When it goes wrong This page is how the product works in its users' apps: it reads lists from their account, runs actions, and hears about new events. Each call needs the user's `auth_id`, which they get by connecting the app (https://viasocket.com/docs/skill/connect.md). Getting each input right here means the user is never asked the same thing twice, and no action fails on a guessed value. Code names an app by its **slug** (`gmail`), an action or trigger by its **key** (`Send_Email`), and a version by its number (`v55`). It uses an `action_id` only where a page says so (a flow step, a sample event). **Event** means two things on these pages: an action or trigger (one row of the app's page), and, under "Events" below, what a trigger reports when it fires. Every function named here (`findEnabledApp`, `runAction`, …) is defined in https://viasocket.com/docs/apps-api.md: copy its module once. ## Find what to call 1. **The app:** `searchApps(name)`, apps whose name starts with the text (try the first word: "google", not "sheets"); its `appslugname` is the slug. Several matches? Show them and ask. It needs no sign-in: before the module exists, open `https://plug-service.viasocket.com/plugins/search?prefix=`. 2. **Its page,** `https://viasocket.com/docs/.md`: its sign-in, its icon, and every action and trigger in one line (add `search=` as a query parameter to filter them). Choose the action or trigger the task needs. 3. **The action's or trigger's page,** linked from the app's: its key and version, its `inputData` as a TypeScript type. Open it by its path (`send-email`); code names it by its key (`Send_Email`, exact and case-sensitive), never the path. 4. **At run time,** `listActions(userId, '')` is the same list from viaSocket itself: each event's `key`, its published `version`, every `versions` entry, and `pauses` (`null`, or why a step with it waits). Read keys from it or from the page, never from memory. ## The tags on an action's keys An action's page shows its `inputData` as a TypeScript type, with notes after some keys: - **`PICK`**: the value is an id the user picks from a list (`listOptions`), never typed. It can also come from an event or record that already names it, such as the pull request number in a pull-request event. - **`KEYS`**: an object whose keys are the `value`s from `listOptions`, one entry per chosen option. - **`after `**: this list needs those keys chosen first. Send them in `existingFields`. - **`searchable`**: the list can filter by the text the user types (`search`). - **`WHEN `**: send the key only while the condition holds. **`REQUIRED WHEN`**: then it must be sent. - **`default`** and **`format`**: the value used when the key is left out, and the shape a text value must have. ## Flow or enabled app There are two ways to run an action: - **A flow.** Use it when the action is known before it runs: fixed in the product's code, or picked by the user in a form. Make a flow with one step that calls the action (https://viasocket.com/docs/automations.md). If the product needs the result, add its own API as the next step. - **The enabled app.** Use it only when nobody knows the action until it runs, for example when the product's AI picks from tools. Enabling creates a flow for one user and connection (`auth_id`) that can run any action of that app. Enabling again creates a second flow, so look for the existing one first and save its `script_id` with the `auth_id`. An action whose `pauses` is set always needs a flow. It waits (`intervention` for a person, `delay` for a set time, `async` for the app's reply), and only a flow can continue after the wait (https://viasocket.com/docs/skill/ai-steps.md). The enabled app runs once and returns. **A `script_id` is like a password.** It runs actions as that user with no other token. Keep the `auth_id` and every `script_id` on the server, per user and connection: never in the browser, a URL, a log or client code, and never given to another user. An action's reply can contain the `script_id` too (Slack's Send Message reply carries it in its `metadata`), so never send a raw reply to the browser: pick the fields the user needs. **The product checks ownership, not viaSocket.** viaSocket checks that a connection belongs to the product, not to which of its users. So before any call, the product's server checks that the signed-in user owns the `auth_id` or `script_id` it is about to use, from its own records. A request naming someone else's id is refused. ```js const slug = '' // run an action (enable once per user and connection) const scriptId = (await findEnabledApp(userId, slug, authId)) || (await enableApp(userId, slug, authId)) // authId: this connection's flow, for a user with two connections to one app const { options } = await listOptions(userId, slug, '', { fieldKey: '', authId, existingFields }) // per PICK key const result = await runAction(scriptId, '', actionInput, { version: '' }) ``` `` is the action's key ("Find what to call"), `` its version (`v55`), and `actionInput` its `inputData`. A paused enabled app (`status: 'paused'` in the flow list) refuses every run ("Flow is currently paused"). Resume it with `setFlowStatus(userId, scriptId, 1)`; do not enable it again. Your own AI agent with the user's apps as tools (LangChain, Vercel AI SDK, any framework) runs through the enabled app: https://viasocket.com/docs/skill/agent-tools.md. ## Keys, versions and values - **One key per event.** Running, options and subscribing name an action or trigger by its key, plus a version. The sample event, automations, the prebuilt UI and Connect's `filteredActions` take the plain `action_id` / `trigger_id` instead (`action_id` in the listing, on the event's page). - **Pass the version whose fields you send.** A newer version may rename or add fields, so code that fills the `inputData` pins its version. A form the user fills sends the version it was drawn for, on `listOptions` and on the run (https://viasocket.com/docs/form-renderer.md does this). With no version, the run uses the published one, which may have changed since. The listing shows the published version and the others; any other version fails with status 404 in `errorMsg`. - **Copy keys, never type them.** Field keys are case-sensitive and differ between actions of one app (`spreadsheet_Id`, `spreadSheet_id`); nested keys are full dotted paths. - **Decide every key.** Send it or leave it out on purpose. Never drop a required key because it looks technical. - A `PICK` key, and any value that depends on the end user's own account (their workspace, personal or shared, admin or not): the end user chooses it on screen, from `listOptions`. - A value that differs on every run: the product's own data or its AI fills it. - A constant in code only when one value is right for every user; the report says why. - Never a text box for an id, and never the first option because it came first: a typed or guessed id acts on the wrong record in the user's account, or fails. - **Once, or per run.** Some `PICK` values are the same on every run for one user: their site, property, workspace, team, calendar, account or board. Ask for these **once, right after Connect**, not in every action's form: - show the list on the connection's own screen; - store the choice with the `auth_id`, show it there, and let the user change it; - fill the key from it on every run. Each event's page has a **Pickers** section for this. For each such key, it names the event and `fieldKey` that list it before any action is chosen (`Get_Site` lists `siteUrl` for Search Console). A value that changes with each run (a message, a row, a date range, a recipient) goes in the action's own form, or the product fills it. Say which in the plan table of https://viasocket.com/docs/skill/app-integrations.md. ## Options - `fieldKey` is the full dotted path (`destination.channel_id`). - `existingFields` holds the values chosen so far, nested like `inputData`; clear a key when what it depends on changes. - **Search:** send what the user types in `search`, about 300 ms after they stop typing. A `searchable` field filters on viaSocket's side; other fields ignore `search`, so filter their list in the product. New text starts a new list, with no `paginate`. - **More pages:** a long list answers `hasMore: true` and a `paginate` value. Send that value back, with the same `search` and `existingFields`, to get the next page, and add it to the list. `paginate` is `null` when there is no more. Treat it as opaque: one app uses a page number, another a cursor. Load more as the user scrolls or clicks "more", never every page up front. - A field can answer a `message` with its list, such as why it is empty or what to choose first. Show it. - Show `label`, send `value` verbatim. A `KEYS` key takes one entry per option `value`. - A once-after-Connect list (an event page's Pickers section, last column) is read the same way, from the event it names; `existingFields` holds the keys its "needs first" column lists: ```js // right after Connect: the user's Search Console sites, once, stored with the auth_id const { options } = await listOptions(userId, slug, 'Get_Site', { fieldKey: 'siteUrl', authId }) // from the event page's Pickers section // a long, searchable list, as the user types and scrolls const page = await listOptions(userId, slug, '', { fieldKey: 'spreadsheet_id', authId, existingFields, search: typed, paginate: lastPage?.paginate }) // page.options, page.hasMore, page.paginate, page.message ``` ## Your own code with the user's connection For an API the app's actions do not cover, `runCode(scriptId, code, inputData, { action })` runs a string of JavaScript where the action would run. `context.inputData` is the input and `context.authData` the connection's credentials. `axios` and `fetch` add the credentials to calls to the app's own domains, when the app's connection lists them; elsewhere, add them from `context.authData` yourself. `return` the value the caller gets. Name an `action`, and its helper functions are in scope. Prefer an action whenever one exists: custom code is the product's to fix when the app's API changes, and the report lists it as such. ## Events A subscription switches a trigger on for one user. For each event, viaSocket runs a **handler**: a string of JavaScript with `context`, `fetch` and `axios` in scope and the event at `context.req.body` (no imports). The server builds the handler when it subscribes, and it lives on viaSocket. So it may hold what it needs to act: another app's `script_id`, an action key and version, or a bearer token that the product's own events endpoint accepts for this user. Never commit or log it. Map its keys from a real event (`sampleEvent`) for the same connection, not from the page's sample. Subscribing needs only the `auth_id`; `triggerInput` is the trigger's own settings, from its page: ```js const slug = '' const { actions } = await listActions(userId, slug) const trigger = actions.find((event) => event.key === '') const event = await sampleEvent(trigger.action_id, authId, null, triggerInput) // map the handler from this const subscriptionId = await subscribeEvent(userId, slug, '', authId, triggerInput, { code: handler }, { version: '' }) ``` Send the event to the product's own API, with its own auth header, so the endpoint stays protected: ```js const handler = `await axios.post("https://your-app.com/api/viasocket-events", { event: context.req.body, user: "${userId}" }, { headers: { authorization: "Bearer ${apiKeyForThisUser}" } })` ``` Or run another app's action, with no server of the product involved. Before subscribing, enable that app for this user (its `script_id`); the key and the version are baked into the string, so update the handler when the code moves to a newer version: ```js const handler = ` const body = context.req.body const res = await axios.post("https://flow.sokt.io/func/${otherScriptId}", { action: "${otherActionKey}", version: "${otherActionVersion}", inputData: { /* built from body: keys from a real sampleEvent, values decided as above */ } }) const out = res.data const failed = typeof out?.success === "boolean" && "data" in out ? !out.success : out?.success === false if (failed) throw new Error(out?.errorMsg?.message || out?.message || "action failed") // shows in the run history return out` ``` - Save `{ userId, app, trigger_key, version, script_id, auth_id, inputData, handler }` in the product's database, in the same write that records the subscribe result. The flow list returns neither `inputData` nor the handler, so this record is the only copy. - `scheduledTime` (minutes, as a string) in `inputData` sets how often a trigger that polls checks; left out, it is `"15"`. - `{ webhook: url }` instead of `{ code }` posts each raw event to that URL, with no headers of the product's own, so the endpoint cannot tell viaSocket from anyone else. A `code` handler can send the product's own auth header instead, so use `webhook` only when the developer asks for exactly that. ## When it goes wrong | symptom | cause | | --- | --- | | 401 / invalid token | Wrong secret, a claim missing, or a `Bearer` prefix: the token goes bare. | | 404 unknown app or action, or `errorMsg.status` 404 for a version | A slug, key or version typed from memory: copy it from the page or the listing. Keys are case-sensitive; the page's path (`send-email`) is not the key. | | Empty option list | `fieldKey` is the leaf, `existingFields` is flat or misses a dependency; or the field answered a `message`: show it. | | A run fails with `Auth data not found`, or options with `Invalid authentication selected` | The connection was revoked or deleted, or the `auth_id` is not one of this product's. Don't show the raw error: show the user a Connect button for that app, then save the new `auth_id` and enable it once. | | `Flow is currently paused` | The enabled app or the flow is paused. Resume it with status `1`. | | `runAction` throws "no flow has this script_id" | The `script_id` was deleted or mistyped. Find the enabled app again, or enable it. | | The app rejects the action | An invented value for a `PICK` key, or a `WHEN` key sent while its condition is false. | | A run fails with the app's message | The reply is `400` with `errorMsg: { status, message, data }`: the app's own status and message are in there. | | The user is asked the same thing in every action | A once-per-user `PICK` (site, property, workspace) built per run: choose it once after Connect. | | Code reads `undefined` from a result or an event | The shape came from a sample, not from a real run or a real event. | | `sampleEvent` answers `"No response"` | It got a version id or a key; it takes the plain `trigger_id` (`action_id` in the listing). | | The fields changed under the code | The app published a newer version and the code names none: pin the version, or reread the page. | | The same event fires twice, or two `script_id`s for one app | Subscribed or enabled twice: check the saved record and the enabled app first. | | A user's connections seem lost | A different `userId` (`unique_identifier`) for the same person. | END OF PAGE