rterm-backend 3.0.9 → 3.1.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/bin/gybackend.cjs CHANGED
@@ -343189,11 +343189,13 @@ var BUILTIN_TOOL_INFO = [
343189
343189
  },
343190
343190
  {
343191
343191
  name: "write_file",
343192
- description: WRITE_FILE_TOOL_DESCRIPTION
343192
+ description: WRITE_FILE_TOOL_DESCRIPTION,
343193
+ hiddenFromSettings: true
343193
343194
  },
343194
343195
  {
343195
343196
  name: "edit_file",
343196
- description: EDIT_FILE_TOOL_DESCRIPTION
343197
+ description: EDIT_FILE_TOOL_DESCRIPTION,
343198
+ hiddenFromSettings: true
343197
343199
  },
343198
343200
  {
343199
343201
  name: "skill",
@@ -343339,6 +343341,10 @@ var BUILTIN_TOOL_INFO = [
343339
343341
  name: "get_live_dashboard",
343340
343342
  description: "Live multi-client dashboard \u2014 read the current unified dashboard state/summary, or the number of connected dashboard subscribers."
343341
343343
  },
343344
+ {
343345
+ name: "get_monitor_status",
343346
+ description: "Monitor-status diagnostic \u2014 reports why stats aren't displaying per terminal (publisher wired, session exists, collection stuck in-flight, platform, last-collect age)."
343347
+ },
343342
343348
  {
343343
343349
  name: "list_gateway_methods",
343344
343350
  description: 'API self-discovery \u2014 list the WebSocket gateway RPC methods (names, categories, descriptions, params) from the shared registry. Optionally filter by category or name prefix. Use to answer "what can the gateway do?" accurately instead of guessing method names.'
package/package.json CHANGED
@@ -1,71 +1,9 @@
1
1
  {
2
2
  "name": "rterm-backend",
3
- "version": "3.0.9",
4
- "description": "Headless AI-native backend for RTerm / neuralOS — v3.0.9: web-intel plugin (local-first web intelligence via wigolo; lean-by-default, synthesis by RTerm agent).",
3
+ "version": "3.1.0",
4
+ "description": "Headless AI-native backend for RTerm / neuralOS — v3.1.0: systematic bug-hunt audit, all 12 candidates confirmed-not-a-bug.",
5
5
  "main": "bin/gybackend.cjs",
6
- "bin": {
7
- "gybackend": "bin/gybackend.cjs",
8
- "rterm-backend": "bin/gybackend.cjs"
9
- },
10
- "scripts": {
11
- "start": "node bin/gybackend.cjs"
12
- },
13
- "dependencies": {
14
- "@nats-io/transport-node": "^3.4.0",
15
- "better-sqlite3": "^12.11.1",
16
- "cpu-features": "^0.0.10",
17
- "node-pty": "^1.2.0-beta.3",
18
- "ssh2": "^1.17.0",
19
- "tree-sitter-bash": "^0.25.1",
20
- "web-tree-sitter": "^0.26.3"
21
- },
22
- "optionalDependencies": {
23
- "serialport": "^13.0.0"
24
- },
25
- "engines": {
26
- "node": ">=18"
27
- },
28
- "os": [
29
- "darwin",
30
- "linux",
31
- "win32"
32
- ],
33
- "license": "Apache-2.0",
34
- "repository": {
35
- "type": "git",
36
- "url": "git+https://github.com/DrOlu/RTerm.git"
37
- },
38
- "keywords": [
39
- "rterm-backend",
40
- "neuralos",
41
- "rterm",
42
- "terminal",
43
- "ssh",
44
- "winrm",
45
- "serial",
46
- "ai-agent",
47
- "llm",
48
- "devops",
49
- "fleet",
50
- "automation",
51
- "headless",
52
- "backend",
53
- "daemon",
54
- "websocket",
55
- "rpc",
56
- "sre",
57
- "observability",
58
- "prometheus",
59
- "opentelemetry",
60
- "secrets",
61
- "on-call",
62
- "gitops",
63
- "cloud-inventory",
64
- "apm",
65
- "dem",
66
- "etw",
67
- "agentspan",
68
- "conductor",
69
- "monitoring"
70
- ]
6
+ "bin": { "gybackend": "bin/gybackend.cjs" },
7
+ "license": "MIT",
8
+ "engines": { "node": ">=18" }
71
9
  }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Sample plugin — Kubernetes SLO tracker.
3
+ *
4
+ * Demonstrates the RTerm plugin system: it registers an agent tool (evaluate a
5
+ * service's SLO from pod health), an event-driven trigger (pod CrashLoopBackOff),
6
+ * and a dashboard panel (the k8s SLO board). RTerm discovers this folder, loads
7
+ * it, calls register(ctx) with RTerm's services, and the capabilities appear
8
+ * automatically — the agent can then call k8s_slo_evaluate, and the trigger fires
9
+ * when a pod crashloops.
10
+ */
11
+ import type { PluginContext } from '../../packages/backend/src/services/plugin/pluginRegistry'
12
+
13
+ export function register(ctx: PluginContext): void {
14
+ ctx.log('[sample-k8s-slo] registering')
15
+
16
+ // Agent tool: evaluate a service's SLO from its pods.
17
+ ctx.registerTool({
18
+ name: 'k8s_slo_evaluate',
19
+ description: 'Evaluate a Kubernetes service SLO (SLI + error budget + burn rate) from its pod health.',
20
+ handler: async (args: Record<string, unknown>) => {
21
+ const service = String(args.service ?? 'default')
22
+ // In a real plugin this would run `kubectl get pods` via ctx.exec and compute.
23
+ // Here we return a structured stub so the agent can reason about it.
24
+ return {
25
+ service,
26
+ sli: 0.9992,
27
+ errorBudgetRemaining: 0.62,
28
+ burnRate: 0.38,
29
+ fastBurning: false,
30
+ podsReady: '12/13',
31
+ note: 'computed by the sample-k8s-slo plugin',
32
+ }
33
+ },
34
+ })
35
+
36
+ // Agent tool: list pods with high restart counts.
37
+ ctx.registerTool({
38
+ name: 'k8s_pod_restarts',
39
+ description: 'List Kubernetes pods with a restart count above a threshold.',
40
+ handler: async (args: Record<string, unknown>) => {
41
+ const min = Number(args.minRestarts ?? 5)
42
+ return { threshold: min, pods: [{ name: 'cache-5b7a2', restarts: 12, ready: false }], note: 'computed by the sample-k8s-slo plugin' }
43
+ },
44
+ })
45
+
46
+ // Trigger: fire a critical alert when a pod crashloops.
47
+ ctx.registerTrigger({
48
+ name: 'k8s-pod-crashloop',
49
+ kind: 'pattern',
50
+ match: 'CrashLoopBackOff',
51
+ action: 'critical-alert',
52
+ })
53
+
54
+ // Dashboard panel: the k8s SLO board.
55
+ ctx.registerPanel('k8s-slo-board', async () => {
56
+ return '<h3>Kubernetes SLO Board</h3><p>Rendered by the sample-k8s-slo plugin.</p>'
57
+ })
58
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "sample-k8s-slo",
3
+ "version": "1.0.0",
4
+ "description": "Sample plugin: track SLOs for Kubernetes services and alert on pod crashes",
5
+ "author": "RTerm",
6
+ "entry": "index.ts",
7
+ "tools": ["k8s_slo_evaluate", "k8s_pod_restarts"],
8
+ "triggers": [{ "name": "k8s-pod-crashloop", "kind": "pattern", "match": "CrashLoopBackOff" }],
9
+ "panels": ["k8s-slo-board"],
10
+ "permissions": ["exec_command", "read_ledger"]
11
+ }
package/LICENSE.md DELETED
@@ -1,201 +0,0 @@
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 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 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
- in such NOTICE file, excluding those 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
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2026 Hyperspace Technologies
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
package/README.md DELETED
@@ -1,31 +0,0 @@
1
- # gybackend
2
-
3
- Backend runtime bootstrap workspace for GyShell (internal/development entry).
4
-
5
- ## Run
6
-
7
- ```bash
8
- npm --workspace @gyshell/gybackend run build
9
- npm --workspace @gyshell/gybackend run start
10
- ```
11
-
12
- This workspace is mainly for repository development and runtime debugging. End users should use the desktop app. `gyll` / CLI TUI is deprecated and unsupported.
13
-
14
- ## Environment Variables
15
-
16
- - `GYBACKEND_WS_HOST` (default `0.0.0.0`)
17
- - `GYBACKEND_WS_PORT` (default `17888`)
18
- - `GYBACKEND_DATA_DIR` (default `./.gybackend-data` under current working directory)
19
- - `GYBACKEND_BOOTSTRAP_LOCAL_TERMINAL` (default `true`)
20
- - `GYBACKEND_TERMINAL_ID` (default `local-main`)
21
- - `GYBACKEND_TERMINAL_TITLE` (default `Local`)
22
- - `GYBACKEND_TERMINAL_CWD` (optional)
23
- - `GYBACKEND_TERMINAL_SHELL` (optional)
24
- - `GYBACKEND_MODEL` (optional bootstrap model name)
25
- - `GYBACKEND_API_KEY` (optional bootstrap model API key)
26
- - `GYBACKEND_BASE_URL` (optional bootstrap model base URL)
27
-
28
- ## Notes
29
-
30
- - gybackend delegates shared backend behavior to `packages/backend`.
31
- - MCP runtime is active through the shared backend core.
@@ -1,328 +0,0 @@
1
- /**
2
- * agentspan-bridge.extreme.spec.ts — exhaustive offline tests for the
3
- * AgentSpan/Conductor bridge: the dependency-free HTTP client (URL building,
4
- * auth headers, error mapping, every endpoint) and the plugin glue (config
5
- * resolution, auth blob parsing, status/row normalization, tool wiring,
6
- * unreachable-server resilience, trigger match). No network — fetch is mocked.
7
- */
8
- import { test } from 'node:test'
9
- import assert from 'node:assert/strict'
10
- import { ConductorClient, ConductorApiError, authHeaders, joinUrl, DEFAULT_BASE_URL } from './conductorClient.mjs'
11
- import {
12
- register,
13
- resolveConfig,
14
- parseAuthBlob,
15
- buildClient,
16
- summarizeStatus,
17
- toExecutionRows,
18
- isFailedExecution,
19
- } from './index.mjs'
20
-
21
- // ─── mock fetch ─────────────────────────────────────────────────────────────
22
- /** A scriptable fetch mock: records calls, returns queued/mapped responses. */
23
- function mockFetch(respond) {
24
- const calls = []
25
- const fn = async (url, init) => {
26
- calls.push({ url, init })
27
- const r = typeof respond === 'function' ? respond(url, init, calls.length) : respond
28
- return { ok: r.ok !== false && (r.status ?? 200) < 400, status: r.status ?? 200, text: async () => r.text ?? (r.json !== undefined ? JSON.stringify(r.json) : '') }
29
- }
30
- fn.calls = calls
31
- return fn
32
- }
33
-
34
- // ─── conductorClient: URL + auth header building ───────────────────────────
35
- test('joinUrl joins base+path with a single slash', () => {
36
- assert.equal(joinUrl('http://h:6767/', '/api/agent/start'), 'http://h:6767/api/agent/start')
37
- assert.equal(joinUrl('http://h:6767', 'api/agent/start'), 'http://h:6767/api/agent/start')
38
- assert.equal(joinUrl(undefined, '/x'), `${DEFAULT_BASE_URL}/x`)
39
- })
40
-
41
- test('authHeaders only sends X-Auth-* when both key+secret present', () => {
42
- assert.deepEqual(authHeaders(undefined), { 'content-type': 'application/json', accept: 'application/json' })
43
- assert.deepEqual(authHeaders({ key: 'k' }), { 'content-type': 'application/json', accept: 'application/json' })
44
- const h = authHeaders({ key: 'k', secret: 's' })
45
- assert.equal(h['X-Auth-Key'], 'k')
46
- assert.equal(h['X-Auth-Secret'], 's')
47
- })
48
-
49
- test('ConductorClient requires a fetchImpl', () => {
50
- assert.throws(() => new ConductorClient({}), /fetchImpl/)
51
- })
52
-
53
- // ─── conductorClient: endpoints ────────────────────────────────────────────
54
- test('health() maps actuator health to {ok,status} and never throws', async () => {
55
- const up = new ConductorClient({ fetchImpl: mockFetch({ json: { status: 'UP' } }) })
56
- assert.deepEqual(await up.health(), { ok: true, status: 'UP', raw: { status: 'UP' } })
57
- const down = new ConductorClient({ fetchImpl: mockFetch(() => { throw new Error('ECONNREFUSED') }) })
58
- const h = await down.health()
59
- assert.equal(h.ok, false)
60
- assert.equal(h.status, 'DOWN')
61
- assert.match(h.error, /ECONNREFUSED/)
62
- })
63
-
64
- test('runAgent posts to /api/agent/start and extracts executionId', async () => {
65
- const f = mockFetch({ json: { executionId: 'exec-123' } })
66
- const c = new ConductorClient({ fetchImpl: f })
67
- const r = await c.runAgent({ name: 'a' }, 'hello')
68
- assert.equal(r.executionId, 'exec-123')
69
- const call = f.calls[0]
70
- assert.equal(call.url, `${DEFAULT_BASE_URL}/api/agent/start`)
71
- assert.equal(call.init.method, 'POST')
72
- const body = JSON.parse(call.init.body)
73
- assert.deepEqual(body.agent, { name: 'a' })
74
- assert.equal(body.input, 'hello')
75
- })
76
-
77
- test('runAgent falls back to workflowId/id when executionId absent', async () => {
78
- const c = new ConductorClient({ fetchImpl: mockFetch({ json: { workflowId: 'wf-9' } }) })
79
- assert.equal((await c.runAgent({ name: 'a' })).executionId, 'wf-9')
80
- })
81
-
82
- test('agentStatus/Respond/Stop hit the lifecycle endpoints + require id', async () => {
83
- const f = mockFetch({ json: { status: 'RUNNING' } })
84
- const c = new ConductorClient({ fetchImpl: f })
85
- await assert.rejects(() => c.agentStatus(), /executionId/)
86
- await c.agentStatus('e1')
87
- await c.agentRespond('e1', { approved: true })
88
- await c.agentStop('e1')
89
- const urls = f.calls.map((x) => `${x.init.method} ${x.url}`)
90
- assert.ok(urls.includes(`GET ${DEFAULT_BASE_URL}/api/agent/e1`))
91
- assert.ok(urls.includes(`POST ${DEFAULT_BASE_URL}/api/agent/e1/respond`))
92
- assert.ok(urls.includes(`POST ${DEFAULT_BASE_URL}/api/agent/e1/stop`))
93
- })
94
-
95
- test('startWorkflow builds the right path + returns the id string', async () => {
96
- const f = mockFetch({ text: 'wf-abc' })
97
- const c = new ConductorClient({ fetchImpl: f })
98
- const id = await c.startWorkflow('cleanup', { host: 'web-1' }, { version: 3 })
99
- assert.equal(id, 'wf-abc')
100
- assert.match(f.calls[0].url, /\/api\/workflow\/cleanup\?version=3$/)
101
- })
102
-
103
- test('getWorkflow/terminate/retry/search hit the engine surface', async () => {
104
- const f = mockFetch({ json: { results: [] } })
105
- const c = new ConductorClient({ fetchImpl: f })
106
- await c.getWorkflow('w1')
107
- await c.terminateWorkflow('w1', 'done')
108
- await c.retryWorkflow('w1')
109
- await c.searchWorkflows('status:FAILED', 5)
110
- const urls = f.calls.map((x) => `${x.init.method} ${x.url}`)
111
- assert.ok(urls.some((u) => u.startsWith(`GET ${DEFAULT_BASE_URL}/api/workflow/w1?includeTasks=`)))
112
- assert.ok(urls.some((u) => u.startsWith(`DELETE ${DEFAULT_BASE_URL}/api/workflow/w1?reason=done`)))
113
- assert.ok(urls.includes(`POST ${DEFAULT_BASE_URL}/api/workflow/w1/retry`))
114
- assert.ok(urls.some((u) => u.includes('/api/workflow/search?') && u.includes('status%3AFAILED')))
115
- })
116
-
117
- test('non-2xx responses raise ConductorApiError with status + body', async () => {
118
- // health() swallows errors into {ok:false}; other methods raise ConductorApiError.
119
- const up = new ConductorClient({ fetchImpl: mockFetch({ ok: false, status: 500, text: 'boom' }) })
120
- const h = await up.health()
121
- assert.equal(h.ok, false)
122
- const c2 = new ConductorClient({ fetchImpl: mockFetch({ ok: false, status: 500, text: 'boom' }) })
123
- await assert.rejects(() => c2.getWorkflow('w1'), ConductorApiError)
124
- const c3 = new ConductorClient({ fetchImpl: mockFetch({ ok: false, status: 404, text: 'nope' }) })
125
- await assert.rejects(() => c3.agentStatus('x'), ConductorApiError)
126
- })
127
-
128
- // ─── plugin glue: config + auth ────────────────────────────────────────────
129
- test('resolveConfig prefers settings, falls back to env, strips trailing slash', () => {
130
- const c = resolveConfig({ settings: { agentspan: { serverUrl: 'http://srv:6767/', authSecretRef: 'as-auth' } } }, {})
131
- assert.equal(c.serverUrl, 'http://srv:6767')
132
- assert.equal(c.authSecretRef, 'as-auth')
133
- const env = resolveConfig({}, { AGENTSPAN_SERVER_URL: 'http://env:6767/' })
134
- assert.equal(env.serverUrl, 'http://env:6767')
135
- assert.equal(resolveConfig({}, {}).serverUrl, DEFAULT_BASE_URL)
136
- })
137
-
138
- test('parseAuthBlob parses KEY=VAL lines into {key,secret}', () => {
139
- assert.deepEqual(parseAuthBlob('AGENTSPAN_AUTH_KEY=k\nAGENTSPAN_AUTH_SECRET=s'), { key: 'k', secret: 's' })
140
- assert.deepEqual(parseAuthBlob('AUTH_KEY=a\nAUTH_SECRET=b'), { key: 'a', secret: 'b' })
141
- assert.equal(parseAuthBlob('AGENTSPAN_AUTH_KEY=only'), undefined)
142
- assert.equal(parseAuthBlob(''), undefined)
143
- assert.equal(parseAuthBlob(undefined), undefined)
144
- })
145
-
146
- test('buildClient wires auth from ctx.getSecret + configures baseUrl', () => {
147
- const ctx = {
148
- settings: { agentspan: { serverUrl: 'http://srv:6767', authSecretRef: 'as-auth' } },
149
- getSecret: (k) => (k === 'as-auth' ? 'AGENTSPAN_AUTH_KEY=k\nAGENTSPAN_AUTH_SECRET=s' : undefined),
150
- }
151
- const { client, config } = buildClient(ctx, mockFetch({ json: {} }))
152
- assert.equal(config.serverUrl, 'http://srv:6767')
153
- assert.equal(client.auth.key, 'k')
154
- // missing secret → no auth, no crash
155
- const noSecret = buildClient({ settings: { agentspan: { authSecretRef: 'nope' } }, getSecret: () => undefined }, mockFetch({ json: {} }))
156
- assert.equal(noSecret.client.auth, undefined)
157
- })
158
-
159
- // ─── plugin glue: normalization helpers ────────────────────────────────────
160
- test('summarizeStatus normalizes agent + workflow payloads', () => {
161
- const a = summarizeStatus({ executionId: 'e1', agentName: 'bot', status: 'RUNNING', tasks: [{ status: 'COMPLETED' }, { status: 'FAILED' }] })
162
- assert.equal(a.status, 'RUNNING')
163
- assert.equal(a.taskCount, 2)
164
- assert.equal(a.completedTasks, 1)
165
- assert.equal(a.failedTasks, 1)
166
- const w = summarizeStatus({ workflowId: 'w1', workflowName: 'cleanup', status: 'COMPLETED', reasonForIncompletion: undefined })
167
- assert.equal(w.name, 'cleanup')
168
- assert.equal(w.status, 'COMPLETED')
169
- assert.deepEqual(summarizeStatus(null), { status: 'UNKNOWN' })
170
- })
171
-
172
- test('toExecutionRows handles results/workflows/array shapes', () => {
173
- assert.equal(toExecutionRows({ results: [{ workflowId: 'a', workflowName: 'x', status: 'RUNNING' }] }).length, 1)
174
- assert.equal(toExecutionRows({ workflows: [{ id: 'b', name: 'y', status: 'FAILED' }] })[0].status, 'FAILED')
175
- assert.equal(toExecutionRows([{ workflowId: 'c' }]).length, 1)
176
- assert.deepEqual(toExecutionRows({}), [])
177
- })
178
-
179
- test('isFailedExecution matches terminal-failure statuses only', () => {
180
- assert.ok(isFailedExecution('FAILED'))
181
- assert.ok(isFailedExecution('terminated'))
182
- assert.ok(isFailedExecution('TIMED_OUT'))
183
- assert.ok(!isFailedExecution('RUNNING'))
184
- assert.ok(!isFailedExecution('COMPLETED'))
185
- })
186
-
187
- // ─── plugin registration + tool behavior (mocked server) ──────────────────
188
- /** Build a ctx with register* capture + a mocked client injected. */
189
- function makeCtx(fetchImpl, settings = {}) {
190
- const tools = new Map()
191
- const triggers = []
192
- const panels = []
193
- const logs = []
194
- const ctx = {
195
- settings: { agentspan: settings },
196
- registerTool: (t) => tools.set(t.name, t),
197
- registerTrigger: (t) => triggers.push(t),
198
- registerPanel: (p) => panels.push(p),
199
- log: (l) => logs.push(l),
200
- }
201
- // inject the mocked fetch by overriding buildClient's realFetch via a hack:
202
- // we re-register with a patched client below.
203
- return { tools, triggers, panels, logs, ctx }
204
- }
205
-
206
- test('register wires 9 tools, 1 trigger, 1 panel', () => {
207
- const { tools, triggers, panels, ctx } = makeCtx(null, { serverUrl: 'http://x:6767' })
208
- register(ctx)
209
- assert.equal(tools.size, 9)
210
- for (const n of ['agentspan_health', 'agentspan_run', 'agentspan_status', 'agentspan_approve', 'agentspan_list', 'agentspan_stop', 'agentspan_export_playbook', 'agentspan_register_playbook', 'agentspan_delegate']) assert.ok(tools.has(n), `missing ${n}`)
211
- assert.equal(triggers.length, 1)
212
- assert.equal(panels.length, 1)
213
- })
214
-
215
- test('agentspan_health returns error+hint when server unreachable (no throw)', async () => {
216
- const { tools, ctx } = makeCtx(null, { serverUrl: 'http://down:6767' })
217
- // force a failing fetch by monkey-patching global fetch
218
- const realFetch = globalThis.fetch
219
- globalThis.fetch = async () => { throw new Error('ECONNREFUSED') }
220
- register(ctx)
221
- const r = await tools.get('agentspan_health').handler({})
222
- assert.equal(r.error && true, true)
223
- assert.match(r.hint, /AgentSpan server running/)
224
- globalThis.fetch = realFetch
225
- })
226
-
227
- test('agentspan_run (agentConfig) returns executionId + uiUrl from a live mock server', async () => {
228
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
229
- const realFetch = globalThis.fetch
230
- globalThis.fetch = async (url, init) => ({
231
- ok: true, status: 200,
232
- text: async () => JSON.stringify({ executionId: 'exec-42' }),
233
- })
234
- register(ctx)
235
- const r = await tools.get('agentspan_run').handler({ agentConfig: { name: 'a' }, prompt: 'hi' })
236
- assert.equal(r.executionId, 'exec-42')
237
- assert.match(r.uiUrl, /\/execution\/exec-42$/)
238
- globalThis.fetch = realFetch
239
- })
240
-
241
- test('agentspan_run (workflow) returns workflowId; needs agentConfig-or-workflow', async () => {
242
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
243
- const realFetch = globalThis.fetch
244
- globalThis.fetch = async () => ({ ok: true, status: 200, text: async () => 'wf-7' })
245
- register(ctx)
246
- const r = await tools.get('agentspan_run').handler({ workflow: 'cleanup', input: { h: 1 } })
247
- assert.equal(r.workflowId, 'wf-7')
248
- const bad = await tools.get('agentspan_run').handler({})
249
- assert.match(bad.error, /agentConfig or workflow/)
250
- globalThis.fetch = realFetch
251
- })
252
-
253
- test('agentspan_status falls back to workflow engine when agent surface 404s', async () => {
254
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
255
- const realFetch = globalThis.fetch
256
- globalThis.fetch = async (url) => {
257
- if (url.includes('/api/agent/')) return { ok: false, status: 404, text: async () => 'not an agent' }
258
- return { ok: true, status: 200, text: async () => JSON.stringify({ workflowId: 'w1', workflowName: 'cleanup', status: 'COMPLETED', tasks: [] }) }
259
- }
260
- register(ctx)
261
- const r = await tools.get('agentspan_status').handler({ executionId: 'w1' })
262
- assert.equal(r.kind, 'workflow')
263
- assert.equal(r.status, 'COMPLETED')
264
- globalThis.fetch = realFetch
265
- })
266
-
267
- test('agentspan_approve responds + reports new status; requires id', async () => {
268
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
269
- const realFetch = globalThis.fetch
270
- const posted = []
271
- globalThis.fetch = async (url, init) => {
272
- if (init.method === 'POST' && url.includes('/respond')) { posted.push(url); return { ok: true, status: 200, text: async () => '' } }
273
- return { ok: true, status: 200, text: async () => JSON.stringify({ executionId: 'e1', status: 'RUNNING' }) }
274
- }
275
- register(ctx)
276
- const bad = await tools.get('agentspan_approve').handler({})
277
- assert.match(bad.error, /executionId/)
278
- const r = await tools.get('agentspan_approve').handler({ executionId: 'e1', output: { approved: true } })
279
- assert.equal(r.responded, true)
280
- assert.ok(posted[0].includes('/api/agent/e1/respond'))
281
- globalThis.fetch = realFetch
282
- })
283
-
284
- test('agentspan_list returns normalized execution rows', async () => {
285
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
286
- const realFetch = globalThis.fetch
287
- globalThis.fetch = async () => ({ ok: true, status: 200, text: async () => JSON.stringify({ results: [{ workflowId: 'a', workflowName: 'x', status: 'RUNNING' }, { workflowId: 'b', workflowName: 'y', status: 'FAILED' }] }) })
288
- register(ctx)
289
- const r = await tools.get('agentspan_list').handler({})
290
- assert.equal(r.count, 2)
291
- assert.equal(r.executions[1].status, 'FAILED')
292
- globalThis.fetch = realFetch
293
- })
294
-
295
- test('agentspan_stop tries agent stop then terminates workflow; requires id', async () => {
296
- const { tools, ctx } = makeCtx(null, { serverUrl: DEFAULT_BASE_URL })
297
- const realFetch = globalThis.fetch
298
- const calls = []
299
- globalThis.fetch = async (url, init) => {
300
- calls.push(`${init.method} ${url}`)
301
- if (url.includes('/api/agent/') && url.includes('/stop')) return { ok: false, status: 404, text: async () => 'no' }
302
- return { ok: true, status: 200, text: async () => '' }
303
- }
304
- register(ctx)
305
- const bad = await tools.get('agentspan_stop').handler({})
306
- assert.match(bad.error, /executionId/)
307
- const r = await tools.get('agentspan_stop').handler({ executionId: 'w1' })
308
- assert.equal(r.stopped, true)
309
- assert.ok(calls.some((c) => c.startsWith(`DELETE ${DEFAULT_BASE_URL}/api/workflow/w1`)))
310
- globalThis.fetch = realFetch
311
- })
312
-
313
- test('trigger fires only for agentspan FAILED events', () => {
314
- const { triggers, ctx } = makeCtx(null, {})
315
- register(ctx)
316
- const t = triggers[0]
317
- assert.ok(t.match({ source: 'agentspan', status: 'FAILED' }))
318
- assert.ok(!t.match({ source: 'agentspan', status: 'RUNNING' }))
319
- assert.ok(!t.match({ source: 'netdata', status: 'FAILED' }))
320
- })
321
-
322
- test('panel renders an executions table', () => {
323
- const { panels, ctx } = makeCtx(null, { serverUrl: 'http://x:6767' })
324
- register(ctx)
325
- const html = panels[0].render([{ name: 'cleanup', id: 'e1', status: 'RUNNING', startTime: 'now' }])
326
- assert.match(html, /cleanup/)
327
- assert.match(html, /http:\/\/x:6767/)
328
- })
@@ -1,282 +0,0 @@
1
- /**
2
- * agentspan-bridge.phase2.extreme.spec.ts — exhaustive offline tests for the
3
- * Phase-2 additions: playbookToWorkflowDef mapper (step→task mapping, DAG
4
- * edges, wait/rollback, retries), the conductorClient registerWorkflowDef /
5
- * getWorkflowDef methods, and the new tools (agentspan_export_playbook,
6
- * agentspan_register_playbook, agentspan_delegate) with mocked fetch. No network.
7
- */
8
- import { test } from 'node:test'
9
- import assert from 'node:assert/strict'
10
- import { ConductorClient, DEFAULT_BASE_URL } from './conductorClient.mjs'
11
- import {
12
- playbookToWorkflowDef,
13
- stepToTask,
14
- rollbackToTask,
15
- taskRef,
16
- } from './playbookToWorkflowDef.mjs'
17
- import { register, findPlaybook, buildDelegateAgentConfig } from './index.mjs'
18
-
19
- // ─── mock fetch ─────────────────────────────────────────────────────────────
20
- function mockFetch(respond) {
21
- const calls = []
22
- const fn = async (url, init) => {
23
- calls.push({ url, init })
24
- const r = typeof respond === 'function' ? respond(url, init) : respond
25
- return { ok: r.ok !== false && (r.status ?? 200) < 400, status: r.status ?? 200, text: async () => r.text ?? (r.json !== undefined ? JSON.stringify(r.json) : '') }
26
- }
27
- fn.calls = calls
28
- return fn
29
- }
30
-
31
- const samplePlaybook = {
32
- id: 'pb-1',
33
- name: 'nightly backup',
34
- description: 'backup the core switch',
35
- steps: [
36
- { id: 'st-1', name: 'prep', kind: 'command', command: 'term length 0' },
37
- { id: 'st-2', name: 'collect', kind: 'script', scriptId: 'scr-9' },
38
- { id: 'st-3', name: 'settle', kind: 'wait', waitSeconds: 5 },
39
- { id: 'st-4', name: 'apply', kind: 'command', command: 'apply acl', rollback: { kind: 'command', command: 'no acl' }, dependsOn: ['st-1', 'st-2'] },
40
- ],
41
- }
42
-
43
- // ─── taskRef ────────────────────────────────────────────────────────────────
44
- test('taskRef sanitizes to Conductor-safe refs', () => {
45
- assert.equal(taskRef('st-1'), 'st_1')
46
- assert.equal(taskRef('apply acl!'), 'apply_acl_')
47
- assert.equal(taskRef(undefined, 'fallback'), 'fallback')
48
- assert.equal(taskRef(''), 'step')
49
- })
50
-
51
- // ─── stepToTask ─────────────────────────────────────────────────────────────
52
- test('command step → HTTP run_command task with command + validate', () => {
53
- const t = stepToTask({ id: 'st-1', kind: 'command', command: 'show run', validate: { expect: 'ok' } }, 0, {})
54
- assert.equal(t.type, 'HTTP')
55
- assert.equal(t.taskReferenceName, 'st_1')
56
- const req = t.inputParameters.http_request
57
- assert.equal(req.method, 'POST')
58
- assert.equal(req.body.kind, 'run_command')
59
- assert.equal(req.body.command, 'show run')
60
- assert.deepEqual(req.body.validate, { expect: 'ok' })
61
- })
62
-
63
- test('script step → SIMPLE script-reference task (scriptId, no inline body)', () => {
64
- const t = stepToTask({ id: 'st-2', kind: 'script', scriptId: 'scr-9', name: 'collect' }, 1, {})
65
- assert.equal(t.type, 'SIMPLE')
66
- assert.equal(t.inputParameters.kind, 'rterm_script')
67
- assert.equal(t.inputParameters.scriptId, 'scr-9')
68
- assert.equal(t.inputParameters.name, 'collect')
69
- })
70
-
71
- test('wait step → Conductor WAIT task with duration', () => {
72
- const t = stepToTask({ id: 'st-3', kind: 'wait', waitSeconds: 7 }, 2, {})
73
- assert.equal(t.type, 'WAIT')
74
- assert.equal(t.inputParameters.duration, 7)
75
- })
76
-
77
- test('onError=continue sets retryCount; stop (default) is 0', () => {
78
- const cont = stepToTask({ id: 'a', kind: 'command', command: 'x', onError: 'continue' }, 0, { continueRetryCount: 3 })
79
- assert.equal(cont.retryCount, 3)
80
- const stop = stepToTask({ id: 'b', kind: 'command', command: 'x' }, 1, {})
81
- assert.equal(stop.retryCount, 0)
82
- })
83
-
84
- // ─── rollbackToTask ─────────────────────────────────────────────────────────
85
- test('rollback command → optional compensating HTTP task', () => {
86
- const t = rollbackToTask({ kind: 'command', command: 'no acl' }, 'st_4', 0)
87
- assert.equal(t.type, 'HTTP')
88
- assert.equal(t.optional, true)
89
- assert.equal(t.inputParameters.http_request.body.compensating, true)
90
- assert.match(t.taskReferenceName, /^rollback_st_4_/)
91
- })
92
-
93
- test('rollback script → optional compensating SIMPLE task', () => {
94
- const t = rollbackToTask({ kind: 'script', scriptId: 'undo' }, 'st_1', 1)
95
- assert.equal(t.type, 'SIMPLE')
96
- assert.equal(t.inputParameters.scriptId, 'undo')
97
- assert.equal(t.optional, true)
98
- })
99
-
100
- // ─── playbookToWorkflowDef: full mapping ────────────────────────────────────
101
- test('maps all 4 steps + rollback compensating task in order', () => {
102
- const def = playbookToWorkflowDef(samplePlaybook, { execUri: 'http://gw:17888/rpc/exec' })
103
- assert.equal(def.name, 'nightly_backup')
104
- assert.equal(def.version, 1)
105
- assert.equal(def.schemaVersion, 2)
106
- assert.equal(def.restartable, true)
107
- // 4 step tasks + 1 JOIN (st-4 has 2 deps) + 1 rollback = 6
108
- const types = def.tasks.map((t) => t.type)
109
- assert.equal(types.filter((x) => x === 'JOIN').length, 1, 'one JOIN for the 2-dep step')
110
- assert.equal(types.filter((x) => x === 'WAIT').length, 1, 'one WAIT')
111
- const rollback = def.tasks[def.tasks.length - 1]
112
- assert.equal(rollback.optional, true, 'last task is the compensating rollback')
113
- assert.equal(rollback.inputParameters.http_request.body.command, 'no acl')
114
- })
115
-
116
- test('JOIN carries the dependsOn edges (fan-in)', () => {
117
- const def = playbookToWorkflowDef(samplePlaybook, {})
118
- const join = def.tasks.find((t) => t.type === 'JOIN')
119
- assert.deepEqual(join.joinOn, ['st_1', 'st_2'])
120
- // the dependent task (st-4) appears after the JOIN in order
121
- const joinIdx = def.tasks.indexOf(join)
122
- const st4 = def.tasks.find((t) => t.taskReferenceName === 'st_4')
123
- assert.ok(def.tasks.indexOf(st4) > joinIdx, 'dependent task comes after its JOIN')
124
- })
125
-
126
- test('linear playbook (no dependsOn) emits no JOINs', () => {
127
- const pb = { name: 'linear', steps: [
128
- { id: 'a', kind: 'command', command: '1' },
129
- { id: 'b', kind: 'command', command: '2' },
130
- { id: 'c', kind: 'wait', waitSeconds: 1 },
131
- ] }
132
- const def = playbookToWorkflowDef(pb, {})
133
- assert.equal(def.tasks.filter((t) => t.type === 'JOIN').length, 0)
134
- assert.equal(def.tasks.length, 3)
135
- })
136
-
137
- test('multiple rollbacks run in reverse step order (undo newest first)', () => {
138
- const pb = { name: 'multi', steps: [
139
- { id: 'a', kind: 'command', command: 'a1', rollback: { kind: 'command', command: 'undo-a' } },
140
- { id: 'b', kind: 'command', command: 'b1', rollback: { kind: 'command', command: 'undo-b' } },
141
- ] }
142
- const def = playbookToWorkflowDef(pb, {})
143
- const rbs = def.tasks.filter((t) => t.optional)
144
- assert.equal(rbs.length, 2)
145
- assert.equal(rbs[0].inputParameters.http_request.body.command, 'undo-b', 'newest rollback first')
146
- assert.equal(rbs[1].inputParameters.http_request.body.command, 'undo-a')
147
- })
148
-
149
- test('execUri flows into the command tasks + inputTemplate', () => {
150
- const def = playbookToWorkflowDef(samplePlaybook, { execUri: 'http://gw:9000/exec' })
151
- const cmdTask = def.tasks.find((t) => t.type === 'HTTP')
152
- assert.equal(cmdTask.inputParameters.http_request.uri, 'http://gw:9000/exec')
153
- assert.equal(def.inputTemplate.rtermExecUri, 'http://gw:9000/exec')
154
- })
155
-
156
- test('rejects a playbook without steps', () => {
157
- assert.throws(() => playbookToWorkflowDef({ name: 'x' }), /steps array/)
158
- assert.throws(() => playbookToWorkflowDef(null), /steps array/)
159
- })
160
-
161
- // ─── conductorClient: registerWorkflowDef / getWorkflowDef ─────────────────
162
- test('registerWorkflowDef POSTs an array to /api/metadata/workflow', async () => {
163
- const f = mockFetch({ json: {} })
164
- const c = new ConductorClient({ fetchImpl: f })
165
- const def = playbookToWorkflowDef(samplePlaybook, {})
166
- await c.registerWorkflowDef(def)
167
- const call = f.calls[0]
168
- assert.equal(call.url, `${DEFAULT_BASE_URL}/api/metadata/workflow`)
169
- assert.equal(call.init.method, 'POST')
170
- const body = JSON.parse(call.init.body)
171
- assert.ok(Array.isArray(body), 'body is an array of defs')
172
- assert.equal(body[0].name, 'nightly_backup')
173
- })
174
-
175
- test('registerWorkflowDef accepts an array + rejects empty', async () => {
176
- const c = new ConductorClient({ fetchImpl: mockFetch({ json: {} }) })
177
- await assert.rejects(() => c.registerWorkflowDef(), /WorkflowDef/)
178
- })
179
-
180
- test('getWorkflowDef GETs by name (+version)', async () => {
181
- const f = mockFetch({ json: { name: 'x', version: 2 } })
182
- const c = new ConductorClient({ fetchImpl: f })
183
- await c.getWorkflowDef('nightly_backup', 2)
184
- assert.match(f.calls[0].url, /\/api\/metadata\/workflow\/nightly_backup\?version=2$/)
185
- await assert.rejects(() => c.getWorkflowDef(), /name/)
186
- })
187
-
188
- // ─── index helpers: findPlaybook / buildDelegateAgentConfig ────────────────
189
- test('findPlaybook resolves from AutomationManager then settings, by id or name', () => {
190
- const pb = { id: 'pb-1', name: 'nightly' }
191
- const viaAm = findPlaybook({ automationManager: { getPlaybook: (x) => (x === 'pb-1' ? pb : undefined) } }, 'pb-1')
192
- assert.equal(viaAm.name, 'nightly')
193
- const viaSettings = findPlaybook({ settings: { automation: { playbooks: [pb] } } }, 'nightly')
194
- assert.equal(viaSettings.id, 'pb-1')
195
- assert.equal(findPlaybook({ settings: { automation: { playbooks: [] } } }, 'ghost'), undefined)
196
- assert.equal(findPlaybook({}, undefined), undefined)
197
- })
198
-
199
- test('buildDelegateAgentConfig builds a valid durable AgentConfig', () => {
200
- const c = buildDelegateAgentConfig('mybot', 'do the thing', { model: 'anthropic/claude-sonnet-4.6' })
201
- assert.equal(c.name, 'mybot')
202
- assert.equal(c.model, 'anthropic/claude-sonnet-4.6')
203
- assert.equal(c.input, 'do the thing')
204
- const def = buildDelegateAgentConfig(undefined, 't')
205
- assert.equal(def.name, 'rterm_delegate')
206
- assert.equal(def.model, 'openai/gpt-4o')
207
- })
208
-
209
- // ─── new tools (mocked server) ─────────────────────────────────────────────
210
- function makeCtx(playbooks, fetchImpl) {
211
- const tools = new Map()
212
- const triggers = []
213
- const panels = []
214
- const ctx = {
215
- settings: { agentspan: { serverUrl: DEFAULT_BASE_URL }, automation: { playbooks } },
216
- registerTool: (t) => tools.set(t.name, t),
217
- registerTrigger: (t) => triggers.push(t),
218
- registerPanel: (p) => panels.push(p),
219
- log: () => {},
220
- }
221
- return { tools, ctx, fetchImpl }
222
- }
223
-
224
- test('registers 9 tools now (6 phase-1 + 3 phase-2)', () => {
225
- const { tools, ctx } = makeCtx([], null)
226
- register(ctx)
227
- assert.equal(tools.size, 9)
228
- for (const n of ['agentspan_export_playbook', 'agentspan_register_playbook', 'agentspan_delegate']) assert.ok(tools.has(n), `missing ${n}`)
229
- })
230
-
231
- test('agentspan_export_playbook returns the mapped def without registering', async () => {
232
- const posted = []
233
- const realFetch = globalThis.fetch
234
- globalThis.fetch = async (url, init) => { posted.push(url); return { ok: true, status: 200, text: async () => '{}' } }
235
- const { tools, ctx } = makeCtx([samplePlaybook], null)
236
- register(ctx)
237
- const r = await tools.get('agentspan_export_playbook').handler({ playbook: 'nightly backup' })
238
- assert.equal(r.name, 'nightly_backup')
239
- assert.ok(r.taskCount >= 5)
240
- assert.ok(r.def.tasks.some((t) => t.type === 'WAIT'))
241
- assert.equal(posted.length, 0, 'export is pure — no HTTP calls')
242
- const missing = await tools.get('agentspan_export_playbook').handler({ playbook: 'ghost' })
243
- assert.match(missing.error, /not found/)
244
- globalThis.fetch = realFetch
245
- })
246
-
247
- test('agentspan_register_playbook registers the def on the server', async () => {
248
- const calls = []
249
- const realFetch = globalThis.fetch
250
- globalThis.fetch = async (url, init) => {
251
- calls.push({ url, method: init.method })
252
- return { ok: true, status: 200, text: async () => '{}' }
253
- }
254
- const { tools, ctx } = makeCtx([samplePlaybook], null)
255
- register(ctx)
256
- const r = await tools.get('agentspan_register_playbook').handler({ playbook: 'nightly backup' })
257
- assert.equal(r.registered, true)
258
- assert.equal(r.name, 'nightly_backup')
259
- assert.equal(r.runWith.args.workflow, 'nightly_backup')
260
- assert.ok(calls.some((c) => c.url.endsWith('/api/metadata/workflow') && c.method === 'POST'))
261
- globalThis.fetch = realFetch
262
- })
263
-
264
- test('agentspan_delegate builds an AgentConfig and returns executionId + followUp', async () => {
265
- const realFetch = globalThis.fetch
266
- let postedBody
267
- globalThis.fetch = async (url, init) => {
268
- if (init.method === 'POST') postedBody = JSON.parse(init.body)
269
- return { ok: true, status: 200, text: async () => JSON.stringify({ executionId: 'exec-del-1' }) }
270
- }
271
- const { tools, ctx } = makeCtx([], null)
272
- register(ctx)
273
- const bad = await tools.get('agentspan_delegate').handler({})
274
- assert.match(bad.error, /prompt/)
275
- const r = await tools.get('agentspan_delegate').handler({ prompt: 'investigate the disk-full on web-01', model: 'openai/gpt-5.6-sol' })
276
- assert.equal(r.delegated, true)
277
- assert.equal(r.executionId, 'exec-del-1')
278
- assert.match(r.uiUrl, /\/execution\/exec-del-1$/)
279
- assert.equal(postedBody.model, 'openai/gpt-5.6-sol')
280
- assert.equal(postedBody.input, 'investigate the disk-full on web-01')
281
- globalThis.fetch = realFetch
282
- })
@@ -1,252 +0,0 @@
1
- import {
2
- parseNetdataAlert, mapSeverity, buildFingerprint, toTriggerEvent, correlateWithRterm, register,
3
- } from './index.mjs'
4
-
5
- const cases: Array<{ name: string; run: () => void | Promise<void> }> = []
6
- function test(n: string, r: () => void | Promise<void>) { cases.push({ name: n, run: r }) }
7
-
8
- // ---- parseNetdataAlert ----
9
- test('parse: alert notification with all fields', () => {
10
- const payload = {
11
- message: 'CPU usage is 95%', alert: 'cpu_usage', info: 'CPU utilization too high',
12
- chart: 'system.cpu', context: 'system.cpu', space: 'prod-cluster', family: 'cpu',
13
- class: 'Error', severity: 'critical', date: '2026-07-22T10:00:00Z', duration: '5m',
14
- additional_active_critical_alerts: 2, additional_active_warning_alerts: 1,
15
- alert_url: 'https://app.netdata.cloud/alert/123',
16
- }
17
- const p = parseNetdataAlert(payload)
18
- if (!p || p.kind !== 'alert') throw new Error('should parse alert')
19
- if (p.alert !== 'cpu_usage') throw new Error('alert name')
20
- if (p.severity !== 'critical') throw new Error('severity')
21
- if (p.chart !== 'system.cpu') throw new Error('chart')
22
- if (p.additionalCritical !== 2) throw new Error('additional critical')
23
- if (p.host !== 'prod-cluster') throw new Error('host from space')
24
- if (p.alertUrl !== 'https://app.netdata.cloud/alert/123') throw new Error('alert url')
25
- })
26
-
27
- test('parse: warning severity', () => {
28
- const p = parseNetdataAlert({ alert: 'disk_space', severity: 'warning', message: 'Disk 80% full', space: 'web-01' })
29
- if (!p || p.severity !== 'warning') throw new Error('should be warning')
30
- })
31
-
32
- test('parse: clear severity (alert resolved)', () => {
33
- const p = parseNetdataAlert({ alert: 'cpu_usage', severity: 'clear', message: 'CPU back to normal', space: 'web-01' })
34
- if (!p || p.severity !== 'clear') throw new Error('should be clear')
35
- })
36
-
37
- test('parse: reachability notification (node down)', () => {
38
- const p = parseNetdataAlert({ message: 'Node unreachable', node: 'web-02', space: 'prod', status: 'down', date: '2026-07-22T10:00:00Z', duration: '2m' })
39
- if (!p || p.kind !== 'reachability') throw new Error('should parse reachability')
40
- if (p.status !== 'down') throw new Error('status')
41
- if (p.host !== 'web-02') throw new Error('host from node')
42
- })
43
-
44
- test('parse: reachability notification (node up)', () => {
45
- const p = parseNetdataAlert({ node: 'web-02', status: 'up', date: '2026-07-22T10:05:00Z' })
46
- if (!p || p.status !== 'up') throw new Error('should be up')
47
- })
48
-
49
- test('parse: null for invalid payload', () => {
50
- if (parseNetdataAlert(null) !== null) throw new Error('null payload')
51
- if (parseNetdataAlert({}) !== null) throw new Error('empty object')
52
- if (parseNetdataAlert('not an object') !== null) throw new Error('string')
53
- if (parseNetdataAlert({ foo: 'bar' }) !== null) throw new Error('missing required fields')
54
- })
55
-
56
- // ---- mapSeverity ----
57
- test('mapSeverity: critical -> critical', () => {
58
- if (mapSeverity('critical') !== 'critical') throw new Error('critical')
59
- })
60
- test('mapSeverity: warning -> warning', () => {
61
- if (mapSeverity('warning') !== 'warning') throw new Error('warning')
62
- })
63
- test('mapSeverity: clear -> info', () => {
64
- if (mapSeverity('clear') !== 'info') throw new Error('clear should map to info')
65
- })
66
- test('mapSeverity: unknown -> info', () => {
67
- if (mapSeverity('unknown') !== 'info') throw new Error('unknown')
68
- })
69
-
70
- // ---- buildFingerprint ----
71
- test('buildFingerprint: alert fingerprint', () => {
72
- const p = parseNetdataAlert({ alert: 'cpu_usage', severity: 'critical', space: 'web-01' })
73
- const fp = buildFingerprint(p)
74
- if (fp !== 'netdata:web-01:cpu_usage:critical') throw new Error(`got ${fp}`)
75
- })
76
- test('buildFingerprint: reachability fingerprint', () => {
77
- const p = parseNetdataAlert({ node: 'web-02', status: 'down' })
78
- const fp = buildFingerprint(p)
79
- if (fp !== 'netdata:reachability:web-02:down') throw new Error(`got ${fp}`)
80
- })
81
- test('buildFingerprint: empty for null', () => {
82
- if (buildFingerprint(null) !== '') throw new Error('should be empty')
83
- })
84
-
85
- // ---- toTriggerEvent ----
86
- test('toTriggerEvent: alert -> trigger event with correct severity', () => {
87
- const p = parseNetdataAlert({ alert: 'disk_full', severity: 'critical', space: 'db-01', message: 'Disk 95%', date: '2026-07-22T10:00:00Z' })
88
- const evt = toTriggerEvent(p)
89
- if (!evt) throw new Error('should produce event')
90
- if (evt.source !== 'netdata') throw new Error('source')
91
- if (evt.severity !== 'critical') throw new Error('severity')
92
- if (!evt.title.includes('disk_full')) throw new Error('title')
93
- if (!evt.title.includes('db-01')) throw new Error('title host')
94
- if (evt.labels.host !== 'db-01') throw new Error('labels host')
95
- if (evt.labels.alert !== 'disk_full') throw new Error('labels alert')
96
- })
97
-
98
- test('toTriggerEvent: reachability down -> critical', () => {
99
- const p = parseNetdataAlert({ node: 'web-03', status: 'down', date: '2026-07-22T10:00:00Z' })
100
- const evt = toTriggerEvent(p)
101
- if (!evt || evt.severity !== 'critical') throw new Error('down should be critical')
102
- if (!evt.title.includes('DOWN')) throw new Error('title')
103
- })
104
-
105
- test('toTriggerEvent: reachability up -> info', () => {
106
- const p = parseNetdataAlert({ node: 'web-03', status: 'up', date: '2026-07-22T10:00:00Z' })
107
- const evt = toTriggerEvent(p)
108
- if (!evt || evt.severity !== 'info') throw new Error('up should be info')
109
- })
110
-
111
- test('toTriggerEvent: null parsed -> null event', () => {
112
- if (toTriggerEvent(null) !== null) throw new Error('should be null')
113
- })
114
-
115
- // ---- correlateWithRterm ----
116
- test('correlate: with metrics + incidents', () => {
117
- const p = parseNetdataAlert({ alert: 'cpu_usage', severity: 'critical', space: 'web-01', additional_active_critical_alerts: 3 })
118
- const mockMetrics = { snapshot: (host: string) => ({ host, cpuUsagePercent: 95, memoryUsagePercent: 70 }) }
119
- const mockIncidents = { list: () => [
120
- { title: 'web-01 disk full', affected: ['web-01'], status: 'open' },
121
- { title: 'web-02 network issue', affected: ['web-02'], status: 'open' },
122
- { title: 'web-01 resolved issue', affected: ['web-01'], status: 'resolved' },
123
- ] }
124
- const result = correlateWithRterm(p, mockMetrics as any, mockIncidents as any)
125
- if (!result.recentMetrics || result.recentMetrics.cpuUsagePercent !== 95) throw new Error('metrics')
126
- if (result.openIncidents.length !== 1) throw new Error(`expected 1 open incident, got ${result.openIncidents.length}`)
127
- if (!result.correlation.includes('cpu_usage')) throw new Error('correlation should mention alert')
128
- if (!result.correlation.includes('disk full')) throw new Error('correlation should mention incident')
129
- if (!result.correlation.includes('3 additional critical')) throw new Error('correlation should mention additional alerts')
130
- })
131
-
132
- test('correlate: no prior context', () => {
133
- const p = parseNetdataAlert({ alert: 'mem_usage', severity: 'warning', space: 'new-host' })
134
- const result = correlateWithRterm(p, null, null)
135
- if (result.recentMetrics !== null) throw new Error('no metrics')
136
- if (result.openIncidents.length !== 0) throw new Error('no incidents')
137
- if (!result.correlation.includes('No prior RTerm context')) throw new Error('should say no context')
138
- })
139
-
140
- test('correlate: null parsed -> empty', () => {
141
- const result = correlateWithRterm(null, null, null)
142
- if (result.recentMetrics !== null || result.openIncidents.length !== 0) throw new Error('should be empty')
143
- })
144
-
145
- // ---- register (plugin lifecycle) ----
146
- test('register: registers 2 tools, 2 triggers, 1 panel', () => {
147
- const tools: any[] = [], triggers: any[] = [], panels: any[] = [], logs: string[] = []
148
- register({
149
- registerTool: (t) => tools.push(t),
150
- registerTrigger: (t) => triggers.push(t),
151
- registerPanel: (p) => panels.push(p),
152
- exec: async () => '',
153
- readLedger: () => ({}),
154
- log: (line: string) => logs.push(line),
155
- } as any)
156
- if (tools.length !== 2) throw new Error(`expected 2 tools, got ${tools.length}`)
157
- if (triggers.length !== 2) throw new Error(`expected 2 triggers, got ${triggers.length}`)
158
- if (panels.length !== 1) throw new Error(`expected 1 panel, got ${panels.length}`)
159
- if (!tools.some((t) => t.name === 'netdata_alert_summary')) throw new Error('missing alert_summary tool')
160
- if (!tools.some((t) => t.name === 'netdata_correlate')) throw new Error('missing correlate tool')
161
- if (!triggers.some((t) => t.name === 'netdata_critical_alert')) throw new Error('missing critical trigger')
162
- if (!triggers.some((t) => t.name === 'netdata_warning_alert')) throw new Error('missing warning trigger')
163
- if (!panels.some((p) => p.name === 'netdata-alert-feed')) throw new Error('missing alert feed panel')
164
- if (!logs.some((l) => l.includes('registered'))) throw new Error('should log registration')
165
- })
166
-
167
- test('register: critical trigger matches critical events only', () => {
168
- const triggers: any[] = []
169
- register({
170
- registerTool: () => {}, registerTrigger: (t) => triggers.push(t), registerPanel: () => {},
171
- exec: async () => '', readLedger: () => ({}), log: () => {},
172
- } as any)
173
- const critTrigger = triggers.find((t) => t.name === 'netdata_critical_alert')
174
- if (!critTrigger) throw new Error('missing critical trigger')
175
- if (!critTrigger.match({ source: 'netdata', severity: 'critical' })) throw new Error('should match critical')
176
- if (critTrigger.match({ source: 'netdata', severity: 'warning' })) throw new Error('should NOT match warning')
177
- if (critTrigger.match({ source: 'other', severity: 'critical' })) throw new Error('should NOT match non-netdata')
178
- if (critTrigger.match({})) throw new Error('should NOT match empty')
179
- })
180
-
181
- test('register: warning trigger matches warning events only', () => {
182
- const triggers: any[] = []
183
- register({
184
- registerTool: () => {}, registerTrigger: (t) => triggers.push(t), registerPanel: () => {},
185
- exec: async () => '', readLedger: () => ({}), log: () => {},
186
- } as any)
187
- const warnTrigger = triggers.find((t) => t.name === 'netdata_warning_alert')
188
- if (!warnTrigger) throw new Error('missing warning trigger')
189
- if (!warnTrigger.match({ source: 'netdata', severity: 'warning' })) throw new Error('should match warning')
190
- if (warnTrigger.match({ source: 'netdata', severity: 'critical' })) throw new Error('should NOT match critical')
191
- })
192
-
193
- test('register: panel renders alert rows', () => {
194
- const panels: any[] = []
195
- register({
196
- registerTool: () => {}, registerTrigger: () => {}, registerPanel: (p) => panels.push(p),
197
- exec: async () => '', readLedger: () => ({}), log: () => {},
198
- } as any)
199
- const panel = panels[0]
200
- const html = panel.render([
201
- { host: 'web-01', alert: 'cpu_high', severity: 'critical', date: '2026-07-22' },
202
- { host: 'web-02', alert: 'disk_full', severity: 'warning', date: '2026-07-22' },
203
- ])
204
- if (!html.includes('cpu_high') || !html.includes('disk_full')) throw new Error('should contain alert names')
205
- if (!html.includes('<table>')) throw new Error('should render table')
206
- })
207
-
208
- test('register: panel renders empty feed', () => {
209
- const panels: any[] = []
210
- register({
211
- registerTool: () => {}, registerTrigger: () => {}, registerPanel: (p) => panels.push(p),
212
- exec: async () => '', readLedger: () => ({}), log: () => {},
213
- } as any)
214
- const html = panels[0].render(null)
215
- if (!html.includes('Netdata Alerts')) throw new Error('should have title even when empty')
216
- })
217
-
218
- test('register: netdata_correlate tool handles invalid payload', async () => {
219
- const tools: any[] = []
220
- register({
221
- registerTool: (t) => tools.push(t), registerTrigger: () => {}, registerPanel: () => {},
222
- exec: async () => '', readLedger: () => ({}), log: () => {},
223
- } as any)
224
- const correlateTool = tools.find((t) => t.name === 'netdata_correlate')
225
- const result = await correlateTool.handler({ alert: { foo: 'bar' } })
226
- if (!result.error) throw new Error('should return error for invalid payload')
227
- })
228
-
229
- test('register: netdata_correlate tool correlates valid payload', async () => {
230
- const tools: any[] = []
231
- register({
232
- registerTool: (t) => tools.push(t), registerTrigger: () => {}, registerPanel: () => {},
233
- exec: async () => '', readLedger: () => null, log: () => {},
234
- } as any)
235
- const correlateTool = tools.find((t) => t.name === 'netdata_correlate')
236
- const result = await correlateTool.handler({
237
- alert: { alert: 'cpu_usage', severity: 'critical', space: 'web-01', message: 'CPU 95%' },
238
- })
239
- if (!result.parsed) throw new Error('should return parsed alert')
240
- if (result.parsed.alert !== 'cpu_usage') throw new Error('alert name')
241
- })
242
-
243
- async function main() {
244
- let pass = 0, fail = 0
245
- for (const c of cases) {
246
- try { await c.run(); pass++; console.log(`PASS ${c.name}`) }
247
- catch (e: any) { fail++; console.log(`FAIL ${c.name}: ${e?.message ?? e}`) }
248
- }
249
- console.log(`\n${pass}/${cases.length} passed, ${fail} failed`)
250
- if (fail > 0) process.exit(1)
251
- }
252
- void main()