mcp-for-i 0.1.13 → 0.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 +27 -0
- package/dist/config/store.js +229 -109
- package/dist/controlplane/auth.js +128 -0
- package/dist/controlplane/clientIntegrationService.js +83 -4
- package/dist/controlplane/commands.js +52 -11
- package/dist/controlplane/connectionService.js +110 -5
- package/dist/controlplane/connectionTest.js +329 -0
- package/dist/controlplane/errors.js +12 -0
- package/dist/controlplane/runtimeService.js +98 -26
- package/dist/controlplane/server.js +178 -11
- package/dist/controlplane/serverShared.js +25 -6
- package/dist/controlplane/serviceManager.js +147 -100
- package/dist/controlplane/ui.js +1783 -920
- package/dist/ibmi/CompileTools.js +29 -1
- package/dist/ibmi/IBMiContent.js +435 -63
- package/dist/ibmi/IbmDocs.js +685 -0
- package/dist/ibmi/LocalLanguageActions.js +129 -3
- package/dist/ibmi/Search.js +158 -52
- package/dist/ibmi/Tools.js +7 -10
- package/dist/ibmi/client.js +220 -31
- package/dist/ibmi/evfevent.js +256 -0
- package/dist/ibmi/knownHosts.js +190 -0
- package/dist/ibmi/libraryList.js +93 -0
- package/dist/ibmi/sourceInspect.js +815 -0
- package/dist/ibmi/sqlJob.js +888 -0
- package/dist/ibmi/sqlParse.js +317 -0
- package/dist/ibmi/tn5250/certTrust.js +59 -0
- package/dist/ibmi/tn5250/client.js +334 -0
- package/dist/ibmi/tn5250/datastream.js +109 -0
- package/dist/ibmi/tn5250/ebcdic.js +93 -0
- package/dist/ibmi/tn5250/ebcdicTables.js +27 -0
- package/dist/ibmi/tn5250/index.js +6 -0
- package/dist/ibmi/tn5250/screen.js +1033 -0
- package/dist/ibmi/tn5250/telnet.js +186 -0
- package/dist/ibmi/variables.js +18 -7
- package/dist/index.js +79 -24
- package/dist/mcp/annotations.js +155 -0
- package/dist/mcp/audit.js +490 -133
- package/dist/mcp/confirm.js +48 -0
- package/dist/mcp/context.js +43 -5
- package/dist/mcp/deployMethods.js +192 -0
- package/dist/mcp/logger.js +5 -10
- package/dist/mcp/modules/bulkMembers.js +476 -0
- package/dist/mcp/modules/changedLines.js +189 -0
- package/dist/mcp/modules/compare.js +198 -0
- package/dist/mcp/modules/compile.js +515 -0
- package/dist/mcp/modules/ifsOps.js +123 -0
- package/dist/mcp/modules/index.js +38 -0
- package/dist/mcp/modules/inspect.js +811 -0
- package/dist/mcp/modules/libl.js +246 -0
- package/dist/mcp/modules/members.js +171 -0
- package/dist/mcp/modules/objects.js +339 -0
- package/dist/mcp/modules/system.js +266 -0
- package/dist/mcp/modules/tn5250.js +800 -0
- package/dist/mcp/modules/tn5250App.js +194 -0
- package/dist/mcp/modules/tn5250Font.js +8 -0
- package/dist/mcp/modules/tn5250Live.js +221 -0
- package/dist/mcp/modules/tn5250LivePage.js +480 -0
- package/dist/mcp/policy.js +412 -0
- package/dist/mcp/tools.js +1719 -698
- package/dist/security/credentialStore.js +62 -13
- package/dist/security/localPaths.js +138 -0
- package/dist/security/redact.js +79 -0
- package/dist/util/atomicWrite.js +101 -0
- package/dist/util/fileLock.js +206 -0
- package/docs/capabilities.md +264 -220
- package/docs/configuration.md +193 -60
- package/docs/examples.md +109 -73
- package/docs/overview.md +15 -15
- package/docs/security.md +101 -16
- package/docs/tools.md +367 -188
- package/package.json +5 -2
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { clampNumber, enforceWritable, enforceWritableForPerson, getConnectionName, json } from "../tools.js";
|
|
3
|
+
import { getPassword } from "../../security/credentialStore.js";
|
|
4
|
+
import { REDACTED } from "../../security/redact.js";
|
|
5
|
+
import { Tn5250Client, aidForKey, checkTlsCertificate, hostKeyFor } from "../../ibmi/tn5250/index.js";
|
|
6
|
+
import { SUPPORTED_CCSIDS } from "../../ibmi/tn5250/ebcdic.js";
|
|
7
|
+
import { AID_WITHOUT_DATA } from "../../ibmi/tn5250/datastream.js";
|
|
8
|
+
import { startLiveServer } from "./tn5250Live.js";
|
|
9
|
+
const sessions = new Map();
|
|
10
|
+
/** "changed" (connectionName) whenever a session's screen or state may have changed. */
|
|
11
|
+
export const liveEvents = new EventEmitter();
|
|
12
|
+
liveEvents.setMaxListeners(100);
|
|
13
|
+
/** The agent waits this long after the person typed or clicked in the live view. */
|
|
14
|
+
export const PERSON_HOLD_MS = 4000;
|
|
15
|
+
let liveServer;
|
|
16
|
+
let liveServerStarting;
|
|
17
|
+
/** Context of the MCP process, used for input that comes from the live view. */
|
|
18
|
+
let liveCtx;
|
|
19
|
+
/** Replaceable dependencies (tests swap these). */
|
|
20
|
+
export const tn5250Deps = {
|
|
21
|
+
getPassword: (connectionName) => getPassword(connectionName),
|
|
22
|
+
checkCertificate: (info) => checkTlsCertificate({ host: info.host, port: info.port, certificate: info.certificate, authorized: info.authorized })
|
|
23
|
+
};
|
|
24
|
+
/** Keys handled on the local screen (nothing is sent to the IBM i), by every name they go by. */
|
|
25
|
+
const LOCAL_KEY_ALIASES = {
|
|
26
|
+
TAB: "TAB", FIELDADVANCE: "TAB",
|
|
27
|
+
BACKTAB: "BACKTAB", SHIFTTAB: "BACKTAB", FIELDBACKSPACE: "BACKTAB",
|
|
28
|
+
HOME: "HOME",
|
|
29
|
+
END: "END", ENDOFFIELD: "END",
|
|
30
|
+
RESET: "RESET",
|
|
31
|
+
ERASEEOF: "ERASEEOF", ERASEEOFIELD: "ERASEEOF", ERASEENDOFFIELD: "ERASEEOF",
|
|
32
|
+
ERASEINPUT: "ERASEINPUT",
|
|
33
|
+
FIELDEXIT: "FIELDEXIT",
|
|
34
|
+
FIELDPLUS: "FIELDPLUS",
|
|
35
|
+
FIELDMINUS: "FIELDMINUS",
|
|
36
|
+
DUP: "DUP", DUPLICATE: "DUP",
|
|
37
|
+
INSERT: "INSERT", INS: "INSERT",
|
|
38
|
+
DELETE: "DELETE", DEL: "DELETE",
|
|
39
|
+
UP: "UP", ARROWUP: "UP", CURSORUP: "UP",
|
|
40
|
+
DOWN: "DOWN", ARROWDOWN: "DOWN", CURSORDOWN: "DOWN",
|
|
41
|
+
LEFT: "LEFT", ARROWLEFT: "LEFT", CURSORLEFT: "LEFT", BACKSPACE: "LEFT",
|
|
42
|
+
RIGHT: "RIGHT", ARROWRIGHT: "RIGHT", CURSORRIGHT: "RIGHT",
|
|
43
|
+
NEWLINE: "NEWLINE"
|
|
44
|
+
};
|
|
45
|
+
const LOCAL_KEYS = new Set(Object.values(LOCAL_KEY_ALIASES));
|
|
46
|
+
/** How long Attn / SysReq wait for any answer before the keyboard is unlocked again. */
|
|
47
|
+
const HOST_KEY_ANSWER_MS = 2000;
|
|
48
|
+
const CONNECTION_NAME = { type: "string", description: "Saved IBM i connection name (defaults to the active connection)." };
|
|
49
|
+
const TIMEOUT_MS = { type: "number", description: "How long to wait for the host, in milliseconds." };
|
|
50
|
+
const FIELD_ID = {
|
|
51
|
+
type: "string",
|
|
52
|
+
description: "Field id from readScreen (for example \"r6c53\"), its 1-based index, or \"command\" for a recognised command line (===>)."
|
|
53
|
+
};
|
|
54
|
+
const tools = [
|
|
55
|
+
{
|
|
56
|
+
name: "ibmi.tn5250.connect",
|
|
57
|
+
description: "Open a real TN5250 (5250 green-screen) session to the saved connection's host and return the first screen. " +
|
|
58
|
+
"Port and TLS come from the connection settings tn5250Port / tn5250Tls (default 23, or 992 with TLS). " +
|
|
59
|
+
"signOn=true signs on with the connection's stored user and password (never passed as arguments); it counts as sending keys, so read-only connections refuse it.",
|
|
60
|
+
inputSchema: {
|
|
61
|
+
type: "object",
|
|
62
|
+
properties: {
|
|
63
|
+
connectionName: CONNECTION_NAME,
|
|
64
|
+
port: { type: "number", description: "Override the telnet port (1-65535)." },
|
|
65
|
+
tls: { type: "boolean", description: "Override TLS (default: tn5250Tls setting, else true for port 992)." },
|
|
66
|
+
signOn: { type: "boolean", default: false, description: "Sign on with the stored credentials." },
|
|
67
|
+
deviceName: { type: "string", description: "Virtual device name to request (1-10 characters)." },
|
|
68
|
+
screenSize: { type: "string", enum: ["24x80", "27x132"], description: "27x132 announces an IBM-3477-FC display." },
|
|
69
|
+
ccsid: {
|
|
70
|
+
type: "number",
|
|
71
|
+
description: `Single-byte EBCDIC code page for screen text (default: the tn5250Ccsid setting, else 37). Supported: ${SUPPORTED_CCSIDS.join(", ")}.`
|
|
72
|
+
},
|
|
73
|
+
timeoutMs: TIMEOUT_MS,
|
|
74
|
+
approve: { type: "boolean", description: "Set true to approve guarded-policy operations (signOn)." }
|
|
75
|
+
},
|
|
76
|
+
additionalProperties: false
|
|
77
|
+
},
|
|
78
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "ibmi.tn5250.readScreen",
|
|
82
|
+
description: "Read the current 5250 screen: text rows, cursor, keyboard state and the input fields (id, position, length, label, protected/hidden flags, value). " +
|
|
83
|
+
"Hidden (non-display, password-style) field contents are never returned.",
|
|
84
|
+
inputSchema: { type: "object", properties: { connectionName: CONNECTION_NAME }, additionalProperties: false },
|
|
85
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
name: "ibmi.tn5250.setField",
|
|
89
|
+
description: "Fill an input field on the local screen (nothing is sent until sendKeys presses an AID key such as Enter). " +
|
|
90
|
+
"Identify the field by fieldId or by row/col. useStoredPassword=true fills a hidden field with the connection's stored password.",
|
|
91
|
+
inputSchema: {
|
|
92
|
+
type: "object",
|
|
93
|
+
properties: {
|
|
94
|
+
connectionName: CONNECTION_NAME,
|
|
95
|
+
fieldId: FIELD_ID,
|
|
96
|
+
row: { type: "number", description: "1-based row of any position in the field." },
|
|
97
|
+
col: { type: "number", description: "1-based column of any position in the field." },
|
|
98
|
+
value: { type: "string" },
|
|
99
|
+
useStoredPassword: { type: "boolean", description: "Fill a hidden field with the stored password instead of value." }
|
|
100
|
+
},
|
|
101
|
+
additionalProperties: false
|
|
102
|
+
},
|
|
103
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
name: "ibmi.tn5250.sendKeys",
|
|
107
|
+
description: "Type text at the cursor and/or press keys, then wait for the host to answer. keys is a space-separated list: local keys " +
|
|
108
|
+
"(Tab, BackTab, Home, End, Reset, EraseEOF, EraseInput, FieldExit, Field+, Field-, Dup, Insert, Delete, Up, Down, Left, Right, NewLine; " +
|
|
109
|
+
"add *N to repeat, for example Down*3) and at most one host key at the end (Enter, F1-F24, PageUp, PageDown, Clear, Help, Print, Attn, SysReq). " +
|
|
110
|
+
"As in IBM emulators, Esc is Attn (Attention, which opens the job's attention menu or program) and Shift+Esc is SysReq (System Request). " +
|
|
111
|
+
"Pressing an AID key sends the screen to the IBM i: read-only connections refuse it, and text on a recognised command line (===>) is checked against the command policy as cl.run.",
|
|
112
|
+
inputSchema: {
|
|
113
|
+
type: "object",
|
|
114
|
+
properties: {
|
|
115
|
+
connectionName: CONNECTION_NAME,
|
|
116
|
+
text: { type: "string", description: "Text typed at the cursor before the keys." },
|
|
117
|
+
keys: { type: "string", description: "Keys to press, for example \"Enter\", \"F3\" or \"Tab Tab Enter\"." },
|
|
118
|
+
cursorRow: { type: "number", description: "Move the cursor here (1-based) before typing." },
|
|
119
|
+
cursorCol: { type: "number", description: "Move the cursor here (1-based) before typing." },
|
|
120
|
+
timeoutMs: TIMEOUT_MS,
|
|
121
|
+
approve: { type: "boolean", description: "Set true to approve guarded-policy operations." }
|
|
122
|
+
},
|
|
123
|
+
additionalProperties: false
|
|
124
|
+
},
|
|
125
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
name: "ibmi.tn5250.click",
|
|
129
|
+
description: "Click on the 5250 screen the way an emulator mouse does: a click moves the cursor to row/col; a click on a function-key legend " +
|
|
130
|
+
"(for example \"F3=Exit\") presses that key, and on \"More...\" presses PageDown; doubleClick moves the cursor and presses Enter. " +
|
|
131
|
+
"Pressing a key goes through the same checks as sendKeys.",
|
|
132
|
+
inputSchema: {
|
|
133
|
+
type: "object",
|
|
134
|
+
properties: {
|
|
135
|
+
connectionName: CONNECTION_NAME,
|
|
136
|
+
row: { type: "number", description: "1-based row." },
|
|
137
|
+
col: { type: "number", description: "1-based column." },
|
|
138
|
+
doubleClick: { type: "boolean", default: false, description: "Move the cursor and press Enter." },
|
|
139
|
+
hotspots: { type: "boolean", default: true, description: "Press the key named by a function-key legend under the click." },
|
|
140
|
+
timeoutMs: TIMEOUT_MS,
|
|
141
|
+
approve: { type: "boolean", description: "Set true to approve guarded-policy operations." }
|
|
142
|
+
},
|
|
143
|
+
required: ["row", "col"],
|
|
144
|
+
additionalProperties: false
|
|
145
|
+
},
|
|
146
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
name: "ibmi.tn5250.waitFor",
|
|
150
|
+
description: "Wait until text appears on the screen and/or the keyboard unlocks (the host is waiting for input). With no text it waits for the keyboard.",
|
|
151
|
+
inputSchema: {
|
|
152
|
+
type: "object",
|
|
153
|
+
properties: {
|
|
154
|
+
connectionName: CONNECTION_NAME,
|
|
155
|
+
text: { type: "string", description: "Case-insensitive text to look for on any row." },
|
|
156
|
+
keyboardUnlocked: { type: "boolean", description: "Also require the keyboard to be unlocked (default true when text is empty)." },
|
|
157
|
+
timeoutMs: TIMEOUT_MS
|
|
158
|
+
},
|
|
159
|
+
additionalProperties: false
|
|
160
|
+
},
|
|
161
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
name: "ibmi.tn5250.snapshot",
|
|
165
|
+
description: "Capture the screen as plain text plus the structured screen (hidden fields are blanked).",
|
|
166
|
+
inputSchema: { type: "object", properties: { connectionName: CONNECTION_NAME }, additionalProperties: false },
|
|
167
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
name: "ibmi.tn5250.disconnect",
|
|
171
|
+
description: "Close the TN5250 session (the IBM i ends or disconnects the interactive job as configured for the device).",
|
|
172
|
+
inputSchema: { type: "object", properties: { connectionName: CONNECTION_NAME }, additionalProperties: false },
|
|
173
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
|
|
174
|
+
}
|
|
175
|
+
];
|
|
176
|
+
async function handle(ctx, name, args) {
|
|
177
|
+
liveCtx = ctx;
|
|
178
|
+
try {
|
|
179
|
+
return await handleTool(ctx, name, args);
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
const connectionName = args?.connectionName || ctx.activeName;
|
|
183
|
+
if (connectionName && sessions.has(connectionName))
|
|
184
|
+
liveEvents.emit("changed", connectionName);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function handleTool(ctx, name, args) {
|
|
188
|
+
switch (name) {
|
|
189
|
+
case "ibmi.tn5250.connect":
|
|
190
|
+
return connect(ctx, args || {});
|
|
191
|
+
case "ibmi.tn5250.readScreen":
|
|
192
|
+
return json(sessionView(requireSession(ctx, args)));
|
|
193
|
+
case "ibmi.tn5250.setField":
|
|
194
|
+
return setField(ctx, args || {});
|
|
195
|
+
case "ibmi.tn5250.sendKeys":
|
|
196
|
+
return sendKeys(ctx, args || {});
|
|
197
|
+
case "ibmi.tn5250.click":
|
|
198
|
+
return click(ctx, args || {});
|
|
199
|
+
case "ibmi.tn5250.waitFor":
|
|
200
|
+
return waitFor(ctx, args || {});
|
|
201
|
+
case "ibmi.tn5250.snapshot": {
|
|
202
|
+
const session = requireSession(ctx, args);
|
|
203
|
+
const view = sessionView(session);
|
|
204
|
+
return json({ capturedAt: new Date().toISOString(), connectionName: session.connectionName, plainText: view.text.join("\n"), screen: view });
|
|
205
|
+
}
|
|
206
|
+
case "ibmi.tn5250.disconnect": {
|
|
207
|
+
const connectionName = getConnectionName(ctx, args);
|
|
208
|
+
const session = sessions.get(connectionName);
|
|
209
|
+
const existed = closeSession(connectionName);
|
|
210
|
+
const endedJob = session?.signedOn && session.device ? await endDisconnectedJob(ctx, connectionName, session.device) : undefined;
|
|
211
|
+
return json({ disconnected: existed, connectionName, ...(endedJob ? { endedJob } : {}) });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
215
|
+
}
|
|
216
|
+
async function connect(ctx, args) {
|
|
217
|
+
const connectionName = getConnectionName(ctx, args);
|
|
218
|
+
const existing = sessions.get(connectionName);
|
|
219
|
+
if (existing && !existing.client.closed) {
|
|
220
|
+
return json({ reused: true, ...sessionView(existing) });
|
|
221
|
+
}
|
|
222
|
+
if (existing)
|
|
223
|
+
sessions.delete(connectionName);
|
|
224
|
+
const stored = await ctx.store.getConnection(connectionName);
|
|
225
|
+
if (!stored)
|
|
226
|
+
throw new Error(`Unknown connection: ${connectionName}`);
|
|
227
|
+
const globalSettings = typeof ctx.store.getSettings === "function" ? await ctx.store.getSettings() : {};
|
|
228
|
+
const settings = { ...(globalSettings || {}), ...(stored.settings || {}) };
|
|
229
|
+
const tlsSetting = typeof args.tls === "boolean" ? args.tls : typeof settings.tn5250Tls === "boolean" ? settings.tn5250Tls : undefined;
|
|
230
|
+
const portSetting = args.port ?? settings.tn5250Port;
|
|
231
|
+
const port = portSetting !== undefined ? requirePort(portSetting) : tlsSetting ? 992 : 23;
|
|
232
|
+
const useTls = tlsSetting ?? port === 992;
|
|
233
|
+
const deviceName = optionalDeviceName(args.deviceName ?? settings.tn5250DeviceName);
|
|
234
|
+
const terminalType = args.screenSize === "27x132" ? "IBM-3477-FC" : "IBM-3179-2";
|
|
235
|
+
const timeoutMs = clampNumber(args.timeoutMs, 20000, 1000, 120000);
|
|
236
|
+
const ccsid = requireCcsid(args.ccsid ?? settings.tn5250Ccsid ?? 37);
|
|
237
|
+
let password;
|
|
238
|
+
if (args.signOn) {
|
|
239
|
+
const conn = await ctx.ensureActive(connectionName);
|
|
240
|
+
await enforceWritable(ctx, conn, "tn5250.signOn", { ...args, connectionName });
|
|
241
|
+
password = await tn5250Deps.getPassword(connectionName);
|
|
242
|
+
if (!password)
|
|
243
|
+
throw new Error(`No stored password for ${connectionName}; signOn needs the connection's saved password`);
|
|
244
|
+
}
|
|
245
|
+
const client = new Tn5250Client({
|
|
246
|
+
host: stored.host,
|
|
247
|
+
port,
|
|
248
|
+
tls: useTls,
|
|
249
|
+
terminalType,
|
|
250
|
+
deviceName,
|
|
251
|
+
ccsid,
|
|
252
|
+
// The password is only offered in the telnet negotiation when it is encrypted by TLS.
|
|
253
|
+
autoSignOn: password && useTls ? { user: stored.username, password } : undefined,
|
|
254
|
+
connectTimeoutMs: timeoutMs,
|
|
255
|
+
checkCertificate: info => tn5250Deps.checkCertificate(info)
|
|
256
|
+
});
|
|
257
|
+
await client.connect();
|
|
258
|
+
const attnWaitMs = settings.tn5250AttnWaitMs !== undefined ? clampNumber(settings.tn5250AttnWaitMs, HOST_KEY_ANSWER_MS, 250, 15000) : HOST_KEY_ANSWER_MS;
|
|
259
|
+
const session = { connectionName, host: stored.host, port, tls: useTls, client, createdAt: new Date().toISOString(), attnWaitMs };
|
|
260
|
+
sessions.set(connectionName, session);
|
|
261
|
+
client.on("update", () => liveEvents.emit("changed", connectionName));
|
|
262
|
+
client.on("close", () => liveEvents.emit("changed", connectionName));
|
|
263
|
+
if (settings.tn5250LiveView !== false)
|
|
264
|
+
await ensureLiveServer(settings.tn5250LiveViewPort);
|
|
265
|
+
try {
|
|
266
|
+
let settled = await client.waitForSettled(timeoutMs);
|
|
267
|
+
session.device = deviceFromScreen(client.screen) || deviceName;
|
|
268
|
+
let signOn;
|
|
269
|
+
if (password) {
|
|
270
|
+
signOn = { method: client.autoSignOnOffered ? "telnet-environment" : "sign-on-screen" };
|
|
271
|
+
const form = signOnFields(client.screen);
|
|
272
|
+
if (form && settled) {
|
|
273
|
+
if (client.screen.inputInhibited)
|
|
274
|
+
client.screen.reset();
|
|
275
|
+
client.screen.setFieldValue(form.user, stored.username);
|
|
276
|
+
client.screen.setFieldValue(form.password, password);
|
|
277
|
+
client.screen.cursor = form.password.start;
|
|
278
|
+
client.sendKey("ENTER");
|
|
279
|
+
session.lastKey = "ENTER";
|
|
280
|
+
settled = await client.waitForSettled(timeoutMs);
|
|
281
|
+
signOn.method = "sign-on-screen";
|
|
282
|
+
}
|
|
283
|
+
signOn.stillOnSignOnScreen = Boolean(signOnFields(client.screen));
|
|
284
|
+
session.signedOn = !signOn.stillOnSignOnScreen;
|
|
285
|
+
}
|
|
286
|
+
return json({ ...sessionView(session), settled, ...(signOn ? { signOn } : {}) });
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
closeSession(connectionName);
|
|
290
|
+
throw err;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/** The user and password fields of a sign-on style screen, if this is one. */
|
|
294
|
+
function signOnFields(screen) {
|
|
295
|
+
const inputs = screen.inputFields();
|
|
296
|
+
const password = inputs.find(f => f.hidden);
|
|
297
|
+
if (!password)
|
|
298
|
+
return undefined;
|
|
299
|
+
const user = inputs.filter(f => !f.hidden && f.start < password.start).pop();
|
|
300
|
+
return user ? { user, password } : undefined;
|
|
301
|
+
}
|
|
302
|
+
async function setField(ctx, args) {
|
|
303
|
+
const session = requireOpenSession(ctx, args);
|
|
304
|
+
holdForPerson(session);
|
|
305
|
+
const screen = session.client.screen;
|
|
306
|
+
const field = resolveField(screen, args);
|
|
307
|
+
if (!field)
|
|
308
|
+
throw new Error(`TN5250 field not found: ${describeFieldRef(args)}`);
|
|
309
|
+
if (field.bypass)
|
|
310
|
+
throw new Error(`TN5250 field ${screen.fieldId(field)} is protected`);
|
|
311
|
+
let value;
|
|
312
|
+
if (args.useStoredPassword) {
|
|
313
|
+
if (!field.hidden)
|
|
314
|
+
throw new Error("useStoredPassword can only fill a hidden (non-display) field");
|
|
315
|
+
const password = await tn5250Deps.getPassword(session.connectionName);
|
|
316
|
+
if (!password)
|
|
317
|
+
throw new Error(`No stored password for ${session.connectionName}`);
|
|
318
|
+
value = password;
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
if (typeof args.value !== "string")
|
|
322
|
+
throw new Error("value is required (or useStoredPassword=true)");
|
|
323
|
+
value = args.value;
|
|
324
|
+
}
|
|
325
|
+
if (screen.inputInhibited)
|
|
326
|
+
screen.reset();
|
|
327
|
+
screen.setFieldValue(field, value);
|
|
328
|
+
session.lastActor = "agent";
|
|
329
|
+
return json(sessionView(session));
|
|
330
|
+
}
|
|
331
|
+
async function sendKeys(ctx, args) {
|
|
332
|
+
const session = requireOpenSession(ctx, args);
|
|
333
|
+
holdForPerson(session);
|
|
334
|
+
return json(await runInput(ctx, session, args, "agent"));
|
|
335
|
+
}
|
|
336
|
+
/** Type, press local keys and at most one host key; shared by the tools (agent) and the live view (person). */
|
|
337
|
+
async function runInput(ctx, session, args, actor) {
|
|
338
|
+
const { client } = session;
|
|
339
|
+
const screen = client.screen;
|
|
340
|
+
const keys = parseKeys(args.keys);
|
|
341
|
+
const text = typeof args.text === "string" ? args.text : undefined;
|
|
342
|
+
if (keys.length === 0 && !text)
|
|
343
|
+
throw new Error("keys or text is required");
|
|
344
|
+
const aidIndex = keys.findIndex(isAidKey);
|
|
345
|
+
for (const key of keys) {
|
|
346
|
+
if (!LOCAL_KEYS.has(key) && !isAidKey(key)) {
|
|
347
|
+
throw new Error(`Unsupported key: ${key}. Esc is Attn and Shift+Esc is SysReq; see the tool description for the key names.`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (aidIndex >= 0 && aidIndex !== keys.length - 1) {
|
|
351
|
+
throw new Error("Only one AID key (Enter, F1-F24, PageUp, ...) is allowed, and it must be the last key");
|
|
352
|
+
}
|
|
353
|
+
const timeoutMs = clampNumber(args.timeoutMs, 30000, 250, 300000);
|
|
354
|
+
const autoReset = screen.inputInhibited;
|
|
355
|
+
if (autoReset)
|
|
356
|
+
screen.reset();
|
|
357
|
+
if (args.cursorRow !== undefined || args.cursorCol !== undefined) {
|
|
358
|
+
screen.setCursor(Number(args.cursorRow ?? screen.rowCol(screen.cursor).row), Number(args.cursorCol ?? screen.rowCol(screen.cursor).col));
|
|
359
|
+
}
|
|
360
|
+
if (text)
|
|
361
|
+
screen.typeText(text);
|
|
362
|
+
session.lastActor = actor;
|
|
363
|
+
const localKeys = aidIndex >= 0 ? keys.slice(0, aidIndex) : keys;
|
|
364
|
+
for (const key of localKeys)
|
|
365
|
+
applyLocalKey(screen, key);
|
|
366
|
+
let settled;
|
|
367
|
+
let note;
|
|
368
|
+
const aidKey = aidIndex >= 0 ? keys[aidIndex] : undefined;
|
|
369
|
+
if (aidKey) {
|
|
370
|
+
if (screen.keyboardLocked && !screen.inputInhibited && !["ATTN", "SYSREQ"].includes(aidKey)) {
|
|
371
|
+
throw new Error("The keyboard is locked (the host has not finished); use ibmi.tn5250.waitFor first, or Attn/SysReq");
|
|
372
|
+
}
|
|
373
|
+
const conn = await ctx.ensureActive(session.connectionName);
|
|
374
|
+
const gateArgs = { ...args, connectionName: session.connectionName };
|
|
375
|
+
const aid = aidForKey(aidKey);
|
|
376
|
+
const commands = aid !== undefined && !AID_WITHOUT_DATA.has(aid) ? commandLineEntries(screen) : [];
|
|
377
|
+
const gate = actor === "person" ? enforceWritableForPerson : enforceWritable;
|
|
378
|
+
if (commands.length > 0) {
|
|
379
|
+
// Text on a command line is run as CL by the host, so it gets the cl.run checks.
|
|
380
|
+
for (const command of commands)
|
|
381
|
+
await gate(ctx, conn, "cl.run", { ...gateArgs, command, environment: "ile" });
|
|
382
|
+
}
|
|
383
|
+
else {
|
|
384
|
+
await gate(ctx, conn, "tn5250.sendKeys", gateArgs);
|
|
385
|
+
}
|
|
386
|
+
const hostKey = aidKey === "ATTN" || aidKey === "SYSREQ";
|
|
387
|
+
const wasLocked = screen.keyboardLocked;
|
|
388
|
+
const recordsBefore = client.recordsReceived;
|
|
389
|
+
client.sendKey(aidKey);
|
|
390
|
+
session.lastKey = aidKey;
|
|
391
|
+
if (hostKey) {
|
|
392
|
+
// The host may not answer Attn (no attention program) or SysReq; don't leave the keyboard locked forever.
|
|
393
|
+
const startedAt = Date.now();
|
|
394
|
+
const waitMs = Math.min(timeoutMs, session.attnWaitMs ?? HOST_KEY_ANSWER_MS);
|
|
395
|
+
const answered = await client.waitFor(() => client.recordsReceived > recordsBefore, waitMs);
|
|
396
|
+
if (!answered) {
|
|
397
|
+
screen.keyboardLocked = wasLocked;
|
|
398
|
+
settled = !wasLocked;
|
|
399
|
+
note = aidKey === "ATTN"
|
|
400
|
+
? "This screen has no attention menu: no attention program is active here. Use F3 to exit or F12 to cancel to go back. The keyboard was unlocked again."
|
|
401
|
+
: "The host did not answer System Request on this screen. The keyboard was unlocked again.";
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
settled = await client.waitForSettled(Math.max(250, timeoutMs - (Date.now() - startedAt)));
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
settled = await client.waitForSettled(timeoutMs);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return {
|
|
412
|
+
...sessionView(session),
|
|
413
|
+
...(aidKey ? { sent: aidKey, settled } : {}),
|
|
414
|
+
...(note ? { note } : {}),
|
|
415
|
+
...(autoReset ? { autoReset: true } : {})
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
async function click(ctx, args) {
|
|
419
|
+
const session = requireOpenSession(ctx, args);
|
|
420
|
+
holdForPerson(session);
|
|
421
|
+
return json(await runClick(ctx, session, args, "agent"));
|
|
422
|
+
}
|
|
423
|
+
async function runClick(ctx, session, args, actor) {
|
|
424
|
+
const screen = session.client.screen;
|
|
425
|
+
const row = Number(args.row);
|
|
426
|
+
const col = Number(args.col);
|
|
427
|
+
screen.address(row, col); // validates the position
|
|
428
|
+
const key = args.doubleClick ? "ENTER" : args.hotspots === false ? undefined : screen.hotspotAt(row, col);
|
|
429
|
+
if (key) {
|
|
430
|
+
return runInput(ctx, session, { connectionName: session.connectionName, cursorRow: row, cursorCol: col, keys: key, timeoutMs: args.timeoutMs, approve: args.approve }, actor);
|
|
431
|
+
}
|
|
432
|
+
if (screen.inputInhibited)
|
|
433
|
+
screen.reset();
|
|
434
|
+
screen.setCursor(row, col);
|
|
435
|
+
screen.version += 1;
|
|
436
|
+
session.lastActor = actor;
|
|
437
|
+
return sessionView(session);
|
|
438
|
+
}
|
|
439
|
+
/** The agent must not type over the person: refuse while they are using the live view. */
|
|
440
|
+
function holdForPerson(session) {
|
|
441
|
+
if (session.personInputAt && Date.now() - session.personInputAt < PERSON_HOLD_MS) {
|
|
442
|
+
throw new Error("The person is typing in the live 5250 view. Wait a few seconds, read the screen again (ibmi.tn5250.readScreen) and then continue.");
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
async function ensureLiveServer(port) {
|
|
446
|
+
if (liveServer)
|
|
447
|
+
return liveServer;
|
|
448
|
+
if (!liveServerStarting) {
|
|
449
|
+
const preferred = Number.isInteger(Number(port)) && Number(port) >= 0 && Number(port) <= 65535 && port !== undefined ? Number(port) : 3981;
|
|
450
|
+
liveServerStarting = startLiveServer(liveProvider, preferred)
|
|
451
|
+
.then(server => { liveServer = server; return server; })
|
|
452
|
+
.catch(() => undefined)
|
|
453
|
+
.finally(() => { liveServerStarting = undefined; });
|
|
454
|
+
}
|
|
455
|
+
return liveServerStarting;
|
|
456
|
+
}
|
|
457
|
+
/** What the live view server reads and drives. */
|
|
458
|
+
const liveProvider = {
|
|
459
|
+
events: liveEvents,
|
|
460
|
+
list: () => [...sessions.values()].map(session => ({
|
|
461
|
+
connectionName: session.connectionName,
|
|
462
|
+
host: session.host,
|
|
463
|
+
connected: !session.client.closed,
|
|
464
|
+
signedOn: Boolean(session.signedOn),
|
|
465
|
+
lastActor: session.lastActor
|
|
466
|
+
})),
|
|
467
|
+
screen: (connectionName) => {
|
|
468
|
+
const session = sessions.get(connectionName);
|
|
469
|
+
if (!session)
|
|
470
|
+
return undefined;
|
|
471
|
+
const screen = session.client.screen;
|
|
472
|
+
return { ...sessionView(session), runs: screen.renderRuns(), personHoldMs: PERSON_HOLD_MS };
|
|
473
|
+
},
|
|
474
|
+
input: async (connectionName, input) => {
|
|
475
|
+
const session = sessions.get(connectionName);
|
|
476
|
+
if (!session)
|
|
477
|
+
throw new Error(`No 5250 session for ${connectionName}`);
|
|
478
|
+
if (session.client.closed)
|
|
479
|
+
throw new Error(`The 5250 session for ${connectionName} is closed`);
|
|
480
|
+
if (!liveCtx)
|
|
481
|
+
throw new Error("The MCP server is not ready");
|
|
482
|
+
session.personInputAt = Date.now();
|
|
483
|
+
try {
|
|
484
|
+
if (input.click) {
|
|
485
|
+
return await runClick(liveCtx, session, { ...input.click, timeoutMs: 30000 }, "person");
|
|
486
|
+
}
|
|
487
|
+
return await runInput(liveCtx, session, {
|
|
488
|
+
connectionName,
|
|
489
|
+
text: input.text,
|
|
490
|
+
keys: input.keys,
|
|
491
|
+
cursorRow: input.cursorRow,
|
|
492
|
+
cursorCol: input.cursorCol,
|
|
493
|
+
timeoutMs: 30000
|
|
494
|
+
}, "person");
|
|
495
|
+
}
|
|
496
|
+
finally {
|
|
497
|
+
session.personInputAt = Date.now();
|
|
498
|
+
liveEvents.emit("changed", connectionName);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
/** Address of the live view for a session, once the live view server runs. */
|
|
503
|
+
export function liveViewUrl(connectionName) {
|
|
504
|
+
return liveServer?.urlFor(connectionName);
|
|
505
|
+
}
|
|
506
|
+
/** For tests: stop the live view server. */
|
|
507
|
+
export async function stopLiveServer() {
|
|
508
|
+
const server = liveServer;
|
|
509
|
+
liveServer = undefined;
|
|
510
|
+
await server?.close();
|
|
511
|
+
}
|
|
512
|
+
async function waitFor(ctx, args) {
|
|
513
|
+
const session = requireSession(ctx, args);
|
|
514
|
+
const { client } = session;
|
|
515
|
+
const timeoutMs = clampNumber(args?.timeoutMs, 5000, 100, 300000);
|
|
516
|
+
const text = typeof args?.text === "string" && args.text.length > 0 ? args.text.toLowerCase() : undefined;
|
|
517
|
+
const needUnlock = typeof args?.keyboardUnlocked === "boolean" ? args.keyboardUnlocked : !text;
|
|
518
|
+
const matched = await client.waitFor(() => {
|
|
519
|
+
if (text && !client.screen.renderRows().some(row => row.toLowerCase().includes(text)))
|
|
520
|
+
return false;
|
|
521
|
+
return !needUnlock || client.isReady();
|
|
522
|
+
}, timeoutMs);
|
|
523
|
+
return json({ matched, text: args?.text, keyboardUnlocked: needUnlock, timeoutMs, screen: sessionView(session) });
|
|
524
|
+
}
|
|
525
|
+
function applyLocalKey(screen, key) {
|
|
526
|
+
switch (key) {
|
|
527
|
+
case "TAB":
|
|
528
|
+
screen.tab();
|
|
529
|
+
break;
|
|
530
|
+
case "BACKTAB":
|
|
531
|
+
screen.backTab();
|
|
532
|
+
break;
|
|
533
|
+
case "HOME":
|
|
534
|
+
screen.home();
|
|
535
|
+
break;
|
|
536
|
+
case "END":
|
|
537
|
+
screen.endOfField();
|
|
538
|
+
break;
|
|
539
|
+
case "RESET":
|
|
540
|
+
screen.reset();
|
|
541
|
+
break;
|
|
542
|
+
case "ERASEEOF":
|
|
543
|
+
screen.eraseToEndOfField();
|
|
544
|
+
break;
|
|
545
|
+
case "ERASEINPUT":
|
|
546
|
+
screen.eraseInput();
|
|
547
|
+
break;
|
|
548
|
+
case "FIELDEXIT":
|
|
549
|
+
screen.fieldExit();
|
|
550
|
+
break;
|
|
551
|
+
case "FIELDPLUS":
|
|
552
|
+
screen.fieldSign(false);
|
|
553
|
+
break;
|
|
554
|
+
case "FIELDMINUS":
|
|
555
|
+
screen.fieldSign(true);
|
|
556
|
+
break;
|
|
557
|
+
case "DUP":
|
|
558
|
+
screen.dup();
|
|
559
|
+
break;
|
|
560
|
+
case "INSERT":
|
|
561
|
+
screen.toggleInsert();
|
|
562
|
+
break;
|
|
563
|
+
case "DELETE":
|
|
564
|
+
screen.deleteChar();
|
|
565
|
+
break;
|
|
566
|
+
case "UP":
|
|
567
|
+
screen.moveCursor(-1, 0);
|
|
568
|
+
break;
|
|
569
|
+
case "DOWN":
|
|
570
|
+
screen.moveCursor(1, 0);
|
|
571
|
+
break;
|
|
572
|
+
case "LEFT":
|
|
573
|
+
screen.moveCursor(0, -1);
|
|
574
|
+
break;
|
|
575
|
+
case "RIGHT":
|
|
576
|
+
screen.moveCursor(0, 1);
|
|
577
|
+
break;
|
|
578
|
+
case "NEWLINE":
|
|
579
|
+
screen.newLine();
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
function isAidKey(key) {
|
|
584
|
+
return key === "ATTN" || key === "SYSREQ" || aidForKey(key) !== undefined;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Key names to canonical keys. Accepts "Field+", "Field-", "Shift+Tab",
|
|
588
|
+
* "Shift+Esc", "Tab+Enter" style chords and "Down*3" repeats.
|
|
589
|
+
*/
|
|
590
|
+
export function parseKeys(value) {
|
|
591
|
+
if (value === undefined || value === null)
|
|
592
|
+
return [];
|
|
593
|
+
const text = String(value).replace(/\bshift\s*\+\s*/gi, "SHIFT+");
|
|
594
|
+
const out = [];
|
|
595
|
+
for (const raw of text.split(/[\s,]+/).filter(Boolean)) {
|
|
596
|
+
const repeat = /^(.+?)\*(\d{1,3})$/.exec(raw);
|
|
597
|
+
const token = repeat ? repeat[1] : raw;
|
|
598
|
+
const count = repeat ? Number(repeat[2]) : 1;
|
|
599
|
+
const keys = canonicalKeys(token);
|
|
600
|
+
if (repeat && (keys.length !== 1 || !LOCAL_KEYS.has(keys[0])))
|
|
601
|
+
throw new Error(`Only a single local key can be repeated: ${raw}`);
|
|
602
|
+
if (count < 1 || count > 200)
|
|
603
|
+
throw new Error(`Repeat count must be 1-200: ${raw}`);
|
|
604
|
+
for (let n = 0; n < count; n += 1)
|
|
605
|
+
out.push(...keys);
|
|
606
|
+
}
|
|
607
|
+
return out;
|
|
608
|
+
}
|
|
609
|
+
function canonicalKeys(token) {
|
|
610
|
+
const upper = token.toUpperCase().replace(/_/g, "");
|
|
611
|
+
if (upper === "FIELD+")
|
|
612
|
+
return ["FIELDPLUS"];
|
|
613
|
+
if (upper === "FIELD-")
|
|
614
|
+
return ["FIELDMINUS"];
|
|
615
|
+
if (upper.startsWith("SHIFT+"))
|
|
616
|
+
return [canonicalKey(`SHIFT${upper.substring(6)}`)];
|
|
617
|
+
return upper.split("+").filter(Boolean).map(canonicalKey);
|
|
618
|
+
}
|
|
619
|
+
function canonicalKey(name) {
|
|
620
|
+
const key = name.replace(/-/g, "");
|
|
621
|
+
return LOCAL_KEY_ALIASES[key] || hostKeyFor(key) || key;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Text in command lines (fields labelled ===>). Unmodified ones are included
|
|
625
|
+
* too, since a Read Input Fields response sends every field.
|
|
626
|
+
*/
|
|
627
|
+
function commandLineEntries(screen) {
|
|
628
|
+
const rows = screen.renderRows();
|
|
629
|
+
return screen.fields
|
|
630
|
+
.filter(f => screen.isCommandLine(f, rows))
|
|
631
|
+
.map(f => screen.fieldText(f).trim())
|
|
632
|
+
.filter(Boolean);
|
|
633
|
+
}
|
|
634
|
+
function resolveField(screen, args) {
|
|
635
|
+
if (args?.fieldId !== undefined && args.fieldId !== null && String(args.fieldId).trim() !== "") {
|
|
636
|
+
const id = String(args.fieldId).trim().toLowerCase();
|
|
637
|
+
if (id === "command") {
|
|
638
|
+
const rows = screen.renderRows();
|
|
639
|
+
return screen.fields.find(f => screen.isCommandLine(f, rows));
|
|
640
|
+
}
|
|
641
|
+
if (/^\d+$/.test(id))
|
|
642
|
+
return screen.fields[Number(id) - 1];
|
|
643
|
+
const match = /^r(\d+)c(\d+)$/.exec(id);
|
|
644
|
+
if (match)
|
|
645
|
+
return screen.fields.find(f => screen.fieldId(f) === `r${Number(match[1])}c${Number(match[2])}`);
|
|
646
|
+
return undefined;
|
|
647
|
+
}
|
|
648
|
+
if (args?.row !== undefined && args?.col !== undefined) {
|
|
649
|
+
return screen.fieldAt(screen.address(Number(args.row), Number(args.col)));
|
|
650
|
+
}
|
|
651
|
+
throw new Error("fieldId or row and col are required");
|
|
652
|
+
}
|
|
653
|
+
function describeFieldRef(args) {
|
|
654
|
+
return args?.fieldId !== undefined ? String(args.fieldId) : `row ${args?.row} column ${args?.col}`;
|
|
655
|
+
}
|
|
656
|
+
function sessionView(session) {
|
|
657
|
+
const { client } = session;
|
|
658
|
+
return {
|
|
659
|
+
connectionName: session.connectionName,
|
|
660
|
+
host: session.host,
|
|
661
|
+
port: session.port,
|
|
662
|
+
tls: session.tls,
|
|
663
|
+
terminalType: client.terminalType,
|
|
664
|
+
connected: !client.closed,
|
|
665
|
+
...(client.closed ? { closeReason: client.closeReason } : {}),
|
|
666
|
+
lastKey: session.lastKey,
|
|
667
|
+
...(session.lastActor ? { lastActor: session.lastActor } : {}),
|
|
668
|
+
...(session.personInputAt && Date.now() - session.personInputAt < PERSON_HOLD_MS ? { personTyping: true } : {}),
|
|
669
|
+
...(liveServer ? { liveViewUrl: liveServer.urlFor(session.connectionName) } : {}),
|
|
670
|
+
...client.screen.view(),
|
|
671
|
+
...(client.screen.warnings.length > 0 ? { warnings: client.screen.warnings.slice(-5) } : {})
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function requireSession(ctx, args) {
|
|
675
|
+
const connectionName = getConnectionName(ctx, args);
|
|
676
|
+
const session = sessions.get(connectionName);
|
|
677
|
+
if (!session)
|
|
678
|
+
throw new Error(`TN5250 session for ${connectionName} not found. Call ibmi.tn5250.connect first.`);
|
|
679
|
+
return session;
|
|
680
|
+
}
|
|
681
|
+
function requireOpenSession(ctx, args) {
|
|
682
|
+
const session = requireSession(ctx, args);
|
|
683
|
+
if (session.client.closed) {
|
|
684
|
+
throw new Error(`TN5250 session for ${session.connectionName} is closed (${session.client.closeReason}). Call ibmi.tn5250.connect again.`);
|
|
685
|
+
}
|
|
686
|
+
return session;
|
|
687
|
+
}
|
|
688
|
+
/** The "Device:" value on a sign-on screen. */
|
|
689
|
+
function deviceFromScreen(screen) {
|
|
690
|
+
for (const line of screen.renderRows()) {
|
|
691
|
+
const match = /\bDevice[ .]*:\s+([A-Z#@$][A-Z0-9#@$_]{0,9})\b/.exec(line);
|
|
692
|
+
if (match)
|
|
693
|
+
return match[1];
|
|
694
|
+
}
|
|
695
|
+
return undefined;
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Closing the socket leaves a signed-on job disconnected (DSC) until the system
|
|
699
|
+
* ends it. End our own job for that device right away; best effort.
|
|
700
|
+
*/
|
|
701
|
+
async function endDisconnectedJob(ctx, connectionName, device) {
|
|
702
|
+
try {
|
|
703
|
+
const conn = await ctx.ensureActive(connectionName);
|
|
704
|
+
if (!/^[A-Z#@$][A-Z0-9#@$_]{0,9}$/.test(device))
|
|
705
|
+
return undefined;
|
|
706
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
707
|
+
// Only a disconnected job of the signed-on user on that device.
|
|
708
|
+
const rows = await conn.runSQL(`select job_name from table(qsys2.active_job_info(job_name_filter => '${device}')) x ` +
|
|
709
|
+
`where job_status = 'DSC' and job_name like '%/' concat current user concat '/%'`);
|
|
710
|
+
const job = rows?.[0]?.JOB_NAME;
|
|
711
|
+
if (job && /^\d{6}\/[A-Z0-9#@$_]{1,10}\/[A-Z0-9#@$_]{1,10}$/.test(job)) {
|
|
712
|
+
const result = await conn.runCL(`ENDJOB JOB(${job}) OPTION(*IMMED)`);
|
|
713
|
+
return result?.code === 0 ? job : undefined;
|
|
714
|
+
}
|
|
715
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
// the system ends disconnected jobs on its own (QDSCJOBITV)
|
|
720
|
+
}
|
|
721
|
+
return undefined;
|
|
722
|
+
}
|
|
723
|
+
function closeSession(connectionName) {
|
|
724
|
+
const session = sessions.get(connectionName);
|
|
725
|
+
if (!session)
|
|
726
|
+
return false;
|
|
727
|
+
session.client.close();
|
|
728
|
+
sessions.delete(connectionName);
|
|
729
|
+
liveEvents.emit("changed", connectionName);
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
732
|
+
function requireCcsid(value) {
|
|
733
|
+
const ccsid = Number(value);
|
|
734
|
+
if (!SUPPORTED_CCSIDS.includes(ccsid)) {
|
|
735
|
+
throw new Error(`Unsupported TN5250 CCSID: ${value}. Supported single-byte code pages: ${SUPPORTED_CCSIDS.join(", ")}`);
|
|
736
|
+
}
|
|
737
|
+
return ccsid;
|
|
738
|
+
}
|
|
739
|
+
function requirePort(value) {
|
|
740
|
+
const port = Number(value);
|
|
741
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
742
|
+
throw new Error(`Invalid TN5250 port: ${value}`);
|
|
743
|
+
return port;
|
|
744
|
+
}
|
|
745
|
+
function optionalDeviceName(value) {
|
|
746
|
+
if (value === undefined || value === null || String(value).trim() === "")
|
|
747
|
+
return undefined;
|
|
748
|
+
const name = String(value).trim().toUpperCase();
|
|
749
|
+
if (!/^[A-Z#@$][A-Z0-9#@$_]{0,9}$/.test(name))
|
|
750
|
+
throw new Error(`Invalid deviceName: ${value}`);
|
|
751
|
+
return name;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Hide what is typed into hidden (non-display) fields from logs and audit.
|
|
755
|
+
* When the target field cannot be determined the value is hidden too.
|
|
756
|
+
*/
|
|
757
|
+
function redactArgs(ctx, name, args) {
|
|
758
|
+
if (!args || typeof args !== "object")
|
|
759
|
+
return args;
|
|
760
|
+
if (name !== "ibmi.tn5250.setField" && name !== "ibmi.tn5250.sendKeys")
|
|
761
|
+
return args;
|
|
762
|
+
let hidden = true;
|
|
763
|
+
try {
|
|
764
|
+
const session = sessions.get(args.connectionName || ctx.activeName || "");
|
|
765
|
+
if (session) {
|
|
766
|
+
const screen = session.client.screen;
|
|
767
|
+
if (name === "ibmi.tn5250.setField") {
|
|
768
|
+
const field = resolveField(screen, args);
|
|
769
|
+
hidden = !field || field.hidden;
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
const cursor = args.cursorRow !== undefined || args.cursorCol !== undefined
|
|
773
|
+
? screen.address(Number(args.cursorRow ?? screen.rowCol(screen.cursor).row), Number(args.cursorCol ?? screen.rowCol(screen.cursor).col))
|
|
774
|
+
: screen.cursor;
|
|
775
|
+
const field = screen.fieldAt(cursor);
|
|
776
|
+
hidden = !field || field.hidden;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
catch {
|
|
781
|
+
hidden = true;
|
|
782
|
+
}
|
|
783
|
+
if (!hidden)
|
|
784
|
+
return args;
|
|
785
|
+
const copy = { ...args };
|
|
786
|
+
if (name === "ibmi.tn5250.setField" && "value" in copy)
|
|
787
|
+
copy.value = REDACTED;
|
|
788
|
+
if (name === "ibmi.tn5250.sendKeys" && "text" in copy)
|
|
789
|
+
copy.text = REDACTED;
|
|
790
|
+
return copy;
|
|
791
|
+
}
|
|
792
|
+
function onDisconnect(connectionName) {
|
|
793
|
+
if (connectionName) {
|
|
794
|
+
closeSession(connectionName);
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
for (const name of [...sessions.keys()])
|
|
798
|
+
closeSession(name);
|
|
799
|
+
}
|
|
800
|
+
export const tn5250Module = { tools, handle, redactArgs, onDisconnect };
|