@aryacode/dsh-engineering 0.4.5 → 0.4.7

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.
@@ -1,16 +1,20 @@
1
1
  /**
2
- * SDK-free live reads over EtherNet/IP.
2
+ * SDK-free EtherNet/IP surface: reads, identity, discovery and the two
3
+ * approval-gated writes.
3
4
  *
4
- * Two tools: a bounded foreground poll, and a session-owned trend job the chart
5
- * can follow without a model call per sample. Both read declared scalar tags,
6
- * never write, and state that live logic is not the exported logic.
5
+ * Reads never change the controller and need no approval. Writes do: a write is
6
+ * refused unless the row's config allows writes AND a human approves that exact
7
+ * operation, and its result is the value read back over CIP, not an assumption.
7
8
  *
8
9
  * @module dsh-engineering-l5x/tools/live
9
10
  */
10
11
  import { success } from "../core/result.js";
11
- import { integer, list, object, objectItem, string } from "../core/params.js";
12
+ import { integer, list, object, objectItem, scalar, string } from "../core/params.js";
12
13
  import { pollingRequest } from "../engine/direct-polling.js";
14
+ import { batchReadRequest, controllerTarget, discoverRequest, writableTagRequest } from "../engine/cip-request.js";
15
+ import { decodeClockResult, decodeDiscoverResult, decodeReadResult, decodeWriteClockResult, decodeWriteResult, } from "../engine/cip-transaction.js";
13
16
  import { L5xError } from "../core/errors.js";
17
+ import { requireHumanApproval } from "../approvals.js";
14
18
  import { PROJECT_ID, optionalInteger, optionalString, requiredString, tool } from "./common.js";
15
19
  /** A direct read is not a guarantee about the scan. */
16
20
  const LIVE_COVERAGE = {
@@ -21,6 +25,15 @@ const LIVE_COVERAGE = {
21
25
  'transitions between sweeps',
22
26
  ],
23
27
  };
28
+ /** A verified write is a fact about the tag, not about the machine. */
29
+ const WRITE_COVERAGE = {
30
+ complete: false,
31
+ unverified: [
32
+ 'that the written value is the intended process change',
33
+ 'that the logic reacts as expected on the next scan',
34
+ 'that the value is still in place after the next scan',
35
+ ],
36
+ };
24
37
  /** The tags argument, as flat objects rather than a JSON string. */
25
38
  function tagsOf(args) {
26
39
  const raw = args.tags;
@@ -41,28 +54,34 @@ function tagsOf(args) {
41
54
  });
42
55
  return JSON.stringify(tags);
43
56
  }
44
- /** The same tag parameter for both tools. */
57
+ /** The same tag parameter for the polling tools. */
45
58
  const TAGS_PARAM = list('Controller-scoped scalar tags to read, 1 to 16. Each entry names the tag and optionally its program.', objectItem('One declared scalar tag.', {
46
59
  name: string('Tag name. Example: "LineSpeed".'),
47
60
  program: string('Program scope for a program-scoped tag. Omit for a controller tag.'),
48
61
  }, ['name']), { minItems: 1, maxItems: 16 });
62
+ /** The controller address shared by every non-discovery call. */
63
+ const target = {
64
+ ip_address: string('Controller IPv4 address the human named. Example: "192.168.1.10".'),
65
+ slot: integer('CPU slot, 0 to 31. Default 0.', { minimum: 0, maximum: 31, default: 0 }),
66
+ };
49
67
  /**
50
68
  * The live tools.
51
69
  *
52
70
  * @param session - Project handles for the calling chat.
53
71
  * @param polling - The polling engine and its configuration.
54
- * @param ctx - Plugin context that may provide the job service.
72
+ * @param ctx - Plugin context that may provide the job and approval services.
73
+ * @param extensions - One-shot transactions and the write switch.
55
74
  * @returns Tool definitions in registration order.
56
75
  */
57
- export function liveTools(session, polling, ctx) {
76
+ export function liveTools(session, polling, ctx, extensions) {
77
+ const { transactions } = extensions;
58
78
  return [
59
79
  tool({
60
80
  name: 'poll_live_tags',
61
81
  description: 'Read declared scalar PLC tags directly over EtherNet/IP without Studio, FactoryTalk Linx, an ACD upload or the SDK. Explicit controller IPv4 and slot required. Returns timestamped sweeps, quality and controller identity; no writes.',
62
82
  parameters: object({
63
83
  project_id: PROJECT_ID,
64
- ip_address: string('Controller IPv4 address the human named. Example: "192.168.1.10".'),
65
- slot: integer('CPU slot, 0 to 31. Default 0.', { minimum: 0, maximum: 31, default: 0 }),
84
+ ...target,
66
85
  tags: TAGS_PARAM,
67
86
  sample_count: integer('Number of sweeps to read. Default 1.', { minimum: 1, maximum: 1200, default: 1 }),
68
87
  interval_ms: integer('Requested interval between sweeps. Default 200.', { minimum: 50, maximum: 600000, default: 200 }),
@@ -78,7 +97,7 @@ export function liveTools(session, polling, ctx) {
78
97
  }, polling.config);
79
98
  const frames = await polling.start(request, () => { }, exec.signal).done;
80
99
  await session.require(project.id, exec);
81
- return success(`Read ${request.samples} sweep(s) from ${request.ip}.`, {
100
+ return success(`Read ${String(request.samples)} sweep(s) from ${request.ip}.`, {
82
101
  project_id: project.id,
83
102
  source_sha256: project.sha256,
84
103
  ip_address: request.ip,
@@ -95,13 +114,156 @@ export function liveTools(session, polling, ctx) {
95
114
  }, [], LIVE_COVERAGE);
96
115
  },
97
116
  }),
117
+ tool({
118
+ name: 'read_live_tags',
119
+ description: 'Read up to 64 declared scalar tags in ONE EtherNet/IP request (CIP tag group). Faster than polling for a one-shot snapshot; no writes, no Studio, no Linx, no SDK.',
120
+ parameters: object({
121
+ project_id: PROJECT_ID,
122
+ ...target,
123
+ tags: list('Declared scalar tags to read together, 1 to 64. Each entry names the tag and optionally its program.', objectItem('One declared scalar tag.', {
124
+ name: string('Tag name. Example: "LineSpeed".'),
125
+ program: string('Program scope for a program-scoped tag. Omit for a controller tag.'),
126
+ }, ['name']), { minItems: 1, maxItems: 64 }),
127
+ }, ['ip_address', 'tags']),
128
+ async run(args, exec) {
129
+ const project = await session.require(optionalString(args, 'project_id'), exec);
130
+ const { request, evidence } = batchReadRequest(project, {
131
+ ip_address: requiredString(args, 'ip_address'),
132
+ slot: optionalInteger(args, 'slot') ?? 0,
133
+ tags_json: tagsOf(args),
134
+ }, polling.config, extensions.maxBatchTags);
135
+ const result = decodeReadResult(await transactions.run(request, exec.signal));
136
+ await session.require(project.id, exec);
137
+ return success(`Read ${String(result.values.length)} tag(s) from ${request.ip} in one request.`, {
138
+ project_id: project.id,
139
+ source_sha256: project.sha256,
140
+ ip_address: request.ip,
141
+ slot: request.slot,
142
+ provider: 'ethernet-ip',
143
+ request_count: result.request_count,
144
+ controller: result.controller,
145
+ values: result.values,
146
+ evidence,
147
+ live_logic_matches_export: 'unverified',
148
+ }, [], LIVE_COVERAGE);
149
+ },
150
+ }),
151
+ tool({
152
+ name: 'read_controller_clock',
153
+ description: 'Read controller identity and, on L8x controllers, the wall clock beside the workstation clock. Reports unsupported instead of guessing on other models. No writes.',
154
+ parameters: object({ ...target }, ['ip_address']),
155
+ async run(args, exec) {
156
+ const request = { op: 'clock', ...controllerTarget(args, polling.config) };
157
+ const result = decodeClockResult(await transactions.run(request, exec.signal));
158
+ const drift = result.supported && result.controller_time !== undefined
159
+ ? Date.parse(result.host_time) - Date.parse(result.controller_time)
160
+ : undefined;
161
+ return success(result.supported
162
+ ? `Controller clock ${String(result.controller_time)}; workstation ${result.host_time}.`
163
+ : `Controller identity read; wall clock is unavailable on ${result.controller.product_name}.`, {
164
+ ip_address: request.ip,
165
+ slot: request.slot,
166
+ provider: 'ethernet-ip',
167
+ controller: result.controller,
168
+ clock_supported: result.supported,
169
+ ...(result.controller_time === undefined ? {} : { controller_time: result.controller_time }),
170
+ host_time: result.host_time,
171
+ ...(drift === undefined ? {} : { clock_offset_ms: drift }),
172
+ ...(result.reason === undefined ? {} : { reason: result.reason }),
173
+ }, [], LIVE_COVERAGE);
174
+ },
175
+ }),
176
+ tool({
177
+ name: 'discover_controllers',
178
+ description: 'Discover EtherNet/IP controllers on this LAN by UDP broadcast for a bounded window: address, product, revision, serial, status. No address needed, no writes, no Studio or Linx.',
179
+ parameters: object({
180
+ duration_seconds: integer('How long to listen for replies, 1 to 15. Default 3.', { minimum: 1, maximum: 15, default: 3 }),
181
+ }),
182
+ async run(args, exec) {
183
+ const { request } = discoverRequest({ duration_seconds: optionalInteger(args, 'duration_seconds') ?? 3 }, polling.config);
184
+ const result = decodeDiscoverResult(await transactions.run(request, exec.signal, request.duration + 2000));
185
+ return success(`Found ${String(result.devices.length)} controller(s) in ${String(result.seconds)} s.`, {
186
+ provider: 'ethernet-ip',
187
+ broadcast_seconds: result.seconds,
188
+ devices: result.devices,
189
+ limitation: 'Broadcast discovery only reaches devices that answer on this subnet; a routed or filtered network returns nothing.',
190
+ }, [], { complete: false, unverified: ['that a silent device is absent', 'that a listed device is reachable for tag reads'] });
191
+ },
192
+ }),
193
+ tool({
194
+ name: 'write_live_tag',
195
+ description: 'Write ONE declared scalar PLC tag over EtherNet/IP, then read it back and report the controller\'s own value. Requires the row\'s writes switch AND human approval for this exact write. Destructive: it changes a running machine.',
196
+ parameters: object({
197
+ project_id: PROJECT_ID,
198
+ ...target,
199
+ name: string('Declared scalar tag name. Example: "LineSpeed".'),
200
+ program: string('Program scope for a program-scoped tag. Omit for a controller tag.'),
201
+ value: scalar('Value to write: true or false for BOOL, a number for INT, DINT or REAL.'),
202
+ }, ['ip_address', 'name', 'value']),
203
+ async run(args, exec) {
204
+ if (!extensions.allowWrites) {
205
+ throw new L5xError('WRITES_DISABLED', 'Live writes are switched off for this bundle row.', 'Turn on "allowWrites" in the L5X row configuration on the Plugins page, then request the write again.');
206
+ }
207
+ const project = await session.require(optionalString(args, 'project_id'), exec);
208
+ const { request } = writableTagRequest(project, {
209
+ ip_address: requiredString(args, 'ip_address'),
210
+ slot: optionalInteger(args, 'slot') ?? 0,
211
+ name: requiredString(args, 'name'),
212
+ ...(optionalString(args, 'program') === undefined ? {} : { program: optionalString(args, 'program') }),
213
+ value: args.value,
214
+ }, polling.config);
215
+ const address = request.tag.program === undefined
216
+ ? request.tag.name
217
+ : `Program:${String(request.tag.program)}.${String(request.tag.name)}`;
218
+ await requireHumanApproval(ctx, exec, 'write_live_tag', `Write ${JSON.stringify(args.value)} to ${address} on controller ${request.ip} slot ${String(request.slot)}. This changes a running machine.`);
219
+ const result = decodeWriteResult(await transactions.run(request, exec.signal));
220
+ await session.require(project.id, exec);
221
+ if (!result.verified) {
222
+ throw new L5xError('WRITE_NOT_VERIFIED', `${result.tag} was written but the readback is ${JSON.stringify(result.readback)}, not ${JSON.stringify(result.requested_value)}.`, 'Inspect the tag in the controller before retrying; a type or scaling mismatch can reject the value.');
223
+ }
224
+ return success(`Wrote ${JSON.stringify(result.requested_value)} to ${result.tag}; the controller reads back ${JSON.stringify(result.readback)}.`, {
225
+ project_id: project.id,
226
+ source_sha256: project.sha256,
227
+ ip_address: request.ip,
228
+ slot: request.slot,
229
+ provider: 'ethernet-ip',
230
+ approved: 'allowed-once',
231
+ ...result,
232
+ live_logic_matches_export: 'unverified',
233
+ }, [], WRITE_COVERAGE);
234
+ },
235
+ }),
236
+ tool({
237
+ name: 'write_controller_clock',
238
+ description: 'Set the controller wall clock (L8x only), then read it back. Requires the row\'s writes switch AND human approval for this exact change.',
239
+ parameters: object({
240
+ ...target,
241
+ time: string('ISO 8601 timestamp to set. Omit to use the workstation clock now. Example: "2026-10-25T09:30:00Z".'),
242
+ }, ['ip_address']),
243
+ async run(args, exec) {
244
+ if (!extensions.allowWrites) {
245
+ throw new L5xError('WRITES_DISABLED', 'Live writes are switched off for this bundle row.', 'Turn on "allowWrites" in the L5X row configuration on the Plugins page, then request the change again.');
246
+ }
247
+ const request = { op: 'write-clock', ...controllerTarget(args, polling.config), iso: optionalString(args, 'time') ?? new Date().toISOString() };
248
+ await requireHumanApproval(ctx, exec, 'write_controller_clock', `Set the wall clock of controller ${request.ip} slot ${String(request.slot)} to ${String(request.iso)}.`);
249
+ const result = decodeWriteClockResult(await transactions.run(request, exec.signal));
250
+ if (!result.verified) {
251
+ throw new L5xError('WRITE_NOT_VERIFIED', `The clock readback ${result.readback} does not match ${result.requested_time}.`, 'Retry once; if it still differs, the controller rejects clock changes (unsupported model or protected).');
252
+ }
253
+ return success(`Controller clock set to ${result.readback}.`, {
254
+ ip_address: request.ip,
255
+ slot: request.slot,
256
+ approved: 'allowed-once',
257
+ ...result,
258
+ }, [], WRITE_COVERAGE);
259
+ },
260
+ }),
98
261
  tool({
99
262
  name: 'start_plc_trend',
100
263
  description: 'Start a bounded, read-only PLC trend as a session-owned background job. Explicit IPv4, slot and declared scalar tags required. SDK-independent EtherNet/IP; the chart follows the job without a model call per sample.',
101
264
  parameters: object({
102
265
  project_id: PROJECT_ID,
103
- ip_address: string('Controller IPv4 address the human named. Example: "192.168.1.10".'),
104
- slot: integer('CPU slot, 0 to 31. Default 0.', { minimum: 0, maximum: 31, default: 0 }),
266
+ ...target,
105
267
  tags: TAGS_PARAM,
106
268
  sample_count: integer('Number of sweeps in the trend. Default 300.', { minimum: 1, maximum: 1200, default: 300 }),
107
269
  interval_ms: integer('Requested interval between sweeps. Default 200.', { minimum: 50, maximum: 600000, default: 200 }),
@@ -123,7 +285,7 @@ export function liveTools(session, polling, ctx) {
123
285
  const jobId = jobs.start({
124
286
  kind: 'plc-trend',
125
287
  owner,
126
- label: `PLC trend ${request.ip} slot ${request.slot}`,
288
+ label: `PLC trend ${request.ip} slot ${String(request.slot)}`,
127
289
  run(job) {
128
290
  job.append(JSON.stringify({
129
291
  type: 'source',
@@ -157,7 +319,7 @@ export function liveTools(session, polling, ctx) {
157
319
  return { cancel: handle.cancel, done };
158
320
  },
159
321
  });
160
- return success(`Trend ${jobId} started for ${request.samples} sweep(s) from ${request.ip}.`, {
322
+ return success(`Trend ${jobId} started for ${String(request.samples)} sweep(s) from ${request.ip}.`, {
161
323
  job_id: jobId,
162
324
  owner_session_id: owner,
163
325
  project_id: project.id,