attune-sdk 0.4.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.
Files changed (87) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +355 -0
  3. package/dist/action.d.ts +34 -0
  4. package/dist/action.d.ts.map +1 -0
  5. package/dist/action.js +62 -0
  6. package/dist/action.js.map +1 -0
  7. package/dist/api_client/client/client.gen.d.ts +3 -0
  8. package/dist/api_client/client/client.gen.d.ts.map +1 -0
  9. package/dist/api_client/client/client.gen.js +217 -0
  10. package/dist/api_client/client/client.gen.js.map +1 -0
  11. package/dist/api_client/client/index.d.ts +9 -0
  12. package/dist/api_client/client/index.d.ts.map +1 -0
  13. package/dist/api_client/client/index.js +7 -0
  14. package/dist/api_client/client/index.js.map +1 -0
  15. package/dist/api_client/client/types.gen.d.ts +121 -0
  16. package/dist/api_client/client/types.gen.d.ts.map +1 -0
  17. package/dist/api_client/client/types.gen.js +3 -0
  18. package/dist/api_client/client/types.gen.js.map +1 -0
  19. package/dist/api_client/client/utils.gen.d.ts +38 -0
  20. package/dist/api_client/client/utils.gen.d.ts.map +1 -0
  21. package/dist/api_client/client/utils.gen.js +229 -0
  22. package/dist/api_client/client/utils.gen.js.map +1 -0
  23. package/dist/api_client/client.gen.d.ts +13 -0
  24. package/dist/api_client/client.gen.d.ts.map +1 -0
  25. package/dist/api_client/client.gen.js +4 -0
  26. package/dist/api_client/client.gen.js.map +1 -0
  27. package/dist/api_client/core/auth.gen.d.ts +19 -0
  28. package/dist/api_client/core/auth.gen.d.ts.map +1 -0
  29. package/dist/api_client/core/auth.gen.js +15 -0
  30. package/dist/api_client/core/auth.gen.js.map +1 -0
  31. package/dist/api_client/core/bodySerializer.gen.d.ts +26 -0
  32. package/dist/api_client/core/bodySerializer.gen.d.ts.map +1 -0
  33. package/dist/api_client/core/bodySerializer.gen.js +58 -0
  34. package/dist/api_client/core/bodySerializer.gen.js.map +1 -0
  35. package/dist/api_client/core/params.gen.d.ts +44 -0
  36. package/dist/api_client/core/params.gen.d.ts.map +1 -0
  37. package/dist/api_client/core/params.gen.js +101 -0
  38. package/dist/api_client/core/params.gen.js.map +1 -0
  39. package/dist/api_client/core/pathSerializer.gen.d.ts +34 -0
  40. package/dist/api_client/core/pathSerializer.gen.d.ts.map +1 -0
  41. package/dist/api_client/core/pathSerializer.gen.js +107 -0
  42. package/dist/api_client/core/pathSerializer.gen.js.map +1 -0
  43. package/dist/api_client/core/queryKeySerializer.gen.d.ts +19 -0
  44. package/dist/api_client/core/queryKeySerializer.gen.d.ts.map +1 -0
  45. package/dist/api_client/core/queryKeySerializer.gen.js +93 -0
  46. package/dist/api_client/core/queryKeySerializer.gen.js.map +1 -0
  47. package/dist/api_client/core/serverSentEvents.gen.d.ts +72 -0
  48. package/dist/api_client/core/serverSentEvents.gen.d.ts.map +1 -0
  49. package/dist/api_client/core/serverSentEvents.gen.js +133 -0
  50. package/dist/api_client/core/serverSentEvents.gen.js.map +1 -0
  51. package/dist/api_client/core/types.gen.d.ts +79 -0
  52. package/dist/api_client/core/types.gen.d.ts.map +1 -0
  53. package/dist/api_client/core/types.gen.js +3 -0
  54. package/dist/api_client/core/types.gen.js.map +1 -0
  55. package/dist/api_client/core/utils.gen.d.ts +20 -0
  56. package/dist/api_client/core/utils.gen.d.ts.map +1 -0
  57. package/dist/api_client/core/utils.gen.js +88 -0
  58. package/dist/api_client/core/utils.gen.js.map +1 -0
  59. package/dist/api_client/index.d.ts +3 -0
  60. package/dist/api_client/index.d.ts.map +1 -0
  61. package/dist/api_client/index.js +3 -0
  62. package/dist/api_client/index.js.map +1 -0
  63. package/dist/api_client/sdk.gen.d.ts +1000 -0
  64. package/dist/api_client/sdk.gen.d.ts.map +1 -0
  65. package/dist/api_client/sdk.gen.js +2145 -0
  66. package/dist/api_client/sdk.gen.js.map +1 -0
  67. package/dist/api_client/types.gen.d.ts +19794 -0
  68. package/dist/api_client/types.gen.d.ts.map +1 -0
  69. package/dist/api_client/types.gen.js +3 -0
  70. package/dist/api_client/types.gen.js.map +1 -0
  71. package/dist/client.d.ts +42 -0
  72. package/dist/client.d.ts.map +1 -0
  73. package/dist/client.js +73 -0
  74. package/dist/client.js.map +1 -0
  75. package/dist/context.d.ts +112 -0
  76. package/dist/context.d.ts.map +1 -0
  77. package/dist/context.js +108 -0
  78. package/dist/context.js.map +1 -0
  79. package/dist/index.d.ts +43 -0
  80. package/dist/index.d.ts.map +1 -0
  81. package/dist/index.js +38 -0
  82. package/dist/index.js.map +1 -0
  83. package/dist/sensor.d.ts +127 -0
  84. package/dist/sensor.d.ts.map +1 -0
  85. package/dist/sensor.js +880 -0
  86. package/dist/sensor.js.map +1 -0
  87. package/package.json +64 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 David Culbreth
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,355 @@
1
+ # attune-sdk - Node.js SDK for Attune Actions and Sensors
2
+
3
+ A lightweight TypeScript package providing boilerplate for writing [Attune](https://github.com/attune-system/attune) actions and sensors.
4
+
5
+ Version 0.4.0 is compatible with Attune 0.4.0 and its OpenAPI 0.4.0 contract.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install attune-sdk
11
+ ```
12
+
13
+ ## Writing Actions
14
+
15
+ Actions receive parameters as JSON on stdin and output results as JSON on stdout.
16
+ This package handles all of that:
17
+
18
+ ```typescript
19
+ import { runAction } from "attune-sdk";
20
+
21
+ function main(params: { name: string; count?: number }) {
22
+ return { greeting: `Hello, ${params.name}!`.repeat(params.count ?? 1) };
23
+ }
24
+
25
+ runAction(main);
26
+ ```
27
+
28
+ Your function receives the full params object parsed from stdin JSON.
29
+
30
+ ### Accessing Execution Context
31
+
32
+ The context is a module-level singleton available anywhere after import:
33
+
34
+ ```typescript
35
+ import { context, runAction } from "attune-sdk";
36
+
37
+ function main(params: { url: string; method?: string }) {
38
+ return { action: context.actionRef, exec_id: context.executionId };
39
+ }
40
+
41
+ runAction(main);
42
+ ```
43
+
44
+ ### Using the Generated API Client
45
+
46
+ The SDK ships a fully typed API client generated from the Attune OpenAPI spec.
47
+ Both `context` (actions) and `sensorContext` (sensors) expose a `.client`
48
+ property that is pre-configured with the execution-scoped API token:
49
+
50
+ ```typescript
51
+ import { context, runAction } from "attune-sdk";
52
+ import { listPacks, getExecution } from "attune-sdk/api_client";
53
+
54
+ async function main(params: { executionId: number }) {
55
+ // Use the pre-authenticated client from context
56
+ const packs = await listPacks({ client: context.client });
57
+ const exec = await getExecution({
58
+ client: context.client,
59
+ path: { id: params.executionId },
60
+ });
61
+ return { packs: packs.data, execution: exec.data };
62
+ }
63
+
64
+ runAction(main);
65
+ ```
66
+
67
+ The client is also available in sensor context:
68
+
69
+ ```typescript
70
+ import { sensorContext } from "attune-sdk";
71
+ import { listSensors } from "attune-sdk/api_client";
72
+
73
+ const sensors = await listSensors({ client: sensorContext.client });
74
+ ```
75
+
76
+ You can also create a standalone client instance for custom configurations:
77
+
78
+ ```typescript
79
+ import { createClient } from "attune-sdk";
80
+
81
+ const client = createClient({
82
+ baseUrl: "http://localhost:8080",
83
+ headers: { Authorization: "Bearer my-token" },
84
+ });
85
+ ```
86
+
87
+ Generated operations take a single options object. Path, query, and JSON body
88
+ values remain separate:
89
+
90
+ ```typescript
91
+ import {
92
+ createEvent,
93
+ createKey,
94
+ deleteKey,
95
+ getKey,
96
+ installPack,
97
+ updateKey,
98
+ } from "attune-sdk/api_client";
99
+
100
+ const created = await createKey({
101
+ client,
102
+ body: {
103
+ local_ref: "deploy_token",
104
+ owner_type: "pack",
105
+ owner_pack_ref: "deployments",
106
+ name: "Deployment token",
107
+ value: "secret",
108
+ encrypted: true,
109
+ },
110
+ });
111
+ if (!created.data) throw new Error("Key creation failed");
112
+
113
+ // Attune constructs the canonical ref. Responses also retain the local ref.
114
+ const { ref, local_ref } = created.data.data;
115
+ const key = await getKey({ client, path: { ref } });
116
+ await updateKey({ client, path: { ref }, body: { name: "Production deployment token" } });
117
+ await deleteKey({ client, path: { ref } });
118
+
119
+ await installPack({
120
+ client,
121
+ body: { source: "https://github.com/example/pack.git", no_registry: true },
122
+ });
123
+ await createEvent({
124
+ client,
125
+ body: { trigger_ref: "monitor.alert", payload: { severity: "high" } },
126
+ });
127
+ ```
128
+
129
+ Key creation requires `local_ref` and `owner_type`. For identity, pack, action,
130
+ and sensor scopes, pass the matching textual owner field:
131
+ `owner_identity_login`, `owner_pack_ref`, `owner_action_ref`, or
132
+ `owner_sensor_ref`. Do not send `ref`; the server generates the canonical value.
133
+ Use that canonical `ref` for get, update, and delete. `getKey` decrypts the value
134
+ according to the caller's permission and has no decrypt query parameter.
135
+
136
+ ### Legacy HTTP Client
137
+
138
+ A simpler HTTP client is also available for ad-hoc requests:
139
+
140
+ ```typescript
141
+ import { AttuneClient } from "attune-sdk/client";
142
+
143
+ const client = new AttuneClient(); // reads ATTUNE_API_URL and ATTUNE_API_TOKEN from env
144
+ const data = await client.get("/api/v1/artifacts", { params: { execution: "42" } });
145
+ await client.post("/api/v1/artifacts/1/versions/file", { json: { created_by: "my_action" } });
146
+ ```
147
+
148
+ ## Writing Sensors
149
+
150
+ Sensors are long-running processes that emit events. The SDK provides rule
151
+ lifecycle management, signal handling (SIGINT/SIGTERM), and notifier WebSocket
152
+ delivery for managed rule updates out of the box.
153
+
154
+ The sensor context is a module-level singleton, accessible anywhere:
155
+
156
+ ```typescript
157
+ import { sensorContext } from "attune-sdk";
158
+
159
+ console.log(sensorContext.sensorRef);
160
+ console.log(sensorContext.apiUrl);
161
+ console.log(sensorContext.notifierWsUrl);
162
+ console.log(sensorContext.config); // explicitly supplied ATTUNE_SENSOR_CONFIG_* vars
163
+ ```
164
+
165
+ Managed sensors bootstrap their active rules from `ATTUNE_SENSOR_TRIGGERS`, then
166
+ listen for live rule lifecycle updates from `ATTUNE_NOTIFIER_WS_URL` using the
167
+ current `ATTUNE_API_TOKEN`. When `ATTUNE_SENSOR_TRIGGER_TYPES` is available, the
168
+ SDK subscribes to every declared trigger type; older runtimes fall back to the
169
+ trigger refs in the active-rule snapshot. Non-loopback plaintext `ws://` URLs
170
+ are rejected unless `ATTUNE_ALLOW_INSECURE_NOTIFIER_WS=true` is explicitly set.
171
+
172
+ The managed runtime renews sensor credentials by restarting the process. The
173
+ SDK does not refresh tokens or write token-state files.
174
+
175
+ Persisted sensor `config` is not injected into managed child processes. Put
176
+ rule-specific values in trigger parameters. `sensorContext.config` contains
177
+ only `ATTUNE_SENSOR_CONFIG_*` variables explicitly supplied by a custom runtime
178
+ or process launcher; do not use plain environment variables for secrets.
179
+
180
+ ### Polling Sensor (`PollingSensor`)
181
+
182
+ One interval timer per active rule:
183
+
184
+ ```typescript
185
+ import { PollingSensor, runSensor, RuleState } from "attune-sdk";
186
+
187
+ class TemperatureSensor extends PollingSensor {
188
+ interval = 5000; // ms
189
+
190
+ async poll(rule: RuleState) {
191
+ const device = (rule.triggerParams.device as string) ?? "/dev/temp0";
192
+ const temp = readTemperature(device);
193
+ if (temp > 100) {
194
+ await this.emit({ temperature: temp, alert: true }, { rule });
195
+ }
196
+ }
197
+ }
198
+
199
+ runSensor(TemperatureSensor);
200
+ ```
201
+
202
+ Passing `{ rule }` targets that numeric rule ID by default and sends
203
+ `trigger_instance_id: "rule_<id>"`. Use `{ rule, targetRule: false }` only when
204
+ the event should be broadcast to every matching rule for the trigger. Targeted
205
+ emission rejects non-positive, fractional, or unsafe JavaScript integer IDs.
206
+
207
+ `interval` and `poll_interval` trigger parameters are milliseconds;
208
+ `interval_seconds` is converted from seconds to milliseconds. Invalid,
209
+ non-positive, non-finite, or unsupported timer delays fall back to the class
210
+ `interval`.
211
+
212
+ ### Async Polling (`AsyncPollingSensor`)
213
+
214
+ One async loop per active rule (ideal for I/O-bound checks):
215
+
216
+ ```typescript
217
+ import { AsyncPollingSensor, runSensor, RuleState } from "attune-sdk";
218
+
219
+ class ApiSensor extends AsyncPollingSensor {
220
+ interval = 10000; // ms
221
+
222
+ async poll(rule: RuleState) {
223
+ const url = rule.triggerParams.url as string;
224
+ const resp = await fetch(url);
225
+ if (resp.status >= 500) {
226
+ await this.emit({ url, status: resp.status }, { rule });
227
+ }
228
+ }
229
+ }
230
+
231
+ runSensor(ApiSensor);
232
+ ```
233
+
234
+ ### Custom Event Loops (`Sensor` base class)
235
+
236
+ For non-polling sensors, override `run()`:
237
+
238
+ ```typescript
239
+ import { Sensor, runSensor } from "attune-sdk";
240
+ import { watch } from "fs";
241
+
242
+ class FileWatchSensor extends Sensor {
243
+ async run() {
244
+ const path = typeof this.config.watch_path === "string"
245
+ ? this.config.watch_path
246
+ : "/var/log/app.log";
247
+ const watcher = watch(path, () => {
248
+ void this.emit({ path, event: "change" });
249
+ });
250
+ while (!this.isShuttingDown) {
251
+ await new Promise((r) => setTimeout(r, 1000));
252
+ }
253
+ watcher.close();
254
+ }
255
+ }
256
+
257
+ runSensor(FileWatchSensor);
258
+ ```
259
+
260
+ ### Rule Lifecycle Hooks
261
+
262
+ All sensor classes support rule lifecycle hooks that fire when the platform
263
+ creates, enables, disables, deletes, or updates a rule:
264
+
265
+ ```typescript
266
+ class StatefulSensor extends PollingSensor {
267
+ onRuleCreated(rule: RuleState) {
268
+ this.logger.info(`Rule created: ${rule.ruleRef}`);
269
+ }
270
+
271
+ onRuleEnabled(rule: RuleState) {
272
+ // Previously disabled rule re-enabled
273
+ }
274
+
275
+ onRuleDisabled(rule: RuleState) {
276
+ // Rule disabled — pause per-rule work
277
+ }
278
+
279
+ onRuleDeleted(rule: RuleState) {
280
+ // Rule permanently removed — free resources
281
+ }
282
+
283
+ onRuleUpdated(rule: RuleState, oldParams: Record<string, unknown>) {
284
+ this.logger.info(`Rule updated: ${JSON.stringify(oldParams)} → ${JSON.stringify(rule.triggerParams)}`);
285
+ }
286
+ }
287
+ ```
288
+
289
+ ## Environment Variables
290
+
291
+ ### Actions
292
+
293
+ | Variable | Description |
294
+ |----------|-------------|
295
+ | `ATTUNE_ACTION` | Action reference (e.g., `mypack.deploy`) |
296
+ | `ATTUNE_PACK_REF` | Pack reference |
297
+ | `ATTUNE_EXEC_ID` | Execution database ID |
298
+ | `ATTUNE_API_URL` | API base URL |
299
+ | `ATTUNE_API_TOKEN` | Execution-scoped API token (optional) |
300
+ | `ATTUNE_ARTIFACTS_DIR` | Shared artifact volume path |
301
+ | `ATTUNE_RUNTIME_ENVS_DIR` | Runtime environments root |
302
+ | `ATTUNE_RULE` | Rule reference (if rule-triggered) |
303
+ | `ATTUNE_TRIGGER` | Trigger reference (if event-triggered) |
304
+
305
+ ### Sensors
306
+
307
+ | Variable | Description |
308
+ |----------|-------------|
309
+ | `ATTUNE_SENSOR_REF` | Sensor reference |
310
+ | `ATTUNE_SENSOR_ID` | Sensor database ID |
311
+ | `ATTUNE_PACK_REF` | Pack reference |
312
+ | `ATTUNE_API_URL` | API base URL |
313
+ | `ATTUNE_API_TOKEN` | Sensor-scoped API token |
314
+ | `ATTUNE_NOTIFIER_WS_URL` | Notifier WebSocket URL for live managed-rule updates |
315
+ | `ATTUNE_ALLOW_INSECURE_NOTIFIER_WS` | Allow non-loopback plaintext `ws://` only on a trusted development network (default: `false`) |
316
+ | `ATTUNE_SENSOR_TRIGGER_TYPES` | JSON array of every trigger ref declared by the sensor, used for complete notifier subscriptions |
317
+ | `ATTUNE_SENSOR_TRIGGERS` | Bootstrap JSON array of managed rule bindings |
318
+ | `ATTUNE_ARTIFACTS_DIR` | Shared artifact volume path |
319
+ | `ATTUNE_LOG_LEVEL` | Log verbosity |
320
+ | `ATTUNE_LOG_FORMAT` | Runtime-selected log format |
321
+
322
+ Legacy `ATTUNE_MQ_URL` and `ATTUNE_MQ_EXCHANGE` values may also be present, but
323
+ this package does not depend on `amqplib`; managed lifecycle delivery uses the
324
+ notifier WebSocket.
325
+
326
+ ## Development
327
+
328
+ ```bash
329
+ cd js-attune-sdk
330
+ npm install
331
+ npm run build
332
+ npm test
333
+ ```
334
+
335
+ ### Regenerating the API Client
336
+
337
+ The generated client lives in `src/api_client/` and is checked into the repo so
338
+ pack developers don't need to generate it themselves. To regenerate after API
339
+ changes:
340
+
341
+ ```bash
342
+ # From a running API (default: localhost:8080)
343
+ npm run generate-client
344
+
345
+ # From a local spec file
346
+ ./scripts/generate-client.sh /path/to/openapi.json
347
+
348
+ # Verify checked-in output against ../attune/web/openapi.json without replacing it
349
+ npm run generate-client:check
350
+
351
+ # From a custom API URL
352
+ ATTUNE_API_URL=http://my-host:8080 npm run generate-client
353
+ ```
354
+
355
+ This requires `@hey-api/openapi-ts` (included as a dev dependency).
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Action runner — handles stdin parameter parsing, output formatting, and error handling.
3
+ *
4
+ * Usage:
5
+ * import { runAction } from "attune-sdk";
6
+ *
7
+ * function main(params: { name: string; count?: number }) {
8
+ * return { greeting: `Hello, ${params.name}!`.repeat(params.count ?? 1) };
9
+ * }
10
+ *
11
+ * runAction(main);
12
+ *
13
+ * Exit codes:
14
+ * - 0: success (result is written to stdout as JSON)
15
+ * - 1: failure (error details written to stdout as JSON with `success: false`)
16
+ */
17
+ export type ActionFn<TParams extends Record<string, unknown> = Record<string, unknown>> = (params: TParams) => unknown | Promise<unknown>;
18
+ /** Read action parameters from stdin (JSON format). */
19
+ export declare function readParams(): Promise<Record<string, unknown>>;
20
+ /** Write a JSON result to stdout. */
21
+ export declare function emitResult(payload: unknown): void;
22
+ /** Write a JSON error to stdout. */
23
+ export declare function emitError(message: string, details?: unknown): void;
24
+ export interface RunActionOptions {
25
+ /** If true (default), uncaught exceptions are caught and reported as JSON errors. */
26
+ catchExceptions?: boolean;
27
+ }
28
+ /**
29
+ * Run an action entrypoint with automatic parameter parsing and output handling.
30
+ *
31
+ * The entrypoint function receives the full params object parsed from stdin JSON.
32
+ */
33
+ export declare function runAction<TParams extends Record<string, unknown>>(entrypoint: ActionFn<TParams>, options?: RunActionOptions): Promise<void>;
34
+ //# sourceMappingURL=action.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.d.ts","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,QAAQ,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IACpF,CAAC,MAAM,EAAE,OAAO,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAElD,uDAAuD;AACvD,wBAAsB,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAQnE;AAED,qCAAqC;AACrC,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAEjD;AAED,oCAAoC;AACpC,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,IAAI,CAMlE;AAED,MAAM,WAAW,gBAAgB;IAC/B,qFAAqF;IACrF,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrE,UAAU,EAAE,QAAQ,CAAC,OAAO,CAAC,EAC7B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAef"}
package/dist/action.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Action runner — handles stdin parameter parsing, output formatting, and error handling.
3
+ *
4
+ * Usage:
5
+ * import { runAction } from "attune-sdk";
6
+ *
7
+ * function main(params: { name: string; count?: number }) {
8
+ * return { greeting: `Hello, ${params.name}!`.repeat(params.count ?? 1) };
9
+ * }
10
+ *
11
+ * runAction(main);
12
+ *
13
+ * Exit codes:
14
+ * - 0: success (result is written to stdout as JSON)
15
+ * - 1: failure (error details written to stdout as JSON with `success: false`)
16
+ */
17
+ /** Read action parameters from stdin (JSON format). */
18
+ export async function readParams() {
19
+ const chunks = [];
20
+ for await (const chunk of process.stdin) {
21
+ chunks.push(typeof chunk === "string" ? chunk : chunk.toString("utf-8"));
22
+ }
23
+ const raw = chunks.join("").trim();
24
+ if (!raw)
25
+ return {};
26
+ return JSON.parse(raw);
27
+ }
28
+ /** Write a JSON result to stdout. */
29
+ export function emitResult(payload) {
30
+ console.log(JSON.stringify(payload));
31
+ }
32
+ /** Write a JSON error to stdout. */
33
+ export function emitError(message, details) {
34
+ const payload = { success: false, error: message };
35
+ if (details !== undefined) {
36
+ payload.details = details;
37
+ }
38
+ console.log(JSON.stringify(payload));
39
+ }
40
+ /**
41
+ * Run an action entrypoint with automatic parameter parsing and output handling.
42
+ *
43
+ * The entrypoint function receives the full params object parsed from stdin JSON.
44
+ */
45
+ export async function runAction(entrypoint, options = {}) {
46
+ const { catchExceptions = true } = options;
47
+ try {
48
+ const params = await readParams();
49
+ const result = await entrypoint(params);
50
+ emitResult(result ?? {});
51
+ process.exit(0);
52
+ }
53
+ catch (err) {
54
+ if (!catchExceptions)
55
+ throw err;
56
+ const message = err instanceof Error ? err.message : String(err);
57
+ const details = err instanceof Error && process.stderr.isTTY ? err.stack : undefined;
58
+ emitError(message, details);
59
+ process.exit(1);
60
+ }
61
+ }
62
+ //# sourceMappingURL=action.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAKH,uDAAuD;AACvD,MAAM,CAAC,KAAK,UAAU,UAAU;IAC9B,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACxC,MAAM,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAE,KAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IACvF,CAAC;IACD,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACnC,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC;AAED,qCAAqC;AACrC,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,oCAAoC;AACpC,MAAM,UAAU,SAAS,CAAC,OAAe,EAAE,OAAiB;IAC1D,MAAM,OAAO,GAA4B,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC5E,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC;IAC5B,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;AACvC,CAAC;AAOD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,UAA6B,EAC7B,UAA4B,EAAE;IAE9B,MAAM,EAAE,eAAe,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE3C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,UAAU,EAAa,CAAC;QAC7C,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,MAAM,CAAC,CAAC;QACxC,UAAU,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACtB,IAAI,CAAC,eAAe;YAAE,MAAM,GAAG,CAAC;QAChC,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;QACrF,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Client, Config } from './types.gen';
2
+ export declare const createClient: (config?: Config) => Client;
3
+ //# sourceMappingURL=client.gen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.gen.d.ts","sourceRoot":"","sources":["../../../src/api_client/client/client.gen.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAA0C,MAAM,aAAa,CAAC;AAgB1F,eAAO,MAAM,YAAY,GAAI,SAAQ,MAAW,KAAG,MA+PlD,CAAC"}