@jacebenson/jsn 5.2.0-dev.130.1 → 5.2.0-dev.131.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.2.0-dev.130.1",
3
+ "version": "5.2.0-dev.131.1",
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
+ }
@@ -1,7 +1,9 @@
1
1
  import { formatCommandList, formatRecordForDisplay, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
2
2
  import { listRecords, recordListParams, getRecord, createRecord, updateRecord, deleteRecord } from '../records-engine.js';
3
- import { unwrapSysId } from '../resolve-record.js';
3
+ import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { errUsage } from '../errors.js';
5
+ import { AmbClient } from '../amb.js';
6
+ import { watchRecord } from '../record-watch.js';
5
7
  import { declareCapabilities } from '../capabilities.js';
6
8
 
7
9
  declareCapabilities('records', {
@@ -197,6 +199,113 @@ export function recordsCmd(wrap) {
197
199
  });
198
200
  }),
199
201
  })
202
+ .command({
203
+ command: 'watch',
204
+ describe: 'Stream change events for one record through ServiceNow AMB record watchers',
205
+ builder: (y) => y
206
+ .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
207
+ .option('sys-id', { type: 'string', describe: 'Record sys_id' })
208
+ .option('identifier', { type: 'string', describe: 'Identifier value; use --identifier-field number/name/etc for human identifiers' })
209
+ .option('identifier-field', { type: 'string', describe: 'Exact identifier field (default sys_id); disambiguates names and legacy sys_ids' })
210
+ .option('timeout', { type: 'number', default: 0, describe: 'Stop after this many seconds (0 = until interrupted)' })
211
+ .option('max-events', { type: 'number', default: 0, describe: 'Stop after this many change events (0 = unlimited)' })
212
+ .option('state', { type: 'string', choices: ['auto', 'always', 'never'], default: 'auto', describe: 'Fetch current record state after an event: auto (only when the notification lacks detail), always, never' })
213
+ .option('fields', { type: 'string', describe: 'Comma-separated fields for the fetched state (default all readable fields)' })
214
+ .option('reconnect', { type: 'boolean', default: true, describe: 'Reconnect after a dropped connection and report the gap; use --no-reconnect to fail fast' })
215
+ .option('poll-timeout', { type: 'number', default: 60000, describe: 'Long-poll hold timeout in milliseconds (advanced)' })
216
+ .epilogue([
217
+ 'Emits newline-delimited JSON events (type record_change, gap, subscribed, reconnected, watch_summary) with --json or when piped.',
218
+ 'The notification is emitted as the event; a fetched record is attached separately as event.state (source: "fetched").',
219
+ 'Record watchers are best effort: after a reconnect the stream reports a gap and does not replay missed events.',
220
+ 'Requires an interactive ServiceNow session (jsn auth login --browser). Not a durable queue or scheduler.',
221
+ 'Example: jsn records watch --table incident --sys-id <sys_id> --timeout 300 --json',
222
+ 'Example: jsn records watch --table incident --identifier INC0010001 --identifier-field number --max-events 1 --json',
223
+ ].join('\n')),
224
+ handler: wrap(async (argv, app) => {
225
+ const lookup = recordLookup(argv);
226
+ const record = await resolveRecord(app.sdk, { ...lookup, fields: ['sys_id'] });
227
+ const sysID = unwrapSysId(record);
228
+ if (!sysID) throw errUsage('The matched record has no readable sys_id; check field ACLs before retrying.');
229
+ const stateFields = argv.fields ? argv.fields.split(',').filter(Boolean) : null;
230
+
231
+ const controller = new AbortController();
232
+ const cancel = () => controller.abort();
233
+ process.once('SIGINT', cancel);
234
+ process.once('SIGTERM', cancel);
235
+
236
+ const emit = (data, line) => app.output.writeEvent(data, { line });
237
+ // A live record-watcher notification carries `record`: a map of the
238
+ // fields that changed plus sys_* audit fields. It does not carry the
239
+ // `changes` array. Render the changed fields so human output names
240
+ // what moved; the values are current, because the platform does not
241
+ // send the previous value.
242
+ const describeRecord = record => Object.entries(record && typeof record === 'object' ? record : {})
243
+ .filter(([field]) => !field.startsWith('sys_'))
244
+ .slice(0, 5)
245
+ .map(([field, entry]) => {
246
+ const value = entry && typeof entry === 'object' ? (entry.display_value ?? entry.value) : entry;
247
+ return `${field}: ${value === '' || value == null ? '(empty)' : value}`;
248
+ })
249
+ .join(', ');
250
+ const formatEventLine = event => {
251
+ if (event.type === 'record_change') {
252
+ const id = event.display_value || event.sys_id;
253
+ const changes = (event.changes || [])
254
+ .map(c => `${c.field}: ${c.previous_value ?? '?'} → ${c.display_value ?? c.value ?? '?'}`)
255
+ .join(', ');
256
+ const detail = changes || describeRecord(event.record);
257
+ return `${event.received_at} ${event.table} ${id} ${event.operation}${detail ? ` — ${detail}` : ''}`;
258
+ }
259
+ if (event.type === 'unsubscribed') return `unsubscribed${event.reason ? ` (${event.reason})` : ''}`;
260
+ if (event.type === 'gap') return `⚠ connection gap since ${event.since}: ${event.reason} (events in this window were not observed)`;
261
+ if (event.type === 'reconnected') return `⚠ reconnected after ${event.gaps} gap(s); missed events are not replayed`;
262
+ if (event.type === 'watch_summary') {
263
+ return `watch ended (${event.reason}) — ${event.events} event(s), ${event.gaps} gap(s), ${Math.round(event.duration_ms / 1000)}s`;
264
+ }
265
+ if (event.type === 'subscribed') return `watching ${event.channel}`;
266
+ return `${event.type}: ${event.channel || ''}`;
267
+ };
268
+ const onStatus = status => emit(status, formatEventLine(status));
269
+ const onEvent = async event => emit(event, formatEventLine(event));
270
+
271
+ const fetchState = async () => {
272
+ const params = new URLSearchParams({
273
+ sysparm_query: `sys_id=${sysID}`,
274
+ sysparm_limit: '1',
275
+ sysparm_display_value: 'all',
276
+ });
277
+ if (stateFields) params.set('sysparm_fields', [...new Set(['sys_id', ...stateFields])].join(','));
278
+ const rows = await app.sdk.list(argv.table, params);
279
+ return rows[0] ?? null;
280
+ };
281
+
282
+ const client = new AmbClient({
283
+ baseUrl: app.getEffectiveInstance(),
284
+ session: () => app.sdk.ambSession(),
285
+ connectTimeoutMs: argv['poll-timeout'] ?? argv.pollTimeout,
286
+ });
287
+
288
+ try {
289
+ const summary = await watchRecord({
290
+ client,
291
+ table: argv.table,
292
+ sysID,
293
+ timeoutMs: argv.timeout > 0 ? argv.timeout * 1000 : 0,
294
+ maxEvents: argv['max-events'] ?? argv.maxEvents,
295
+ signal: controller.signal,
296
+ statePolicy: argv.state,
297
+ fetchState,
298
+ reconnect: argv.reconnect !== false,
299
+ onStatus,
300
+ onEvent,
301
+ });
302
+ emit(summary, formatEventLine(summary));
303
+ } finally {
304
+ process.removeListener('SIGINT', cancel);
305
+ process.removeListener('SIGTERM', cancel);
306
+ }
307
+ }),
308
+ })
200
309
  .command({
201
310
  command: 'get',
202
311
  describe: 'Get one record by sys_id or an explicit identifier field',
package/src/errors.js CHANGED
@@ -54,6 +54,11 @@ export function errAuth(msg) {
54
54
  return new AppError(CodeAuth, msg, 'Run: jsn auth login');
55
55
  }
56
56
 
57
+ /** Authentication failure with domain-specific recovery guidance. */
58
+ export function errAuthHint(msg, hint) {
59
+ return new AppError(CodeAuth, msg, hint);
60
+ }
61
+
57
62
  export function errForbidden(msg) {
58
63
  return new AppError(CodeForbidden, msg, '', 403);
59
64
  }
package/src/output.js CHANGED
@@ -186,6 +186,33 @@ export class OutputWriter {
186
186
  }
187
187
  }
188
188
 
189
+ /**
190
+ * Write one item of an event stream (e.g. `records watch`).
191
+ *
192
+ * A stream cannot use the single-envelope `ok()`, so this method emits one
193
+ * compact JSON object per line — newline-delimited JSON, the shape agents
194
+ * and scripts can consume incrementally without buffering the whole run.
195
+ * Human formats print `opts.line` (domain-formatted by the command) and
196
+ * fall back to the JSON line when the command supplied none.
197
+ *
198
+ * `--get` stays meaningful: the path is resolved against each event, and
199
+ * a path that does not resolve emits `null` rather than aborting the
200
+ * stream mid-observation.
201
+ */
202
+ writeEvent(data, opts = {}) {
203
+ const format = this.effectiveFormat();
204
+ if (format === FormatStyled || format === FormatMarkdown) {
205
+ this.writer.write(`${opts.line ?? JSON.stringify(data)}\n`);
206
+ return;
207
+ }
208
+ if (this.jqFilter) {
209
+ const value = resolvePath(data, this.jqFilter);
210
+ this.writer.write(`${JSON.stringify(value === undefined ? null : value)}\n`);
211
+ return;
212
+ }
213
+ this.writer.write(`${JSON.stringify(data)}\n`);
214
+ }
215
+
189
216
  writeJSON(data, opts) {
190
217
  const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
191
218
  if (opts.notice) resp.notice = opts.notice;
@@ -0,0 +1,206 @@
1
+ // Record watching: bounded observation of one ServiceNow record over AMB.
2
+ //
3
+ // The AMB client (src/amb.js) owns the wire protocol. This module owns the
4
+ // observation session: what counts as an event, when to fetch the record to
5
+ // fill in detail the notification omitted, bounded duration, cancellation,
6
+ // reconnect backoff and — most importantly — honest gap reporting.
7
+ //
8
+ // A record-watcher subscription is best-effort delivery, not a durable
9
+ // stream. After a disconnect the platform does not replay what was missed,
10
+ // so this module reports a gap instead of pretending the event list is
11
+ // complete.
12
+
13
+ import { AppError, CodeUsage } from './errors.js';
14
+ import { normalizeRecordWatcherEvent, recordWatcherChannel } from './amb.js';
15
+
16
+ export const DEFAULT_RECONNECT_DELAYS = [1000, 2000, 4000, 8000, 16000, 30000];
17
+
18
+ function defaultSleep(ms, signal) {
19
+ return new Promise((resolve) => {
20
+ if (signal?.aborted) return resolve();
21
+ const timer = setTimeout(done, ms);
22
+ function done() {
23
+ clearTimeout(timer);
24
+ signal?.removeEventListener('abort', done);
25
+ resolve();
26
+ }
27
+ if (signal) signal.addEventListener('abort', done, { once: true });
28
+ });
29
+ }
30
+
31
+ /** Does the notification carry enough detail that a follow-up read is redundant? */
32
+ export function notificationHasDetail(event) {
33
+ return Boolean(event?.record) || (Array.isArray(event?.changes) && event.changes.length > 0);
34
+ }
35
+
36
+ /**
37
+ * Watch one record until a bound is reached, the caller cancels, or a fatal
38
+ * error occurs.
39
+ *
40
+ * @param {object} opts
41
+ * @param {{ start: Function, next: Function, stop: Function }} opts.client
42
+ * @param {string} opts.table
43
+ * @param {string} opts.sysID
44
+ * @param {string} [opts.query] — encoded query; defaults to `sys_id=<sysID>`
45
+ * @param {number} [opts.timeoutMs] — 0 means "until cancelled"
46
+ * @param {number} [opts.maxEvents] — 0 means unlimited
47
+ * @param {AbortSignal} [opts.signal]
48
+ * @param {'auto'|'always'|'never'} [opts.statePolicy]
49
+ * @param {() => Promise<object|null>} [opts.fetchState]
50
+ * @param {(event: object) => any} [opts.onEvent]
51
+ * @param {(status: object) => any} [opts.onStatus]
52
+ * @param {boolean} [opts.reconnect]
53
+ * @param {number[]} [opts.reconnectDelays]
54
+ * @param {() => number} [opts.now]
55
+ * @param {Function} [opts.sleep]
56
+ */
57
+ export async function watchRecord({
58
+ client,
59
+ table,
60
+ sysID,
61
+ query,
62
+ timeoutMs = 0,
63
+ maxEvents = 0,
64
+ signal,
65
+ statePolicy = 'auto',
66
+ fetchState,
67
+ onEvent = () => {},
68
+ onStatus = () => {},
69
+ reconnect = true,
70
+ reconnectDelays = DEFAULT_RECONNECT_DELAYS,
71
+ now = () => Date.now(),
72
+ sleep = defaultSleep,
73
+ }) {
74
+ if (!client) throw new AppError(CodeUsage, 'Record watch needs an AMB client.');
75
+ if (!table) throw new AppError(CodeUsage, 'Record watch needs a table.');
76
+ if (!sysID) throw new AppError(CodeUsage, 'Record watch needs a record sys_id.');
77
+ if (!['auto', 'always', 'never'].includes(statePolicy)) {
78
+ throw new AppError(CodeUsage, `Unknown state policy: ${statePolicy}`);
79
+ }
80
+ if (timeoutMs < 0 || maxEvents < 0) throw new AppError(CodeUsage, 'Watch bounds cannot be negative.');
81
+ if (statePolicy !== 'never' && typeof fetchState !== 'function') {
82
+ throw new AppError(CodeUsage, 'State fetching is enabled but no record reader was supplied.');
83
+ }
84
+
85
+ const channel = recordWatcherChannel(table, query || `sys_id=${sysID}`);
86
+ const startedAt = now();
87
+ const startedISO = new Date(startedAt).toISOString();
88
+ const deadline = timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
89
+
90
+ let events = 0;
91
+ let gaps = 0;
92
+ let attempts = 0;
93
+ let lastEventAt = null;
94
+ let connected = false;
95
+ let reason = 'timeout';
96
+
97
+ const finish = async (why) => {
98
+ reason = why;
99
+ try { await client.stop([channel]); } catch { /* unsubscription is best effort */ }
100
+ onStatus({ type: 'unsubscribed', reason: why });
101
+ const endedAt = now();
102
+ return {
103
+ type: 'watch_summary',
104
+ table,
105
+ sys_id: sysID,
106
+ channel,
107
+ reason: why,
108
+ events,
109
+ gaps,
110
+ reconnects: Math.max(0, gaps),
111
+ complete: gaps === 0 && reason !== 'error',
112
+ started_at: startedISO,
113
+ ended_at: new Date(endedAt).toISOString(),
114
+ duration_ms: Math.max(0, endedAt - startedAt),
115
+ last_event_at: lastEventAt,
116
+ };
117
+ };
118
+
119
+ onStatus({ type: 'connecting', table, sys_id: sysID, channel });
120
+
121
+ try {
122
+ while (true) {
123
+ const remaining = deadline - now();
124
+ if (remaining <= 0) return await finish('timeout');
125
+ if (signal?.aborted) return await finish('cancelled');
126
+
127
+ if (!connected) {
128
+ const session = await client.start([channel]);
129
+ connected = true;
130
+ attempts = 0;
131
+ const resumed = gaps > 0;
132
+ onStatus({
133
+ type: resumed ? 'reconnected' : 'subscribed',
134
+ channel,
135
+ ...(session?.sessionStatus ? { session_status: session.sessionStatus } : {}),
136
+ // State the limitation, do not imply the stream was continuous.
137
+ ...(resumed ? { may_have_missed_events: true, gaps } : {}),
138
+ });
139
+ }
140
+
141
+ let messages;
142
+ try {
143
+ messages = await client.next({ timeoutMs: Math.min(remaining, 60000), signal });
144
+ } catch (error) {
145
+ if (signal?.aborted) return await finish('cancelled');
146
+ if (deadline - now() <= 0) return await finish('timeout');
147
+ if (error?.fatal === true || !reconnect) throw error;
148
+
149
+ // A dropped connection is a real gap in observation, not a retry note.
150
+ gaps += 1;
151
+ const gapStart = lastEventAt || startedISO;
152
+ const gapAt = new Date(now()).toISOString();
153
+ onStatus({
154
+ type: 'gap',
155
+ at: gapAt,
156
+ since: gapStart,
157
+ reason: error?.message || String(error),
158
+ code: error?.code || null,
159
+ });
160
+ connected = false;
161
+ const wait = reconnectDelays[Math.min(attempts, reconnectDelays.length - 1)];
162
+ attempts += 1;
163
+ const waitedUntil = now() + wait;
164
+ while (now() < waitedUntil && !signal?.aborted && now() < deadline) {
165
+ await sleep(Math.min(wait, Math.max(1, waitedUntil - now())), signal);
166
+ }
167
+ continue;
168
+ }
169
+
170
+ for (const message of messages) {
171
+ if (signal?.aborted) return await finish('cancelled');
172
+ const event = normalizeRecordWatcherEvent(message, { table, sysID }, new Date(now()).toISOString());
173
+ // The channel query scopes delivery to this record. The live payload
174
+ // does not carry a sys_id (jsn fills it from the subscription), so this
175
+ // guard only bites on an instance that does send one — for example a
176
+ // table-level channel returning a different record.
177
+ if (event.sys_id && sysID && event.sys_id !== sysID) continue;
178
+
179
+ const shouldFetch = statePolicy === 'always'
180
+ || (statePolicy === 'auto' && !notificationHasDetail(event));
181
+ if (shouldFetch) {
182
+ try {
183
+ const record = await fetchState();
184
+ event.state = { source: 'fetched', fetched_at: new Date(now()).toISOString(), record };
185
+ } catch (error) {
186
+ // Never let a failed follow-up read masquerade as a failed or
187
+ // complete event; keep the notification and record the problem.
188
+ event.state = null;
189
+ event.state_error = {
190
+ code: error?.code || null,
191
+ message: error?.message || String(error),
192
+ };
193
+ }
194
+ }
195
+
196
+ events += 1;
197
+ lastEventAt = event.received_at;
198
+ await onEvent(event);
199
+ if (maxEvents > 0 && events >= maxEvents) return await finish('max_events');
200
+ }
201
+ }
202
+ } catch (error) {
203
+ await finish('error');
204
+ throw error;
205
+ }
206
+ }
package/src/sdk.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { batchRead } from './sdk-batch.js';
4
4
  import { gunzipSync } from 'node:zlib';
5
- import { AppError, CodeAPI, CodeAuth, errAuth, errAPI, errNetwork, errUsage } from './errors.js';
5
+ import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
6
6
  import { getStringField } from './helpers.js';
7
7
  import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
8
8
  import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
@@ -974,6 +974,40 @@ export class SDKClient {
974
974
  return variables;
975
975
  }
976
976
 
977
+ /**
978
+ * Session material for channels that authorize like a browser (AMB).
979
+ *
980
+ * AMB does not accept bearer/basic headers on subscribe; it needs the
981
+ * cookies and X-UserToken of a UI session. gck credentials already carry
982
+ * them; basic/oauth profiles obtain them by warming the same session the
983
+ * SDK uses for UI calls. A bearer-token profile that cannot warm a session
984
+ * is an actionable error, never a silent fallback.
985
+ */
986
+ async ambSession() {
987
+ if (!this.authProvider) throw errAuth('No authentication configured');
988
+ const creds = await this.authProvider.getCredentials();
989
+ if (!creds) throw errAuth('No valid credentials');
990
+ if (creds.auth_method === 'gck') {
991
+ if (!creds.cookies) {
992
+ throw errAuthHint('This gck credential has no session cookies, so AMB cannot open a channel.',
993
+ 'Re-import the browser session: jsn auth login --browser');
994
+ }
995
+ return { cookies: creds.cookies, userToken: creds.access_token || '', authMethod: 'gck' };
996
+ }
997
+ if (creds.auth_method === 'basic' || creds.auth_method === 'token' || creds.auth_method === 'oauth') {
998
+ const cookies = await this._warmSession();
999
+ if (!cookies) {
1000
+ throw errAuthHint(
1001
+ `${creds.auth_method} credentials could not open a UI session, which AMB requires.`,
1002
+ 'Record watching needs a browser session. Run "jsn auth login --browser" and use that profile, or ask an administrator whether AMB is enabled for this account.',
1003
+ );
1004
+ }
1005
+ return { cookies, userToken: this.sessionUserToken || '', authMethod: creds.auth_method };
1006
+ }
1007
+ throw errAuthHint(`Authentication method "${creds.auth_method}" cannot open an AMB session.`,
1008
+ 'Use a browser-session (gck) profile: jsn auth login --browser');
1009
+ }
1010
+
977
1011
  async _warmSession() {
978
1012
  if (this.oauthCookies) return this.oauthCookies;
979
1013
  if (!this._sessionPromise) {