--- name: viasocket-automations description: >- Build a viaSocket automation from code: one trigger (an app event, a schedule or a webhook) and ordered JavaScript steps that call actions in the user’s connected apps. viaSocket runs it and keeps its history. Use it when the product’s own code builds the flow for each end user; when users build their own on ready-made screens, that is the prebuilt UI (embed.md); an automation of the product itself is my-automations. --- # Automations for each user, from the product’s code Back to the skill: https://viasocket.com/docs/skill.md Contents: The module; The trigger; The steps; Example: daily news to a sheet; After it is saved; Run history; Finished when; When it goes wrong The functions named here from outside this page (`embedToken`, `sampleEvent`, `listFlows`, `setFlowStatus`, `renameFlow`) are in the module of https://viasocket.com/docs/apps-api.md Three kinds of automation, one page each, all on the same engine. This page: the product’s code builds one per end user, on that user’s own connections. https://viasocket.com/docs/embed.md: end users build their own, in viaSocket’s ready screens inside the product. https://viasocket.com/docs/skill/my-automations.md: an automation of the product itself, in the developer’s workspace (a nightly report to the team’s Slack, one action run once from the backend), signed with the developer’s own token. Give every user of the product their own automation behind one button: “send me a summary of my inbox every day at 9”, “when a lead comes in, post it to my Slack”. The product’s code builds it for the user, from a template the developer decides, and viaSocket runs it from then on: it wakes it on the schedule or the event, calls the user’s own apps through the connections they made, retries, and keeps every run’s history for the user to see. An automation is a flow: one trigger (what starts it: an event in one of the user’s apps, a schedule, or a call from the product) and ordered steps, each a piece of JavaScript that calls the user’s apps and reads the earlier steps’ results. viaSocket runs it in its VM. A flow built here is the same kind a user builds in the prebuilt UI (https://viasocket.com/docs/embed.md): it is in their flow list and opens by its `script_id`, the id every call below takes. One event with one reaction needs no steps: subscribe to it instead, which makes a one-handler flow of its own (https://viasocket.com/docs/skill/actions-and-events.md). The path, each call a function of the module below: 1. `automationToken(userId)`: a short-lived token for this user. 2. `createFlow`: the flow, once per automation and user; keep its `script_id`. 3. `setTrigger`: what starts it. 4. `saveSteps`: what it does. Saving both puts it live. 5. `readFlow` to change it later; `runHistory` to show the user its runs. ## The module Copy it into the product’s server once; every call on this page is one of its functions. Server only. It imports `embedToken` from the apps module, https://viasocket.com/docs/apps-api.md. ```js // viasocket-automations.js (or .mjs: it is an ES module, so on a CommonJS project name it .mjs, as apps-api.md says of viasocket.js) import { embedToken } from './viasocket.js' // or './viasocket.mjs' const API = 'https://flow-api.viasocket.com' // Every call below: a real status. 400 names the field, 403 is another user's flow, 404 an unknown flow. async function call(token, method, url, body) { const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json', proxy_auth_token: token }, body: body && JSON.stringify(body) }) const text = await res.text() let payload try { payload = JSON.parse(text) } catch { payload = { message: text.slice(0, 200) } } // a 429/502 may answer text if (!res.ok) throw Object.assign(new Error(payload?.message || `${method} ${url}: ${res.status}`), { status: res.status, body: payload }) return payload.data } // Short-lived: derive it at the start of each build, edit or read; never store it. export async function automationToken(userId) { const res = await fetch(`${API}/users/register`, { headers: { authorization: embedToken(userId), ...(process.env.VIASOCKET_ORIGIN ? { Origin: process.env.VIASOCKET_ORIGIN } : {}) // an embed with a domain whitelist } }) const text = await res.text() let payload try { payload = JSON.parse(text) } catch { payload = { message: text.slice(0, 200) } } if (!res.ok) throw Object.assign(new Error(payload?.message || `automationToken: ${res.status}`), { status: res.status, body: payload }) return payload.data.token } export const createFlow = async (token, { title, description }) => // → script_id; title and description are what the user sees (await call(token, 'POST', `${API}/automations`, { title, description })).script_id export const setTrigger = (token, scriptId, trigger) => // trigger: one of the shapes under "The trigger" → { script_id, triggerType, status, … } call(token, 'POST', `${API}/automations/${scriptId}/trigger`, trigger) export const saveSteps = (token, scriptId, steps) => // replaces the whole array, then publishes → the flow, as readFlow call(token, 'POST', `${API}/automations/${scriptId}/steps`, { steps }) export const readFlow = (token, scriptId) => // { script_id, title, status, trigger, steps, variables, version, webhook_url_of_flow } call(token, 'GET', `${API}/automations/${scriptId}`) export async function runHistory(token, scriptId, { page = 1, limit = 40, count = false } = {}) { // newest first, kept 14 days (30 for a failed or paused run) const url = `${API}/logs/orgId/${process.env.VIASOCKET_ORG_ID}?projectId=${process.env.VIASOCKET_PROJECT_ID}&scriptId=${scriptId}&page=${page}&limit=${limit}${count ? '&getCount=true' : ''}` const res = await fetch(url, { headers: { proxy_auth_token: token } }) if (!res.ok) throw new Error(`runHistory: ${res.status}`) // 403: another user's flow return (await res.json()).data // count: { successCount, failedCount } } ``` | function | request | | --- | --- | | `automationToken(userId)` | `GET https://flow-api.viasocket.com/users/register`, header `authorization: ` → `data.token` | | `createFlow` | `POST https://flow-api.viasocket.com/automations` `{ title, description }`, header `proxy_auth_token` | | `setTrigger` | `POST https://flow-api.viasocket.com/automations//trigger` `{ triggerType, … }`, header `proxy_auth_token` | | `saveSteps` | `POST https://flow-api.viasocket.com/automations//steps` `{ steps }`, header `proxy_auth_token` | | `readFlow` | `GET https://flow-api.viasocket.com/automations/`, header `proxy_auth_token` | | `runHistory` | `GET https://flow-api.viasocket.com/logs/orgId/?projectId=&scriptId=&page=1&limit=40`, header `proxy_auth_token` | - `proxy_auth_token` is that user’s own token for viaSocket: not the developer’s login, and not the 36Blocks session of login-and-orgs, which uses the same header name. It builds and changes flows as that user: server only. - The same `/automations` routes build the product’s own flows, in the developer’s workspace, with the developer’s agent token (`VIASOCKET_AGENT_TOKEN`, written by setup) in the `Authorization` header instead of `proxy_auth_token` (one header, never both): https://viasocket.com/docs/skill/my-automations.md. - An embed with allowed domains (the **Whitelist domains** card on the embed’s Configuration page in viaSocket) needs `VIASOCKET_ORIGIN` set to an origin on one of them or a subdomain (`https://app.example.com` for `example.com`), or `automationToken` answers 403 “Origin not allowed by whitelist”. - **One flow per automation.** Create it once, keep its `script_id`, send every change to it. - Saving the trigger and the steps publishes the flow (it is `draft` until then); there is no publish call. - **`saveSteps` replaces the whole array**: a step left out is deleted. To edit, `readFlow`, change its `steps`, and send them all back — this also keeps steps the user added in the prebuilt UI. ## The trigger | `setTrigger(token, scriptId, …)` | starts when | the steps read at `context.req.body` | | --- | --- | --- | | `{ triggerType: "plugin", trigger_id, auth_id, inputData }` | an event in a connected app | the event as the app sent it | | `{ triggerType: "cron", cronStatement: "Every day at 9am", timezone: "Asia/Kolkata" }` | on a schedule (plain words or five-field cron; `timezone` optional; left out, the product’s own workspace zone, the same for every user: send the user’s zone for their local time) | nothing; use `new Date()` | | `{ triggerType: "webhook" }` | the product POSTs to `https://flow.sokt.io/func/` | the POST body; the caller gets the last step’s return value | | `{ triggerType: "webhook", runOncePerItem: true }` | the same, once per element of the posted array | one element, and none of the caller’s headers (a key check goes in `transformCode`); the caller gets `Flow Queued`, each run’s result is in `runHistory` | | `{ triggerType: "webhook", runOncePerItem: true, arrayKey: "items" }` | the same, the array sits under `items` | one element of `body.items` | - `plugin`: `trigger_id` and the typed `inputData` come from the trigger’s page, `https://viasocket.com/docs//.md`; `auth_id` is the user’s connection (`"NoAuth"` for an app without sign-in). Map the steps from `sampleEvent(trigger_id, auth_id, authType)` (`authType`: the app’s `service.auth_type`) for that connection and `inputData` (https://viasocket.com/docs/skill/actions-and-events.md). viaSocket registers its own hook with the app and fills `inputData.hookUrl` itself: never send it. Saving it subscribes with the app and fetches one live sample event from it, so `setTrigger` can take some seconds: give it no short timeout of your own. The event is subscribed with the app the moment `setTrigger` answers, steps or no steps; deleting the flow (status `0`) ends it. `setTrigger` answers that same event as `sampleData` (`readFlow` shows it too): the one the flow builder shows for the trigger. - `cron`: unreadable text is refused. `readFlow` returns the schedule in viaSocket’s words (`"At 9:00 AM every day"`): compare the meaning, not the text. `timezone` left out means the product’s own workspace zone, the same for every user; a name that is not a real IANA zone is refused when the trigger is saved (`Cron add failed`), so send one such as `Europe/London`. - `webhook`, two more options: `transformCode: "return context.req.body.orders.filter(o => o.paid)"` builds the array to run per element from the whole body; `customResponse: ""` answers the caller with that text instead of the last step’s return (not with per-item runs). - No trigger for what is needed? Use `cron` plus a step that fetches only new items, remembering the last one in the Memory action (key-value storage). An event the app pushes that the catalog lacks is also reported: https://viasocket.com/docs/skill/feedback.md, “When viaSocket lacks it”. ## The steps `saveSteps` takes `[{ stepname, code, service_action_functions }]`: | field | rule | | --- | --- | | `stepname` | lowercase letters, digits, `_`; starts with a letter; unique. Later steps read its return value at `context.res.` | | `code` | one JavaScript string; its `return` value is the step’s result | | `service_action_functions` | every action the code calls, as `{ name, auth_id, action_id }`: `name` is what the code calls it, `action_id` comes from the action’s page (never its version id), `auth_id` is the user’s connection to that app. `[]` for a step that only decides or transforms. A step has no version field: it runs the version the action had when the steps were saved, so save them again to move to a newer one | Every key of a trigger’s or an action’s `inputData` is decided as https://viasocket.com/docs/skill/actions-and-events.md says: - a `PICK` key, or a choice that depends on the user’s own account (their workspace, personal or shared), is the user’s, on screen, before the flow is created; - a constant only when one value is right for every user, said in the report; - never the first option because it came first. A page’s sample was recorded on another account: map `context.req.body` and `context.res.` from a real `sampleEvent` and a real run on the test connection, never from the sample. ```js // A registered action, called by its name with the inputData typed on its page (here Slack’s Send Message): const sent = await sendMessage({ inputData: { destination: { messageto: "channel", channel_id: ["C0123ABCD"] }, markdown_content: `New lead: ${context?.req?.body?.name}` }}) // context is read-only; read by full path where used: context?.req?.body // the trigger’s payload context?.res?.fetch_news // an earlier step’s result // fetch and axios are in scope, so any HTTP API works, the product’s own included: return await axios.post("https://your-product.com/api/hook", { id: sent?.ts }, { headers: { "x-key": "" } }) ``` The VM: - In scope: the registered actions, `context`, `fetch`, `axios`, `await`. No `import`, no npm packages. - **58 seconds per run.** Then it is aborted. Never sleep in code: the Delay action, and actions that wait for a person, pause the run outside the limit. Longer work is split across runs (a schedule, or one flow calling another’s webhook). AI work that may take longer, or that can wait to cost less, is the Run AI Model in Background action: https://viasocket.com/docs/skill/ai-steps.md. - **A failed step does not stop the run.** Its result becomes `{ "error": {} }` (the message is in the run history), later steps still run, and a webhook caller still gets 200. Check `context.res.?.error` before using a result. Let an error throw: a `try/catch` that swallows it records the step as successful, with no `error` to check. - An early `return` ends only that step. `console.log` writes the run history; markdown with real values reads well; no secrets. - App lists arrive paged; loop when you need everything. - Runs overlap and events repeat: before an act that must not happen twice, check a record (the app’s state, an idempotency key, or Memory). - Text that varies per input (replies, summaries) is the Run AI Model action’s job; code does calculation and mapping. - An action that waits (for a person: Send Approval Email of the `email` app; a set time: Delay; or an app’s later reply) pauses the run; the answer is at `context.res.` when it continues, and a webhook caller never sees it: https://viasocket.com/docs/skill/ai-steps.md. - One decision or action per step, so the history shows each branch and an edit touches one step. Run AI Model, Delay and Memory need no search: https://viasocket.com/docs/skill/built-in-actions.md. Run AI Model returns `{ content, model, message_id, finish_reason, credits_used, images }`; `content` is a string (JSON text when `response_type` is `json_object`, which also needs `response_json_structure`: the shape wanted, as a JSON string). ## Example: daily news to a sheet ```js import { automationToken, createFlow, setTrigger, saveSteps } from './viasocket-automations.js' // or .mjs, as above const fetchNews = ` return await runAiModel({ inputData: { query: "Look up today's major news. Return up to 10 stories.", prompt: "Return ONLY valid JSON: { news: [{ date, headline, summary, url }] }.", response_type: "json_object", response_json_structure: '{"news":[{"date":"","headline":"","summary":"","url":""}]}' }})` const storeNews = ` if (context?.res?.fetch_news?.error) return { skipped: true } const news = JSON.parse(context?.res?.fetch_news?.content || "{}").news || [] if (!news.length) return { skipped: true } const result = await addMultipleRows({ inputData: { spreadSheet_Id: "${spreadsheetId}", sheet_id: "${sheetId}", use_json_rows: true, rows_json: JSON.stringify(news) }}) console.log('### Stored ' + (result?.appendedRows || 0) + ' rows') return result` const token = await automationToken(userId) const scriptId = await createFlow(token, { title: 'Daily news', description: 'Every day at 8am, today’s news into the sheet.' }) await setTrigger(token, scriptId, { triggerType: 'cron', cronStatement: 'Every day at 8am' }) await saveSteps(token, scriptId, [ { stepname: 'fetch_news', code: fetchNews, service_action_functions: [{ name: 'runAiModel', auth_id: 'NoAuth', action_id: 'rowskkqydb6f' }] }, { stepname: 'store_news', code: storeNews, service_action_functions: [{ name: 'addMultipleRows', auth_id: sheetsAuthId, action_id: 'rowfudy5tu2q' }] } ]) ``` Values fixed for this user (the sheet’s ids) are baked into the code when it is saved; values that vary per run come from `context`. ## After it is saved - **It runs** from that moment (`plugin`, `cron`), or on each POST (`webhook`). - **The same automation for every user**: create one flow per user, with that user’s `auth_id`s and on-screen choices. - **The user sees it** in the prebuilt UI, `open: { flowId: "" }`, with its runs in the History tab. - **List, pause, resume, delete**: `listFlows`, `setFlowStatus` and `renameFlow` (https://viasocket.com/docs/skill/manage.md); pause every flow on a connection (status `2`) before revoking it. - **Change it**: `readFlow`, edit, `saveSteps` (whole), the same `script_id`. On a paused flow the save is kept but publishing answers 400 `The flow can’t be published because it’s paused`: resume it (status `1`) first. - **Delete is a bin**: status `0` stops the trigger and keeps the flow for 7 days, when it is removed for good with its steps; `1` within those days restores it. `listFlows` returns drafted, paused and binned flows too, each with its `status` (the listing says `drafted` where `createFlow` and `readFlow` say `draft`). A title is at most 75 characters. `createFlow` has no idempotency key: list first, create once. - **Limits**: no rate limit on these calls (a 429 reaches a flow only from the AI service behind Run AI Model); each run has 58 seconds of code and the paid actions need credits (the built-in page says what a 402 means). ## Run history `runHistory(token, scriptId)` → an object whose `.finalResponse` array holds the runs, newest first, kept 14 days (30 for a failed or paused run); `{ count: true }` → `{ successCount, failedCount }`. Another user’s flow answers 403. Show users these fields, never the raw entry (its `requestSnapshot` holds request headers, location included): | field | meaning | | --- | --- | | `status` | `success`, or `failed` when any step failed | | `createdAt` | when it ran | | `console` | each step’s logs; a failed step’s error message | | `stepOrderJsonData` | per step, in order: `id` (step name), `status` (200 / 400), `timeTaken` | | `output` | the last step’s result, as a JSON string | | `flowHitId` | the run’s id: `open: { flowId, flowHitId }` shows it in the prebuilt UI | ## Finished when 1. `automationToken` returned a token for the test user (https://viasocket.com/docs/skill/test-connection.md). 2. `createFlow`, `setTrigger` and `saveSteps` returned without throwing, and `readFlow` shows the trigger and every step by name. 3. With a `plugin` trigger: `sampleEvent` returned a real event holding every `context.req.body` path the steps read. 4. It ran once (the webhook was POSTed, the schedule passed, or the event was caused), and the effect or `runHistory` shows it. 5. `npx -y viasocket-apps check ` passed with 0 FAIL; it also resolves every `trigger_id` and `action_id` the flow uses. ## When it goes wrong | symptom | cause | | --- | --- | | `automationToken` 401 | The embed token’s secret or ids are wrong. | | `automationToken` 403 `Origin not allowed` | The embed has a domain whitelist: set `VIASOCKET_ORIGIN` to an allowed origin. | | A call throws about the token | It expired, is missing, or belongs to another project. Derive a fresh one. | | `setTrigger` aborts with a timeout of the caller’s | A `plugin` trigger fetches a live sample from the app, which can take seconds. Let the call finish; an abort is not a refusal, so `readFlow` first, then retry. | | A call throws with a message | Refused: 400 names the field (an unreadable `cronStatement`, a missing `auth_id`, an `action_id` that does not exist), 403 is another user’s flow, 404 an unknown `scriptId`. A refused `saveSteps` changes nothing: the steps saved before stay live. | | `setTrigger` rejects the id | A `trigger_version_id` was sent, or fields that do not match `triggerType`. | | A step’s action never runs | An `action_version_id` in `service_action_functions`. | | ` is not defined` | That name is not registered in the step’s `service_action_functions`. | | A step fails inside the action | `inputData` keys not from the action’s page, or another app’s or user’s `auth_id`. | | `undefined` from `context.req.body` | Keys guessed instead of mapped from a real event. | | `undefined` from `context.res` | The earlier step failed (`{ "error": {} }`), returned nothing on that path, or its `stepname` differs. | | A run answers 400 `Flow aborted because of the 58 seconds execution limit` | Use the Delay action or split the work across runs. | | A run answers 400 `Flow is currently paused` / `Flow has been deleted` | `setFlowStatus(userId, scriptId, 1)` resumes or restores it. | | Steps disappeared after an edit | Only the changed step was sent; send the whole array. | | The flow is missing in the prebuilt UI | Built for another user, or the UI was mounted with `showEnabled: false`. | END OF PAGE