@jacebenson/jsn 5.2.0 → 5.3.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/README.md CHANGED
@@ -163,19 +163,82 @@ mapping variable names to values, then preview with
163
163
  Omit `--dry-run` to submit after confirmation. `--quantity` defaults to one;
164
164
  `--requested-for` accepts a user sys_id subject to instance delegation rules.
165
165
 
166
+ `show` is the one view of an item — `describe` and `inputs` are aliases for it.
167
+ It reads the item twice and answers once: the Table API gives the definition
168
+ (`sc_cat_item` plus `item_option_new`), and
169
+ `/api/sn_sc/servicecatalog/items/{id}` gives what this account can actually
170
+ request. The catalog API wins when it answers; the definition list keeps the
171
+ command working when it does not, with `variables_source` naming which one
172
+ answered and `variables_api_error` carrying the reason for the fallback.
173
+
174
+ Questions come back as `{name, label, type, friendly_type, mandatory,
175
+ instance_supplied}` with `required_variables` and `instance_supplied_variables`,
176
+ so a script can build the payload without guessing names or types. Layout
177
+ entries that draw the form but hold no value — containers, labels, HTML and rich
178
+ text blocks, breaks and UI macros — are not reported as questions; only their
179
+ container children are walked. `required_variables` excludes the
180
+ instance-supplied ones: "Requested for" (type 31) is mandatory in the API
181
+ payload, but the instance fills it from the session and `--requested-for`
182
+ overrides it. `order` refuses locally when a required question is missing and an
183
+ unknown variable name is reported as `unknown_variable_names` without blocking.
184
+ The server remains the authority.
185
+
186
+ What the API returns is what a caller can send: questions withheld by a catalog UI
187
+ policy are absent, and a policy-applied mandatory flag is not visible here, so the
188
+ server still decides at submission. Record producers and order guides expose their
189
+ variables but are not orderable through `order`.
190
+
166
191
  Orders use `order_now`, preserving catalog fulfillment rather than inserting an
167
- RITM directly. The command handles standard catalog items; record producers and
168
- order guides require separate workflows. Server rules validate mandatory and
169
- dynamic variables at submission; a preview does not validate those rules. Preview
170
- output lists variable names, not entered values. This operation requires a
171
- write-enabled profile (also for previews), but no development update set.
172
- Confirmation follows the existing profile policy; automation can supply `--force`
173
- only for an approved order. Timeout or incomplete response is an uncertain
174
- outcome: inspect requests before retrying. JSN does not automatically submit a
175
- second order. `create/list/show` retain their definition-management behavior.
192
+ RITM directly. `order_now` returns the request (REQ); JSN then reads the request's
193
+ items and reports `request_id`, `request_number` and `requested_items`
194
+ (`sys_id`/`number`). If that follow-up read is denied, the order is still
195
+ reported as placed with `requested_items_readable: false` — inspect requests
196
+ rather than resubmitting. The command handles standard catalog items; record
197
+ producers and order guides require separate workflows. Server rules validate
198
+ dynamic variables at submission; a preview does not validate those rules.
199
+ Preview output lists variable names and required names, not entered values.
200
+ Previews only read, so they work on a read-only profile; submitting requires a
201
+ write-enabled profile and no development update set. Confirmation follows the
202
+ existing profile policy; automation can supply `--force` only for an approved
203
+ order. Timeout or incomplete response is an uncertain outcome: inspect requests
204
+ before retrying. JSN does not automatically submit a second order.
205
+ `create/list/show` retain their definition-management behavior.
176
206
 
177
207
  See the [Service Catalog API reference](https://www.servicenow.com/docs/r/api-reference/rest-apis/c_ServiceCatalogAPI.html).
178
208
 
209
+ ### Viewing service and HR cases
210
+
211
+ `jsn cases list`, `jsn cases show <number>` and `jsn cases search "<text>"` read
212
+ cases through the normal authenticated Table API. Which case table is meant
213
+ depends on the installed application, so JSN probes the known case tables in
214
+ order — `sn_customerservice_case` (Customer Service Management), then
215
+ `sn_hr_core_case` (HR Service Delivery) — and uses the first one the profile can
216
+ read. `jsn cases tables` reports each candidate without claiming access, and
217
+ `--table <name>` names any other case table.
218
+
219
+ ```bash
220
+ jsn cases list --json
221
+ jsn cases list --hr --query "active=true"
222
+ jsn cases search "printer" --table sn_customerservice_case
223
+ jsn cases show CS0001001
224
+ ```
225
+
226
+ Visibility is not widened by JSN: application roles and ACLs decide which
227
+ records are returned, and a denied table reports `forbidden` (HTTP 403) rather
228
+ than an empty list. An instance without a case application reports which tables
229
+ were unavailable instead of pretending there are no cases, and naming such a
230
+ table with `--table` fails the same way (`Reading <table> failed (HTTP 400)`,
231
+ exit 2) instead of printing an empty list. To scope a list to the connected
232
+ account, add a query term — field names differ per application, for example
233
+ `--query "opened_by=javascript:gs.getUserID()"`. These commands only read; case
234
+ work that changes state stays in the application UI or `jsn records update`.
235
+
236
+ HR cases are a thin addition over this generic path: `--hr` selects
237
+ `sn_hr_core_case`. Employee self-service visibility depends on the HR roles and
238
+ ACLs of the connected account — an administrator profile does not represent an
239
+ employee's view. HR case tasks, relations and the employee portal's widgets are
240
+ not exposed yet.
241
+
179
242
  ## Domain configuration and browser sessions
180
243
 
181
244
  `jsn domains current` reports the selected profile's configured `X-Now-Domain`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.2.0",
3
+ "version": "5.3.0",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -4,7 +4,7 @@ description: Use the jsn CLI for ServiceNow development, administration, and dat
4
4
  license: MIT
5
5
  metadata:
6
6
  author: jacebenson
7
- version: "4.3.13"
7
+ version: "4.3.14"
8
8
  repository: https://github.com/jacebenson/jsn
9
9
  ---
10
10
 
@@ -28,6 +28,16 @@ For development:
28
28
  5. Ask whether anything else belongs in the update set. If the user confirms
29
29
  it is finished, complete it with notes.
30
30
 
31
+ Tracking a record: when the user asks to track, watch or be told about changes
32
+ to an incident, task, change request or other record, use
33
+ `jsn records watch --table <table> --sys-id <id> --timeout <seconds> --json`.
34
+ It streams newline-delimited JSON (`record_change`, `gap`, `watch_summary`),
35
+ so run it for a bounded window and report what arrived; schedules and user
36
+ notifications belong to your runtime, not to the command. Use `--max-events 1`
37
+ for a single-change check. A `gap` or `"complete": false` means events were
38
+ missed — read the record's current state rather than assuming continuity.
39
+ Watching needs a browser session (`jsn auth login --browser`).
40
+
31
41
  For incoming update sets: import the XML, preview the set, and resolve preview
32
42
  errors with the human where needed. Once the preview is clear, commit the set
33
43
  and verify the results.
package/src/amb.js ADDED
@@ -0,0 +1,370 @@
1
+ // ServiceNow AMB (Asynchronous Message Bus) client.
2
+ //
3
+ // AMB is ServiceNow's real-time channel service. It is a Bayeux / CometD
4
+ // long-polling endpoint at `/amb`: you POST JSON message arrays to
5
+ // `/amb/handshake` (once) and `/amb/connect` (everything else), and the
6
+ // server holds the connect request until it has an event or its hold timer
7
+ // expires. It is NOT socket.io — the wire format is Bayeux, so no socket.io
8
+ // or WebSocket runtime dependency is needed here.
9
+ //
10
+ // Authorization is the part that surprises people: AMB authorizes like a
11
+ // browser session, not like a REST request. A bearer token or Basic header
12
+ // is not enough; the server wants the session cookies (glide_session_store,
13
+ // JSESSIONID, BAYEUX_BROWSER) plus X-UserToken that a logged-in UI session
14
+ // carries. `SDKClient.ambSession()` supplies that material from the active
15
+ // JSN credential; when it cannot, this module raises an actionable error
16
+ // instead of guessing.
17
+ //
18
+ // This module owns protocol framing, cookie/token handling and event
19
+ // normalization. Reconnect policy, gap reporting and duration bounds live in
20
+ // src/record-watch.js.
21
+
22
+ import { AppError, CodeAPI, CodeAuth, CodeNetwork, CodeUsage } from './errors.js';
23
+
24
+ const BAYEUX_VERSION = '1.0';
25
+ const DEFAULT_CONNECT_TIMEOUT = 60000;
26
+ const DEFAULT_REQUEST_TIMEOUT = 30000;
27
+
28
+ // AMB's subscribe step is tied to a browser session. These are the cookies
29
+ // that carry it, plus node affinity (BAYEUX_BROWSER) which subscribe needs
30
+ // when the instance sits behind a load balancer.
31
+ const SESSION_COOKIE = /^(glide_|JSESSIONID|BIGipServer|XSRF-TOKEN|BAYEUX_BROWSER)/i;
32
+
33
+ export class AmbError extends AppError {
34
+ constructor(code, message, hint = '', status = 0, cause = null) {
35
+ super(code, message, hint, status, cause);
36
+ // Auth/usage rejections cannot be fixed by reconnecting; transport and
37
+ // 5xx failures can. The watch loop reads this to decide.
38
+ this.fatal = code === CodeAuth || code === CodeUsage
39
+ || (code === CodeAPI && status > 0 && status < 500);
40
+ }
41
+ }
42
+
43
+ function ambAuthError(message, hint) {
44
+ return new AmbError(CodeAuth, message, hint);
45
+ }
46
+
47
+ /**
48
+ * The channel name for a record-watcher subscription.
49
+ *
50
+ * Encoding is ServiceNow's: standard base64 of the encoded query with `=`
51
+ * replaced by `-` (a channel segment cannot contain `=`). The action prefix
52
+ * defaults to `default`.
53
+ */
54
+ export function recordWatcherChannel(table, query, actionPrefix = 'default') {
55
+ if (typeof table !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(table)) {
56
+ throw new AmbError(CodeUsage, `Invalid table name for record watch: ${table}`);
57
+ }
58
+ if (typeof query !== 'string' || !query.trim()) {
59
+ throw new AmbError(CodeUsage, 'A record watcher needs a non-empty encoded query.');
60
+ }
61
+ const encoded = Buffer.from(query, 'utf8').toString('base64').replace(/=/g, '-');
62
+ return `/rw/${actionPrefix || 'default'}/${table}/${encoded}`;
63
+ }
64
+
65
+ const OPERATION_NAMES = {
66
+ insert: 'created', entry: 'created', add: 'created', created: 'created',
67
+ update: 'updated', change: 'updated', modify: 'updated', updated: 'updated',
68
+ delete: 'deleted', removed: 'deleted', deleted: 'deleted',
69
+ };
70
+
71
+ /** Normalize one raw change entry; the platform has used several shapes. */
72
+ function normalizeChange(change) {
73
+ if (Array.isArray(change)) {
74
+ const [field, previous, value] = change;
75
+ return { field: String(field ?? ''), previous_value: previous ?? null, value: value ?? null };
76
+ }
77
+ if (!change || typeof change !== 'object') return null;
78
+ const field = change.field ?? change.name ?? change.key;
79
+ if (!field) return null;
80
+ const value = change.value ?? change.new_value ?? change.newValue;
81
+ const previous = change.previous_value ?? change.old_value ?? change.oldValue;
82
+ const out = { field: String(field) };
83
+ if (value !== undefined) out.value = value;
84
+ if (change.display_value !== undefined) out.display_value = change.display_value;
85
+ if (previous !== undefined) out.previous_value = previous;
86
+ return out;
87
+ }
88
+
89
+ /**
90
+ * Turn a Bayeux event message on a record-watcher channel into the stable
91
+ * event shape JSN emits. Notification data is kept separate from any record
92
+ * state fetched later (see record-watch.js) — this object is only what the
93
+ * notification itself carried.
94
+ *
95
+ * @param {object} message — { channel, data, id }
96
+ * @param {{table?: string, sysID?: string}} expected — the watched record
97
+ * @param {string} [receivedAt] — ISO timestamp
98
+ */
99
+ export function normalizeRecordWatcherEvent(message, expected = {}, receivedAt = new Date().toISOString()) {
100
+ const channel = message?.channel || '';
101
+ let data = message?.data;
102
+ if (typeof data === 'string') {
103
+ try { data = JSON.parse(data); } catch { data = null; }
104
+ }
105
+ if (!data || typeof data !== 'object') data = {};
106
+ const record = data.record && typeof data.record === 'object' ? data.record : null;
107
+ const channelTable = channel.split('/')[3] || null;
108
+ const table = data.table || record?.table || expected.table || channelTable;
109
+ const sysID = data.sys_id || record?.sys_id || expected.sysID || null;
110
+ const rawOperation = String(data.operation || data.op || data.action || '').toLowerCase();
111
+ const operation = OPERATION_NAMES[rawOperation] || (rawOperation ? 'changed' : 'unknown');
112
+ const changes = Array.isArray(data.changes)
113
+ ? data.changes.map(normalizeChange).filter(Boolean)
114
+ : [];
115
+ const displayValue = data.display_value ?? data.displayValue
116
+ ?? record?.number ?? record?.display_value ?? null;
117
+
118
+ const event = {
119
+ type: 'record_change',
120
+ channel,
121
+ table,
122
+ sys_id: sysID,
123
+ operation,
124
+ received_at: receivedAt,
125
+ };
126
+ if (rawOperation) event.action = rawOperation;
127
+ if (displayValue != null) event.display_value = displayValue;
128
+ if (message?.id != null) event.event_id = message.id;
129
+ if (changes.length) event.changes = changes;
130
+ if (record) event.record = record;
131
+ return event;
132
+ }
133
+
134
+ /** Seed a cookie jar from a `a=1; b=2` header value. */
135
+ function seedCookies(jar, header) {
136
+ for (const part of String(header || '').split(';')) {
137
+ const pair = part.trim();
138
+ const eq = pair.indexOf('=');
139
+ if (eq <= 0) continue;
140
+ jar.set(pair.slice(0, eq), pair.slice(eq + 1));
141
+ }
142
+ }
143
+
144
+ function serializeCookies(jar) {
145
+ return [...jar].map(([name, value]) => `${name}=${value}`).join('; ');
146
+ }
147
+
148
+ /**
149
+ * Minimal Bayeux client for ServiceNow's /amb endpoint.
150
+ *
151
+ * `session()` returns `{ cookies, userToken }` and is called again on every
152
+ * reconnect so an expired session can be refreshed instead of replaying a
153
+ * dead cookie.
154
+ */
155
+ export class AmbClient {
156
+ constructor({
157
+ baseUrl,
158
+ session,
159
+ fetchImpl = globalThis.fetch,
160
+ path = '/amb',
161
+ connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT,
162
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT,
163
+ }) {
164
+ if (!baseUrl) throw new AmbError(CodeUsage, 'AMB needs an instance URL.');
165
+ if (typeof session !== 'function') throw new AmbError(CodeUsage, 'AMB needs a session provider.');
166
+ this.baseUrl = String(baseUrl).replace(/\/$/, '');
167
+ this.session = session;
168
+ this.fetchImpl = fetchImpl;
169
+ this.path = path.startsWith('/') ? path : `/${path}`;
170
+ this.connectTimeoutMs = connectTimeoutMs;
171
+ this.requestTimeoutMs = requestTimeoutMs;
172
+ this.clientId = null;
173
+ this.sessionStatus = null;
174
+ this.cookieJar = new Map();
175
+ this.userToken = '';
176
+ this.messageCounter = 0;
177
+ }
178
+
179
+ /** POST a Bayeux message array to /amb/handshake or /amb/connect. */
180
+ async _send(messages, { op, timeoutMs, signal }) {
181
+ const endpoint = op === 'handshake' ? 'handshake' : 'connect';
182
+ const url = `${this.baseUrl}${this.path}/${endpoint}`;
183
+ const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };
184
+ const cookies = serializeCookies(this.cookieJar);
185
+ if (cookies) headers.Cookie = cookies;
186
+ if (this.userToken) headers['X-UserToken'] = this.userToken;
187
+
188
+ const controller = new AbortController();
189
+ let timedOut = false;
190
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
191
+ const forwardAbort = () => controller.abort();
192
+ if (signal) {
193
+ if (signal.aborted) controller.abort();
194
+ else signal.addEventListener('abort', forwardAbort, { once: true });
195
+ }
196
+ try {
197
+ const response = await this.fetchImpl(url, {
198
+ method: 'POST',
199
+ headers,
200
+ body: JSON.stringify(messages),
201
+ signal: controller.signal,
202
+ });
203
+ this._captureSession(response);
204
+ if (!response.ok) {
205
+ const detail = await response.text().catch(() => '');
206
+ const status = response.status;
207
+ if (status === 401) {
208
+ throw new AmbError(CodeAuth, 'AMB rejected the active session (HTTP 401).',
209
+ 'Run "jsn auth login --browser" (or reauthenticate the profile), then retry the watch.', 401);
210
+ }
211
+ if (status === 403) {
212
+ throw new AmbError(CodeAPI,
213
+ 'AMB access forbidden (HTTP 403).',
214
+ 'Record watching requires an interactive user session; check the role/ACL that governs AMB channels on this instance.',
215
+ 403);
216
+ }
217
+ if (status === 404) {
218
+ throw new AmbError(CodeAPI,
219
+ 'AMB endpoint not found (HTTP 404).',
220
+ 'This instance does not expose /amb, or the instance URL is wrong. Record watching is supported on ServiceNow instances with the AMB service enabled.',
221
+ 404);
222
+ }
223
+ const summary = detail.replace(/\s+/g, ' ').trim().slice(0, 200);
224
+ throw new AmbError(CodeAPI, `AMB ${op} failed (HTTP ${status})${summary ? `: ${summary}` : '.'}`,
225
+ status >= 500 ? 'The instance may be unavailable or the AMB service restarting; retry shortly.' : 'Check the AMB service on this instance.',
226
+ status);
227
+ }
228
+ const json = await response.json();
229
+ if (!Array.isArray(json)) {
230
+ throw new AmbError(CodeAPI, `AMB ${op} returned an unexpected response.`, 'Expected a Bayeux message array; the instance may be proxying /amb to something else.');
231
+ }
232
+ return json;
233
+ } catch (error) {
234
+ if (error instanceof AppError) throw error;
235
+ const abortedByCaller = signal?.aborted === true;
236
+ if (timedOut && !abortedByCaller) {
237
+ const timeout = new AmbError(CodeNetwork, `AMB ${op} timed out after ${timeoutMs}ms.`,
238
+ 'The instance did not answer the AMB request. Check connectivity, then retry.');
239
+ timeout.timedOut = true;
240
+ throw timeout;
241
+ }
242
+ if (abortedByCaller) {
243
+ const aborted = new AmbError(CodeNetwork, 'AMB request cancelled.');
244
+ aborted.cancelled = true;
245
+ throw aborted;
246
+ }
247
+ const network = new AmbError(CodeNetwork, `Network error talking to AMB: ${error.message || error}`,
248
+ 'Check your internet connection and instance URL.');
249
+ network.cause = error;
250
+ throw network;
251
+ } finally {
252
+ clearTimeout(timer);
253
+ if (signal) signal.removeEventListener('abort', forwardAbort);
254
+ }
255
+ }
256
+
257
+ /** Keep session cookies and X-UserToken from any AMB response. */
258
+ _captureSession(response) {
259
+ const setCookies = response.headers?.getSetCookie?.() || [];
260
+ const raw = setCookies.length
261
+ ? setCookies
262
+ : [response.headers?.get?.('set-cookie')].filter(Boolean);
263
+ for (const value of raw) {
264
+ const pair = value.split(';', 1)[0].trim();
265
+ const eq = pair.indexOf('=');
266
+ if (eq <= 0) continue;
267
+ const name = pair.slice(0, eq);
268
+ if (SESSION_COOKIE.test(name)) this.cookieJar.set(name, pair.slice(eq + 1));
269
+ }
270
+ const token = response.headers?.get?.('x-usertoken');
271
+ if (token) this.userToken = token;
272
+ }
273
+
274
+ _message(channel, fields = {}) {
275
+ if (!this.clientId) throw new AmbError(CodeUsage, 'AMB client has no clientId; handshake first.');
276
+ return { channel, clientId: this.clientId, id: String(++this.messageCounter), ...fields };
277
+ }
278
+
279
+ /**
280
+ * Refresh session material, handshake, and subscribe to every channel.
281
+ * Re-run this after a dropped connection: re-subscribing is what restores
282
+ * delivery, and the gap is reported by the caller.
283
+ */
284
+ async start(channels = []) {
285
+ const session = await this.session();
286
+ if (!session?.cookies) {
287
+ throw ambAuthError('AMB needs a browser session and the active profile has none.',
288
+ 'Log in with a UI session ("jsn auth login --browser") or use a profile that stores gck cookies. Bearer-token-only profiles cannot open AMB channels.');
289
+ }
290
+ this.cookieJar.clear();
291
+ seedCookies(this.cookieJar, session.cookies);
292
+ this.userToken = session.userToken || '';
293
+ this.clientId = null;
294
+
295
+ const [handshake] = await this._send([{
296
+ channel: '/meta/handshake',
297
+ version: BAYEUX_VERSION,
298
+ supportedConnectionTypes: ['long-polling'],
299
+ id: String(++this.messageCounter),
300
+ }], { op: 'handshake', timeoutMs: this.requestTimeoutMs });
301
+ if (!handshake?.successful || !handshake?.clientId) {
302
+ throw new AmbError(CodeAuth,
303
+ `AMB handshake was rejected${handshake?.error ? `: ${handshake.error}` : '.'}`,
304
+ 'The active session is not accepted by AMB. Reauthenticate with "jsn auth login --browser"; basic/OAuth-only logins often cannot open a UI session.');
305
+ }
306
+ this.clientId = handshake.clientId;
307
+ this.sessionStatus = handshake.ext?.['glide.session.status'] ?? null;
308
+
309
+ for (const channel of channels) {
310
+ const [reply] = await this._send([this._message('/meta/subscribe', { subscription: channel })],
311
+ { op: 'subscribe', timeoutMs: this.requestTimeoutMs });
312
+ if (!reply?.successful) {
313
+ throw new AmbError(CodeAPI,
314
+ `AMB subscribe failed for ${channel}${reply?.error ? `: ${reply.error}` : '.'}`,
315
+ 'The record watcher channel was refused. Check that the record is accessible to this user and that AMB record watchers are enabled on the instance.');
316
+ }
317
+ }
318
+ return { clientId: this.clientId, sessionStatus: this.sessionStatus, channels: [...channels] };
319
+ }
320
+
321
+ /**
322
+ * One long-poll: returns the non-meta Bayeux messages it received. A local
323
+ * timeout returns an empty array (the loop just polls again) unless the
324
+ * caller's signal aborted, which throws with `cancelled`.
325
+ */
326
+ async next({ timeoutMs = this.connectTimeoutMs, signal } = {}) {
327
+ let messages;
328
+ try {
329
+ messages = await this._send([this._message('/meta/connect', { connectionType: 'long-polling' })],
330
+ { op: 'connect', timeoutMs, signal });
331
+ } catch (error) {
332
+ if (error.timedOut) return [];
333
+ throw error;
334
+ }
335
+ const events = [];
336
+ for (const message of messages) {
337
+ if (!message || typeof message !== 'object') continue;
338
+ if (message.channel?.startsWith('/meta/')) {
339
+ // Server advised a fresh handshake (session moved nodes, restarted).
340
+ if (message.advice?.reconnect === 'handshake' || (message.error && !message.successful)) {
341
+ this.clientId = null;
342
+ throw new AmbError(CodeNetwork, `AMB connection lost${message.error ? `: ${message.error}` : '.'}`,
343
+ 'Reconnecting re-subscribes the record watcher; events sent while disconnected are not replayed.');
344
+ }
345
+ continue;
346
+ }
347
+ events.push(message);
348
+ }
349
+ return events;
350
+ }
351
+
352
+ /** Best-effort unsubscribe + disconnect. Never throws. */
353
+ async stop(channels = []) {
354
+ if (!this.clientId) return;
355
+ for (const channel of channels) {
356
+ try {
357
+ await this._send([this._message('/meta/unsubscribe', { subscription: channel })],
358
+ { op: 'unsubscribe', timeoutMs: 5000 });
359
+ } catch { /* best effort; the connect loop is already stopping */ }
360
+ }
361
+ try {
362
+ await this._send([this._message('/meta/disconnect', {})], { op: 'disconnect', timeoutMs: 5000 });
363
+ } catch { /* best effort */ }
364
+ this.clientId = null;
365
+ }
366
+ }
367
+
368
+ export function createAmbClient(options) {
369
+ return new AmbClient(options);
370
+ }
package/src/app.js CHANGED
@@ -139,6 +139,10 @@ export class App {
139
139
 
140
140
  const scopeFormatted = `[${scope}]`;
141
141
 
142
+ // Terminal hyperlinks are invisible in a TTY and garbage in a pipe, so the
143
+ // banner only wraps values when stderr is actually a terminal.
144
+ const link = (text, url) => (process.stderr.isTTY === true ? hyperlink(text, url) : text);
145
+
142
146
  // Read-only profiles get a lock badge on every command run, so the
143
147
  // armed safety is always visible (not just in `auth status`).
144
148
  const roBadge = this.session?.readOnly === true ? ' 🔒' : '';
@@ -146,10 +150,10 @@ export class App {
146
150
  process.stderr.write('# Use `jsn scopes` to change scope, `jsn updatesets set` to change updateset\n');
147
151
  process.stderr.write('PROFILE USER [SCOPE] UPDATE SET\n');
148
152
 
149
- const profileStr = `${hyperlink(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
150
- const userStr = hyperlink(String(displayUserName).padEnd(9), userLink);
151
- const scopeStr = hyperlink(String(scopeFormatted).padEnd(17), scopeLink);
152
- const updateSetStr = hyperlink(String(updateSet), updateSetLink);
153
+ const profileStr = `${link(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
154
+ const userStr = link(String(displayUserName).padEnd(9), userLink);
155
+ const scopeStr = link(String(scopeFormatted).padEnd(17), scopeLink);
156
+ const updateSetStr = link(String(updateSet), updateSetLink);
153
157
 
154
158
  process.stderr.write(`${profileStr} ${userStr} ${scopeStr} ${updateSetStr}\n\n`);
155
159
 
package/src/cli.js CHANGED
@@ -10,6 +10,7 @@ import { App } from './app.js';
10
10
  import { resolveSession, applySession } from './session.js';
11
11
  import { renderHelp, renderTips } from './help.js';
12
12
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
13
+ import { maybeShowWelcome } from './welcome.js';
13
14
  import { skippedUpdatesCmd } from './commands/skipped-updates.js';
14
15
  import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, contextHeaderSkipCommands } from './capabilities.js';
15
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
@@ -34,6 +35,7 @@ import { groupsCmd } from './commands/groups.js';
34
35
  import { groupMembersCmd } from './commands/groupmembers.js';
35
36
  import { groupRolesCmd } from './commands/grouproles.js';
36
37
  import { ticketsCmd } from './commands/tickets.js';
38
+ import { casesCmd } from './commands/cases.js';
37
39
  import { transactionsCmd } from './commands/transactions.js';
38
40
 
39
41
  import { platformCmd } from './commands/platform.js';
@@ -75,6 +77,7 @@ import { scrapiCmd } from './commands/scrapi.js';
75
77
  import { b4rulesCmd } from './commands/b4rules.js';
76
78
  import { atfCmd } from './commands/atf.js';
77
79
  import { scanCmd } from './commands/scan.js';
80
+ import { storeCmd } from './commands/store.js';
78
81
  import { approvalsCmd } from './commands/approvals.js';
79
82
  import { historyCmd } from './commands/history.js';
80
83
  import { perfCmd } from './commands/perf.js';
@@ -353,6 +356,7 @@ export function buildCLI() {
353
356
  .command(requestsCmd(wrap))
354
357
  .command(tasksCmd(wrap))
355
358
  .command(catalogCmd(wrap))
359
+ .command(casesCmd(wrap))
356
360
  // AUTOMATION — Async
357
361
  .command(flowsCmd(wrap))
358
362
  .command(actionsCmd(wrap))
@@ -426,6 +430,7 @@ export function buildCLI() {
426
430
  // DEVELOPER
427
431
  .command(atfCmd(wrap))
428
432
  .command(scanCmd(wrap))
433
+ .command(storeCmd(wrap))
429
434
  .command(approvalsCmd(wrap))
430
435
  .command(skippedUpdatesCmd(wrap))
431
436
  .command(perfCmd(wrap))
@@ -581,7 +586,12 @@ export function buildCLI() {
581
586
  }
582
587
  process.exit(0);
583
588
  }
584
- process.stdout.write(renderHelp(loadConfig(formatArgv), visibleCommandRegistry(cliInstance.commandRegistry(), loadConfig(formatArgv), formatArgv)) + '\n');
589
+ // First-run orientation (issue #387) sits above the unchanged help.
590
+ // maybeShowWelcome decides for itself: human terminal, no machine
591
+ // format, no configured profile, and not shown before.
592
+ const config = loadConfig(formatArgv);
593
+ maybeShowWelcome({ argv: formatArgv, requestedFormat, cfg: config });
594
+ process.stdout.write(renderHelp(config, visibleCommandRegistry(cliInstance.commandRegistry(), config, formatArgv)) + '\n');
585
595
  process.exit(0);
586
596
  }
587
597
  // Every other failure here (unknown command, missing required argument,
@@ -6,7 +6,7 @@ const BASIC_COMMANDS = new Set([
6
6
  'groups', 'groupmembers', 'grouproles', 'users', 'setup', 'auth', 'skill',
7
7
  'cmdb',
8
8
  'version', 'upgrade', 'docs', 'history', 'discover', 'completion',
9
- 'catalogitems',
9
+ 'catalogitems', 'cases',
10
10
  ]);
11
11
 
12
12
  export async function detectCommandAudience(sdk, username, instanceURL = sdk?.baseURL) {