@moxxy/factorix-plugin-sdk 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moxxy Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # Factorix plugin SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build plugins for [Factorix](https://github.com/WebEferen/factorix). The SDK lives in the Factorix repository under `packages/plugin-sdk` and is published to npm from there. A plugin is a server you run. Factorix calls it at one address, and it can add:
4
+
5
+ - **A tracker.** Factorix follows issues from your service the way it follows Linear or Jira: it syncs them, assigns agents through labels, moves statuses, and comments.
6
+ - **Pages.** Entries in Factorix's sidebar or under Settings that open your own HTML in a frame, with forms that post back to your plugin.
7
+ - **Settings.** Fields an organization's admin fills in for your plugin, rendered by Factorix from your manifest.
8
+ - **Work for agents.** With the permissions an organization's admin allows, a plugin reads what happened on its tickets and asks its agents for work.
9
+
10
+ Your code never runs inside Factorix, and Factorix's database and session never reach your plugin. What the plugin gets is the connection an admin made for it, the settings an organization saved for it, and the calls its permissions allow.
11
+
12
+ Plugins that ship with Factorix live in its `plugins/` folder, one folder each, and Factorix starts and installs them by itself. `plugins/digest` is a complete one: a sidebar page, its own tables, a schedule, and an agent that writes each day's digest. The guide to building, installing, and configuring plugins is `docs/plugins.md` in the Factorix repository. This README covers the SDK itself.
13
+
14
+ ## A plugin in one file
15
+
16
+ ```ts
17
+ import { definePlugin } from '@moxxy/factorix-plugin-sdk'
18
+ import { serve } from '@moxxy/factorix-plugin-sdk/node'
19
+
20
+ const plugin = definePlugin({
21
+ name: 'Acme board',
22
+ version: '1.0.0',
23
+ connection: {
24
+ fields: [
25
+ { key: 'site', label: 'Site', type: 'url', required: true },
26
+ { key: 'token', label: 'API token', type: 'secret', required: true },
27
+ ],
28
+ },
29
+ settings: { fields: [{ key: 'region', label: 'Region', type: 'text' }] },
30
+ permissions: ['activity:read'],
31
+ pages: [{ key: 'reports', label: 'Reports', render: (context) => `<h1>Hello ${context.account.name}</h1>` }],
32
+ tracker: (connection) => new AcmeTracker(connection.config.site, connection.secrets.token),
33
+ })
34
+
35
+ await serve(plugin, { secret: process.env.PLUGIN_SECRET, port: 8787 })
36
+ ```
37
+
38
+ Outside the Factorix repository, `npm install @moxxy/factorix-plugin-sdk`. `tracker` returns an object with the methods of the `Tracker` type. `examples/memory-tracker.ts` is a complete one that keeps its issues in memory. From the Factorix repository:
39
+
40
+ ```sh
41
+ PLUGIN_SECRET=$(openssl rand -hex 24) yarn workspace @moxxy/factorix-plugin-sdk example
42
+ ```
43
+
44
+ `createHandler(plugin, { secret })` gives the same thing as a `(Request) => Promise<Response>` function, for any runtime that is not plain Node.
45
+
46
+ ## Installing it in Factorix
47
+
48
+ A plugin in Factorix's own `plugins/` folder is installed by Factorix itself, see `docs/plugins.md`. One that runs anywhere else:
49
+
50
+ 1. Run the plugin somewhere Factorix can reach, behind HTTPS. Connection secrets travel to this address, and people's browsers open its pages there too.
51
+ 2. An installation admin opens Settings, Plugins, chooses Install plugin, and enters the address (ending in `/factorix`) and the secret the plugin was started with.
52
+ 3. An organization's admin turns the plugin on there, sees the permissions it asks for, and fills in its settings.
53
+ 4. For a tracker: Settings, Connections, Add, kind Plugin. Then create a project on that connection.
54
+
55
+ After you release a new version with a changed manifest, press Refresh on the plugin's row.
56
+
57
+ ## Events
58
+
59
+ Without events Factorix polls a tracker every few minutes. To tell it sooner, implement `registerWebhook`, remember the `url` it is given, and send events there:
60
+
61
+ ```ts
62
+ import { factorix } from '@moxxy/factorix-plugin-sdk'
63
+
64
+ const fx = factorix({ url: 'https://factorix.example.com', secret: process.env.PLUGIN_SECRET })
65
+ await fx.sendEvent(callbackUrl, { kind: 'issue.upserted', issue: { id: 'issue-12' } }, deliveryId)
66
+ ```
67
+
68
+ Factorix trusts only the issue's id in an event and reads the rest back through `getIssue`.
69
+
70
+ ## Pages
71
+
72
+ A page's address carries a `factorix` parameter: who opened it, their organization, the plugin's id in that Factorix, and the plugin's settings, signed and good for five minutes. The SDK checks it before `render` runs. `render` also gets the token itself, so the page's own requests can send it back (as `?factorix=` or an `x-factorix-page` header) and be checked the same way with `readPageToken`.
73
+
74
+ A form on the page posts to the page's own address, which reaches its `action`. Put the token in the form's address and answer with a redirect back to the page:
75
+
76
+ ```ts
77
+ {
78
+ key: 'notes',
79
+ label: 'Notes',
80
+ render: (context, request, token) => `<form method="post" action="?factorix=${token}"><input name="note"><button>Save</button></form>`,
81
+ async action(context, request, token) {
82
+ if (context.account.role !== 'admin') return new Response('Admins only', { status: 403 })
83
+ await save(context.org.id, (await request.formData()).get('note'))
84
+ return new Response(null, { status: 303, headers: { location: `?factorix=${token}` } })
85
+ },
86
+ }
87
+ ```
88
+
89
+ The page runs in a sandboxed frame on your own address. It cannot read Factorix's cookies or navigate its window. Its link stops working after five minutes, so a page left open that long asks the person to open it again.
90
+
91
+ ## Calling Factorix
92
+
93
+ `factorix()` signs calls back to Factorix. Each one acts for one organization, which has to have turned the plugin on, and needs the plugin's id: a page has it as `context.plugin.id`, and a plugin with work to do outside a page keeps it from there.
94
+
95
+ ```ts
96
+ import { factorix, FactorixError } from '@moxxy/factorix-plugin-sdk'
97
+
98
+ const fx = factorix({ url: process.env.FACTORIX_URL, secret: process.env.PLUGIN_SECRET, pluginId: context.plugin.id })
99
+ const { settings, secrets } = await fx.settings(orgId) // secret settings are never in the page token
100
+ const activity = await fx.activity(orgId, since) // needs activity:read
101
+ const agents = await fx.agents(orgId) // needs agents:run
102
+ const run = await fx.startRun(orgId, { agentId, prompt, outputSchema })
103
+ const done = await fx.getRun(orgId, run.id) // done.output once done.state is succeeded
104
+ const members = await fx.members(orgId) // needs members:read
105
+ const projects = await fx.projects(orgId) // needs tickets:write
106
+ const ticket = await fx.createTicket(orgId, { projectId: projects[0].id, title: 'Order a laptop' })
107
+ const now = await fx.getTicket(orgId, ticket.id) // now.closed once its status is completed or canceled
108
+ await fx.finishStep(orgId, { runId, nodeId, handle: 'sent' }) // needs workflows:blocks, ends a step a block held
109
+ await fx.fireTrigger(orgId, { trigger: 'reacted', data: { who: 'Kim' }, eventId }) // needs workflows:blocks, starts workflows built on it
110
+ ```
111
+
112
+ What a plugin may ask beyond its own settings is a permission it names in `definePlugin({ permissions })`:
113
+
114
+ - `activity:read`: the organization's tickets that have an assignee or an agent and changed since a moment or are still open (at most 31 days back), the merge requests of those tickets merged since then, and what agents reported on them.
115
+ - `agents:run`: the organization's agents, and runs of them with no ticket and no repository. A run gets your prompt and answers in the shape of `outputSchema`, a JSON Schema of an object. Claude and Codex both fill it, so close every object with `additionalProperties: false` and list every property under `required`. At most three of a plugin's runs are unfinished at once.
116
+ - `members:read`: the organization's people and agents, with their names, handles, roles, and whether each is active. No email addresses.
117
+ - `tickets:write`: the names of the organization's projects, and tickets you create in them, in whatever tracker each project follows. Give `agentId` to hand the ticket to an agent. You read back only tickets you created.
118
+ - `workflows:blocks`: blocks and triggers in the organization's workflows, and what each block is given when it runs. A trigger starts workflows with no ticket, and each filled-in field of it has to equal the event's value under the same key. `definePlugin` adds it for a plugin with `blocks` or `triggers`.
119
+
120
+ An organization's admin sees these when turning the plugin on, and Factorix answers only what that admin allowed. A permission a newer version of your plugin adds is refused until the admin saves the plugin's settings again. A refused call throws `FactorixError`, whose `status` is 403 for a permission that was not allowed, 404 when the organization has not turned the plugin on or the run is not this plugin's, 409 for a disabled agent or too many runs, and 401 for a wrong secret.
121
+
122
+ Text in the activity comes from trackers and people. When you put it into a prompt, mark it as data, as `plugins/digest` does, since the agent follows what its prompt asks.
123
+
124
+ ## Workflow blocks
125
+
126
+ A block is a step an organization's workflows can take, run by your plugin:
127
+
128
+ ```ts
129
+ definePlugin({
130
+ name: 'Chat',
131
+ version: '1.0.0',
132
+ blocks: [
133
+ {
134
+ key: 'post',
135
+ title: 'Post to chat',
136
+ description: 'Posts a message to a channel.',
137
+ fields: [
138
+ { key: 'channel', label: 'Channel', kind: 'select', dynamic: true, required: true },
139
+ { key: 'text', label: 'Message', kind: 'template', required: true },
140
+ ],
141
+ outputs: [
142
+ { id: 'sent', label: 'Sent' },
143
+ { id: 'muted', label: 'Muted' },
144
+ ],
145
+ async run(call) {
146
+ return { handle: 'sent', output: { ts: await post(call.config.channel, call.config.text) } }
147
+ },
148
+ options: async ({ org }) => listChannels(org.id),
149
+ },
150
+ ],
151
+ })
152
+ ```
153
+
154
+ `call.config` holds the block's fields with `{{...}}` placeholders already filled. A `dynamic` select gets its choices from `options`. A block leaves through the output it names, the first by default, or through `failed` when `run` throws. `output` reaches later blocks as `{{steps.<block id>.<key>}}`. Slow work answers `{ wait: true }` and calls `finishStep` with `call.run.id` and `call.nodeId` once done, using `call.plugin.id` as the `pluginId`. A held step fails after seven days without word.
155
+
156
+ ## Your own tables
157
+
158
+ A plugin that needs to store something uses its own database. The SDK has a small runner for migrations that go both ways:
159
+
160
+ ```ts
161
+ import { migrateDown, migrateUp } from '@moxxy/factorix-plugin-sdk'
162
+
163
+ const migrations = [{ id: '0001_boards', up: 'CREATE TABLE boards (id text PRIMARY KEY, org_id text NOT NULL)', down: 'DROP TABLE boards' }]
164
+ await migrateUp(client, migrations) // on start
165
+ await migrateDown(client, migrations, 1) // roll the newest one back
166
+ ```
167
+
168
+ `client` is one Postgres connection, such as a `pg` Client or a client taken from a Pool. Each migration runs in a transaction, and a lock keeps two instances from running the same one. Keep the organization's id on every row: one plugin serves every organization that turned it on. A plugin in Factorix's `plugins/` folder that asks for a database gets an empty one of its own as `DATABASE_URL`.
169
+
170
+ ## Testing
171
+
172
+ ```ts
173
+ import { checkTracker, factorixClient, fakeFactorix } from '@moxxy/factorix-plugin-sdk/testing'
174
+
175
+ const client = factorixClient(plugin)
176
+ await checkTracker(client.tracker({ config: { site: 'https://acme.test' }, secrets: { token: 't' } }))
177
+ expect(await client.runBlock('post', { config: { channel: 'C1', text: 'Hi' } })).toEqual({ handle: 'sent', output: { ts: '1.5' } })
178
+ expect((await client.openPage('reports')).status).toBe(200)
179
+ expect((await client.openPage('notes', { account: { id: 'a', name: 'Kim', role: 'admin' } }, { form: { note: 'hi' } })).status).toBe(303)
180
+
181
+ const fake = fakeFactorix({ agents: () => [{ id: 'agent-1', handle: 'eng', name: 'Eng', status: 'active', runtime: 'claude', model: null }] })
182
+ const fx = factorix({ url: 'https://factorix.test', secret: 'test-secret-0123456789', pluginId: 'plugin-1', fetch: fake.fetch })
183
+ ```
184
+
185
+ `factorixClient` calls your plugin the way Factorix does, signatures included, and `openPage` with `form` posts to a page's `action`. `fakeFactorix` answers your plugin's calls to Factorix without a network: give it a handler for each call your test needs, and throw a `FactorixError` from one to refuse. `checkTracker` walks a tracker through a sync, a status change, agent labels, and a comment, and says what is off. It writes to the tracker, so point it at a test account.
186
+
187
+ ## The protocol
188
+
189
+ Version 1. Everything is JSON over HTTPS, signed with one shared secret:
190
+
191
+ - `x-factorix-timestamp`: milliseconds since the epoch. More than five minutes off is refused.
192
+ - `x-factorix-signature`: `sha256=` and the hex HMAC-SHA256 of `<timestamp>.<body>`.
193
+
194
+ Factorix to plugin, `POST <address>`:
195
+
196
+ ```json
197
+ { "protocol": 1, "method": "tracker.listTeams", "params": [], "connection": { "id": "…", "config": {}, "secrets": {} } }
198
+ ```
199
+
200
+ The answer is `{ "result": … }`, or `{ "error": { "message": "…" } }` with a status of 400 or above. `manifest`, `workflow.block`, and `workflow.options` come with no connection. `workflow.block` has the block's call as its one param and answers `{ "handle", "output" }` or `{ "wait": true }`. `workflow.options` has `{ "block", "field", "org" }` and answers `[{ "value", "label" }]`.
201
+
202
+ The manifest names what the plugin asks of Factorix as `"permissions": ["activity:read", "agents:run"]`.
203
+
204
+ Plugin to Factorix, each signed the same way:
205
+
206
+ - `POST <factorix>/webhooks/plugin/<connectionId>` with `{ "event": … }`, and an optional `x-factorix-delivery` header to drop repeats.
207
+ - `POST <factorix>/webhooks/plugins/<pluginId>/settings` with `{ "orgId": "…" }`, answered with `{ "settings", "secrets" }`.
208
+ - `POST <factorix>/webhooks/plugins/<pluginId>/activity` with `{ "orgId", "since" }`, answered with `{ "activity" }`. Needs `activity:read`.
209
+ - `POST <factorix>/webhooks/plugins/<pluginId>/agents` with `{ "orgId" }`, answered with `{ "agents" }`. Needs `agents:run`.
210
+ - `POST <factorix>/webhooks/plugins/<pluginId>/runs` with `{ "orgId", "agentId", "prompt", "outputSchema" }`, answered with `{ "run" }`. Needs `agents:run`.
211
+ - `POST <factorix>/webhooks/plugins/<pluginId>/runs/<runId>` with `{ "orgId" }`, answered with `{ "run" }`. Needs `agents:run`.
212
+ - `POST <factorix>/webhooks/plugins/<pluginId>/members` with `{ "orgId" }`, answered with `{ "members" }`. Needs `members:read`.
213
+ - `POST <factorix>/webhooks/plugins/<pluginId>/projects` with `{ "orgId" }`, answered with `{ "projects" }`. Needs `tickets:write`.
214
+ - `POST <factorix>/webhooks/plugins/<pluginId>/tickets` with `{ "orgId", "projectId", "title", "description", "priority", "agentId" }`, answered with `{ "ticket" }`. Needs `tickets:write`.
215
+ - `POST <factorix>/webhooks/plugins/<pluginId>/tickets/<ticketId>` with `{ "orgId" }`, answered with `{ "ticket" }`. Needs `tickets:write`.
216
+ - `POST <factorix>/webhooks/plugins/<pluginId>/workflow-steps` with `{ "orgId", "runId", "nodeId", "handle", "output", "error" }`, answered with `{ "ok": true }`. Needs `workflows:blocks`.
217
+ - `POST <factorix>/webhooks/plugins/<pluginId>/workflow-triggers` with `{ "orgId", "trigger", "data", "eventId" }`, answered with `{ "started" }`. Needs `workflows:blocks`.
218
+
219
+ A refusal is a status of 400 or above with `{ "error": { "message": "…" } }`.
220
+
221
+ Limits today: a plugin provides a tracker, pages, settings, workflow blocks and triggers, and work for agents. It cannot serve a code host or attachments yet.
222
+
223
+ ## Publishing the SDK
224
+
225
+ From the Factorix repository: `yarn workspace @moxxy/factorix-plugin-sdk release`. It builds `dist/` with its own `package.json` and publishes that folder. Inside the repository nothing is built: plugins read the SDK's sources.
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './migrations.js';
2
+ export * from './plugin.js';
3
+ export { readPageToken, sign, verify } from './signing.js';
4
+ export * from './types.js';
package/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './migrations.js';
2
+ export * from './plugin.js';
3
+ export { readPageToken, sign, verify } from './signing.js';
4
+ export * from './types.js';
@@ -0,0 +1,19 @@
1
+ /** One database connection that runs SQL with numbered parameters. A `pg` Client fits as it is. A Pool does not, since a transaction must stay on one connection. */
2
+ export interface SqlClient {
3
+ query(sql: string, params?: unknown[]): Promise<{
4
+ rows: Record<string, unknown>[];
5
+ }>;
6
+ }
7
+ export interface Migration {
8
+ /** Sorted as text to decide the order, so start it with a number: `0001_boards`. */
9
+ id: string;
10
+ up: string;
11
+ down: string;
12
+ }
13
+ /**
14
+ * Your plugin's own tables, in your plugin's own database. Each migration runs in a transaction with its record, so one
15
+ * that fails leaves nothing behind. The lock keeps two instances starting at once from running the same one twice.
16
+ */
17
+ export declare function migrateUp(db: SqlClient, migrations: Migration[]): Promise<string[]>;
18
+ /** Rolls back the newest applied migrations, one unless `steps` says more. */
19
+ export declare function migrateDown(db: SqlClient, migrations: Migration[], steps?: number): Promise<string[]>;
package/migrations.js ADDED
@@ -0,0 +1,69 @@
1
+ const TABLE = 'plugin_migrations';
2
+ async function applied(db) {
3
+ await db.query(`CREATE TABLE IF NOT EXISTS ${TABLE} (id text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`);
4
+ return (await db.query(`SELECT id FROM ${TABLE} ORDER BY id`)).rows.map((row) => String(row.id));
5
+ }
6
+ function ordered(migrations) {
7
+ const sorted = [...migrations].sort((a, b) => (a.id < b.id ? -1 : 1));
8
+ if (new Set(sorted.map((migration) => migration.id)).size !== sorted.length)
9
+ throw new Error('Two migrations share an id');
10
+ return sorted;
11
+ }
12
+ /**
13
+ * Your plugin's own tables, in your plugin's own database. Each migration runs in a transaction with its record, so one
14
+ * that fails leaves nothing behind. The lock keeps two instances starting at once from running the same one twice.
15
+ */
16
+ export async function migrateUp(db, migrations) {
17
+ const ran = [];
18
+ await db.query('SELECT pg_advisory_lock(hashtext($1))', [TABLE]);
19
+ try {
20
+ const done = new Set(await applied(db));
21
+ for (const migration of ordered(migrations)) {
22
+ if (done.has(migration.id))
23
+ continue;
24
+ await db.query('BEGIN');
25
+ try {
26
+ await db.query(migration.up);
27
+ await db.query(`INSERT INTO ${TABLE} (id) VALUES ($1)`, [migration.id]);
28
+ await db.query('COMMIT');
29
+ }
30
+ catch (error) {
31
+ await db.query('ROLLBACK');
32
+ throw new Error(`Migration ${migration.id} failed: ${error.message}`);
33
+ }
34
+ ran.push(migration.id);
35
+ }
36
+ }
37
+ finally {
38
+ await db.query('SELECT pg_advisory_unlock(hashtext($1))', [TABLE]);
39
+ }
40
+ return ran;
41
+ }
42
+ /** Rolls back the newest applied migrations, one unless `steps` says more. */
43
+ export async function migrateDown(db, migrations, steps = 1) {
44
+ const ran = [];
45
+ const byId = new Map(migrations.map((migration) => [migration.id, migration]));
46
+ await db.query('SELECT pg_advisory_lock(hashtext($1))', [TABLE]);
47
+ try {
48
+ for (const id of (await applied(db)).reverse().slice(0, steps)) {
49
+ const migration = byId.get(id);
50
+ if (!migration)
51
+ throw new Error(`Migration ${id} is applied but no longer defined, so it cannot be rolled back`);
52
+ await db.query('BEGIN');
53
+ try {
54
+ await db.query(migration.down);
55
+ await db.query(`DELETE FROM ${TABLE} WHERE id = $1`, [id]);
56
+ await db.query('COMMIT');
57
+ }
58
+ catch (error) {
59
+ await db.query('ROLLBACK');
60
+ throw new Error(`Rolling back ${id} failed: ${error.message}`);
61
+ }
62
+ ran.push(id);
63
+ }
64
+ }
65
+ finally {
66
+ await db.query('SELECT pg_advisory_unlock(hashtext($1))', [TABLE]);
67
+ }
68
+ return ran;
69
+ }
package/node.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type Server } from 'node:http';
2
+ import { type HandlerOptions, type Plugin } from './plugin.js';
3
+ /** Starts a plain Node server for a plugin. Put HTTPS in front of it: Factorix sends connection secrets to this address. */
4
+ export declare function serve(plugin: Plugin, options: HandlerOptions & {
5
+ port?: number;
6
+ hostname?: string;
7
+ }): Promise<Server>;
package/node.js ADDED
@@ -0,0 +1,29 @@
1
+ import { createServer } from 'node:http';
2
+ import { createHandler } from './plugin.js';
3
+ /** Starts a plain Node server for a plugin. Put HTTPS in front of it: Factorix sends connection secrets to this address. */
4
+ export function serve(plugin, options) {
5
+ const handler = createHandler(plugin, options);
6
+ const server = createServer(async (req, res) => {
7
+ try {
8
+ const chunks = [];
9
+ for await (const chunk of req)
10
+ chunks.push(chunk);
11
+ const headers = new Headers();
12
+ for (const [name, value] of Object.entries(req.headers))
13
+ if (value !== undefined)
14
+ headers.set(name, [value].flat().join(', '));
15
+ const method = req.method ?? 'GET';
16
+ const response = await handler(new Request(`http://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`, {
17
+ method,
18
+ headers,
19
+ body: method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks),
20
+ }));
21
+ res.writeHead(response.status, Object.fromEntries(response.headers));
22
+ res.end(Buffer.from(await response.arrayBuffer()));
23
+ }
24
+ catch {
25
+ res.writeHead(500).end();
26
+ }
27
+ });
28
+ return new Promise((resolve) => server.listen(options.port ?? 8787, options.hostname ?? '0.0.0.0', () => resolve(server)));
29
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@moxxy/factorix-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Build plugins for Factorix: trackers, pages, settings, and calls back into Factorix, served from your own server",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/WebEferen/factorix.git",
9
+ "directory": "packages/plugin-sdk"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./index.d.ts",
15
+ "default": "./index.js"
16
+ },
17
+ "./node": {
18
+ "types": "./node.d.ts",
19
+ "default": "./node.js"
20
+ },
21
+ "./testing": {
22
+ "types": "./testing.d.ts",
23
+ "default": "./testing.js"
24
+ }
25
+ },
26
+ "engines": {
27
+ "node": ">=22"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ }
32
+ }
package/plugin.d.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { type Activity, type Agent, type BlockAnswer, type BlockCall, type BlockField, type Connection, type Field, type Manifest, type Member, type PageContext, type Permission, type Run, type RunRequest, type Ticket, type TicketProject, type TicketRequest, type Tracker, type TrackerEvent } from './types.js';
2
+ export interface PageDefinition {
3
+ key: string;
4
+ /** What the entry in Factorix's menu says. */
5
+ label: string;
6
+ /** Where the page lives under your plugin's address. Defaults to `/pages/<key>`. */
7
+ path?: string;
8
+ /** `sidebar` puts it in the main menu, `settings` on the plugin's row under Settings. */
9
+ placement?: 'sidebar' | 'settings';
10
+ /** Returns the HTML of the page, or a whole response. `token` is the signed context, to send back with the page's own requests. */
11
+ render(context: PageContext, request: Request, token: string): string | Response | Promise<string | Response>;
12
+ /**
13
+ * Handles a POST to the page's own address, such as a form on it. The token is read the same way as for `render`, so
14
+ * put it in the form's address (`action="?factorix=<token>"`). Answer with a redirect back to the page, or with HTML.
15
+ */
16
+ action?(context: PageContext, request: Request, token: string): string | Response | Promise<string | Response>;
17
+ }
18
+ export interface BlockDefinition {
19
+ /** Lowercase letters, digits, and underscores, starting with a letter. Keep it once workflows use the block. */
20
+ key: string;
21
+ title: string;
22
+ description: string;
23
+ fields?: BlockField[];
24
+ /** The ways out of the block. Defaults to one, `next`. A block that throws leaves through `failed`, which every block has. */
25
+ outputs?: {
26
+ id: string;
27
+ label: string;
28
+ }[];
29
+ /** What it hands to later blocks, as `{{steps.<block id>.<key>}}`, so the editor can offer them. */
30
+ provides?: {
31
+ key: string;
32
+ label: string;
33
+ }[];
34
+ /** Does the block's work. Answer quickly: anything slow answers `{ wait: true }` and calls `finishStep` when done. */
35
+ run(call: BlockCall): BlockAnswer | Promise<BlockAnswer>;
36
+ /** The choices of a `dynamic` field, for one organization. */
37
+ options?(input: {
38
+ field: string;
39
+ org: {
40
+ id: string;
41
+ };
42
+ }): {
43
+ value: string;
44
+ label: string;
45
+ }[] | Promise<{
46
+ value: string;
47
+ label: string;
48
+ }[]>;
49
+ }
50
+ /**
51
+ * Something that happens in your plugin and can start a workflow, with no ticket. Report each one with
52
+ * `factorix().fireTrigger`. Its fields narrow which events start a workflow: each one an admin fills in has to equal the
53
+ * event's value under the same key, so they can only be `text` or `select`.
54
+ */
55
+ export interface TriggerDefinition {
56
+ /** Lowercase letters, digits, and underscores, starting with a letter, and no block's key. Keep it once workflows use it. */
57
+ key: string;
58
+ title: string;
59
+ description: string;
60
+ fields?: BlockField[];
61
+ /** What an event hands to the blocks after it, as `{{steps.<block id>.<key>}}`, so the editor can offer them. */
62
+ provides?: {
63
+ key: string;
64
+ label: string;
65
+ }[];
66
+ /** The choices of a `dynamic` field, for one organization. */
67
+ options?(input: {
68
+ field: string;
69
+ org: {
70
+ id: string;
71
+ };
72
+ }): {
73
+ value: string;
74
+ label: string;
75
+ }[] | Promise<{
76
+ value: string;
77
+ label: string;
78
+ }[]>;
79
+ }
80
+ export interface PluginDefinition {
81
+ name: string;
82
+ version: string;
83
+ description?: string;
84
+ /** What an admin fills in to connect one account. Reaches `tracker` as `connection.config` and `connection.secrets`. */
85
+ connection?: {
86
+ fields: Field[];
87
+ };
88
+ /** What an organization sets once for the whole plugin. Reaches pages as `context.settings`. */
89
+ settings?: {
90
+ fields: Field[];
91
+ };
92
+ /** What the plugin asks of Factorix through `factorix()`. An organization's admin allows them when turning the plugin on. */
93
+ permissions?: Permission[];
94
+ pages?: PageDefinition[];
95
+ /** Steps it adds to the workflows of each organization that turns it on. */
96
+ blocks?: BlockDefinition[];
97
+ /** What can start those workflows from inside the plugin. */
98
+ triggers?: TriggerDefinition[];
99
+ /** Builds a tracker for one connection. Called per request, so keep it cheap and keep nothing in it. */
100
+ tracker?(connection: Connection): Tracker;
101
+ }
102
+ export interface Plugin extends PluginDefinition {
103
+ manifest: Manifest;
104
+ }
105
+ export declare function definePlugin(definition: PluginDefinition): Plugin;
106
+ export interface HandlerOptions {
107
+ /** The secret shared with Factorix: the one an installation admin types when installing the plugin. */
108
+ secret: string;
109
+ /** The path part of the address given to Factorix. Defaults to `/factorix`. */
110
+ path?: string;
111
+ }
112
+ /**
113
+ * Serves a plugin from any runtime that speaks `Request` and `Response`. Calls from Factorix arrive as POST on `path`,
114
+ * signed, and pages as GET under it with a signed `factorix` parameter. Anything else gets a 404 or a 401.
115
+ */
116
+ export declare function createHandler(plugin: Plugin, options: HandlerOptions): (request: Request) => Promise<Response>;
117
+ export interface FactorixOptions {
118
+ /** The address of the Factorix installation. A plugin in Factorix's own `plugins/` folder gets it as `FACTORIX_URL`. */
119
+ url: string;
120
+ secret: string;
121
+ /** The plugin's id in that installation, needed for every call but `sendEvent`. Pages get it as `context.plugin.id`. */
122
+ pluginId?: string;
123
+ /** Stands in for the global `fetch`, for tests. */
124
+ fetch?: typeof fetch;
125
+ }
126
+ /** A call Factorix refused. `status` is 403 for a permission the organization did not allow, and 404 when it has not turned the plugin on. */
127
+ export declare class FactorixError extends Error {
128
+ readonly status: number;
129
+ constructor(status: number, message: string);
130
+ }
131
+ /** The calls a plugin makes to Factorix, signed with the shared secret. Every call but `sendEvent` acts for one organization. */
132
+ export declare function factorix(options: FactorixOptions): {
133
+ /**
134
+ * Tells Factorix something changed. `callbackUrl` is the address `registerWebhook` was given, or the connection's
135
+ * id. Give a `deliveryId` when the source has one, and a repeated delivery is dropped.
136
+ */
137
+ sendEvent(callbackUrl: string, event: TrackerEvent, deliveryId?: string): Promise<void>;
138
+ /** What an organization set for this plugin, secret fields included. */
139
+ settings(orgId: string): Promise<{
140
+ settings: Record<string, string>;
141
+ secrets: Record<string, string>;
142
+ }>;
143
+ /** What happened on the organization's tickets since `since`, at most 31 days back. Needs `activity:read`. */
144
+ activity(orgId: string, since: Date | string): Promise<Activity>;
145
+ /** The organization's agents. Needs `agents:run`. */
146
+ agents(orgId: string): Promise<Agent[]>;
147
+ /**
148
+ * Asks one of the organization's agents for work, in a run with no ticket and no repository. The run is queued and
149
+ * the answer comes later: read it with `getRun`. At most three of a plugin's runs are unfinished at once. Needs `agents:run`.
150
+ */
151
+ startRun(orgId: string, request: RunRequest): Promise<Run>;
152
+ /** A run this plugin started, with the agent's answer once it succeeded. Needs `agents:run`. */
153
+ getRun(orgId: string, runId: string): Promise<Run>;
154
+ /** The people and agents of the organization. Needs `members:read`. */
155
+ members(orgId: string): Promise<Member[]>;
156
+ /** The projects a ticket can be created in. Needs `tickets:write`. */
157
+ projects(orgId: string): Promise<TicketProject[]>;
158
+ /** Creates a ticket in one of the organization's projects, in whatever tracker that project follows. Needs `tickets:write`. */
159
+ createTicket(orgId: string, request: TicketRequest): Promise<Ticket>;
160
+ /** A ticket this plugin created, as it stands now. Needs `tickets:write`. */
161
+ getTicket(orgId: string, ticketId: string): Promise<Ticket>;
162
+ /**
163
+ * Ends a step one of your blocks held with `{ wait: true }`. `handle` and `output` work as in the block's answer, and
164
+ * `error` fails the step instead. Throws `FactorixError` 409 once the step has ended. Needs `workflows:blocks`.
165
+ */
166
+ finishStep(orgId: string, step: {
167
+ runId: string;
168
+ nodeId: string;
169
+ handle?: string;
170
+ output?: Record<string, string>;
171
+ error?: string;
172
+ }): Promise<void>;
173
+ /**
174
+ * Reports that one of your triggers happened, and starts the organization's workflows built on it. `data` holds the
175
+ * values its fields are compared with and what it provides, as texts; other keys are dropped. Sending the same
176
+ * `eventId` again starts nothing new, so a retry is safe. Answers how many workflows started. Needs `workflows:blocks`.
177
+ */
178
+ fireTrigger(orgId: string, event: {
179
+ trigger: string;
180
+ data?: Record<string, string>;
181
+ eventId?: string;
182
+ }): Promise<number>;
183
+ };
184
+ export type FactorixClient = ReturnType<typeof factorix>;