@zalosai/zalos-cli 0.2.20 → 0.2.22

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/PUBLISHING.md CHANGED
@@ -59,6 +59,17 @@ Do not publish with uncommitted package changes or reuse an existing version.
59
59
 
60
60
  ## Central developer access release
61
61
 
62
+ Version 0.2.22 adds `workflow activate` and `workflow schedule
63
+ list/upsert/remove/preview/run`. Deploy the schedule-preview API and scoped-token
64
+ route grants before publishing. Schedule tests use the CLI caller, not the
65
+ scheduler bot; saving task edits, publication and activation remain separate.
66
+
67
+ Version 0.2.21 adds `workflow view --published` and `workflow export --published`
68
+ for reading client-facing workflow definitions through the existing API. These
69
+ reads omit draft update checksums and reject protected workflows that resolve to
70
+ an unpublished version. Team-scoped `export --all --published` is supported;
71
+ cross-team `--all-teams --published` is not.
72
+
62
73
  Version 0.2.20 adds `zl workflow eval` for evaluation suites, cases, results,
63
74
  incidents, evidence, captured-execution scoring, case launches and thread
64
75
  consolidation. Writes preview by default and require `--apply`. Deploy the
package/README.md CHANGED
@@ -144,6 +144,38 @@ Workflow import/update/publish require `--apply`; without it they validate and p
144
144
  from the signed-in human's team membership, role, and token scopes. Credential reads
145
145
  return metadata only. No product command loads database credentials.
146
146
 
147
+ ### Scheduled chat tasks
148
+
149
+ Workers are workflows with one Chat Trigger. Manage their existing scheduled tasks
150
+ without exporting or replacing the full workflow graph:
151
+
152
+ ```bash
153
+ zl --environment staging workflow schedule list <id> --published
154
+ zl --environment staging workflow schedule upsert <id> --input task.json
155
+ zl --environment staging workflow schedule upsert <id> --input task.json --apply
156
+ zl --environment staging workflow schedule preview <id> <task-id> --count 3
157
+ zl --environment staging workflow publish <id> --apply
158
+ zl --environment staging workflow activate <id> --apply
159
+ zl --environment staging workflow schedule remove <id> <task-id> --apply
160
+ zl --environment staging workflow deactivate <id> --apply
161
+ ```
162
+
163
+ `task.json` contains one existing `scheduledChatTasks` entry, including its stable
164
+ `id`, `name`, `enabled`, `targetChatNodeId`, version-2 `schedule`, `openingRequest`,
165
+ and `inputs` bindings. Upsert and remove preserve other tasks/settings and use the
166
+ current workflow checksum. The API reuses the scheduler compiler and chat input
167
+ validation. Protected workflow edits require publication; activation is separate.
168
+ Deactivation pauses schedules without stopping existing chats.
169
+
170
+ Use `preview --published --at 2027-01-01T09:00:00Z` to evaluate inputs at an exact
171
+ occurrence; without `--at`, previews start at the next fire time. `--count` is 1–10.
172
+ `workflow schedule run <id> <task-id>` previews a manual test using published task
173
+ inputs evaluated at the current time (or `--at`). Add `--apply` to start it through
174
+ the normal workflow execution API. This runs as the CLI caller, **not the scheduler
175
+ bot**; it does not prove scheduled-identity access. Disabled tasks can be tested
176
+ without enabling them. No schedule command publishes, activates, or executes as a
177
+ side effect of editing. Unlike `workflow run`, schedule test runs require `--apply`.
178
+
147
179
  ### Workflow evaluations
148
180
 
149
181
  Evaluation commands use the selected environment and profile's team. They require
@@ -196,6 +228,20 @@ whether runs use that version and names the live version when they do not. Use
196
228
  keeps stdout as reusable workflow JSON and writes a structured stderr warning when the
197
229
  exported draft differs from the version used by runs.
198
230
 
231
+ Use `workflow view <id> --published` or `workflow export <id> --published` to read
232
+ the definition clients run, without publishing or changing the draft:
233
+
234
+ ```bash
235
+ zl --environment us-prod workflow export <workflow-id> --published --pretty --output /tmp/published.json
236
+ zl --environment us-prod workflow export --all --published --output /tmp/team-live-workflows.json
237
+ ```
238
+
239
+ Protected workflows return their published content; unprotected workflows return
240
+ their current definition. A protected workflow that falls back to a draft is
241
+ rejected. Published reads omit update checksums: export the current draft before
242
+ editing it. `--published` cannot be combined with `--all-teams`; select the owning
243
+ team and use an ID or `--all`.
244
+
199
245
  `workflow list --all-teams` and `workflow export --all-teams` read every workflow in
200
246
  the selected regional database. They require an internal Zalos human CLI token with
201
247
  `workflows:read`; external users and automation tokens are rejected. `workflow export --all`
@@ -0,0 +1,197 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { client } from '../client.js';
3
+ import { ApiError, ValidationError } from '../utils/errors.js';
4
+ import { printJson } from '../utils/output.js';
5
+ import { action, dataRow, integer, isRow, resourceId } from '../utils/product-api.js';
6
+ import { parseJson } from '../utils/validate.js';
7
+ import { parseWorkflowFile } from '../workflow-file.js';
8
+ function path(id) {
9
+ return `/workflows/${resourceId(id)}`;
10
+ }
11
+ function taskId(id) {
12
+ if (id.length > 100)
13
+ throw new ValidationError('taskId', 'Task IDs must be 1–100 characters');
14
+ return resourceId(id);
15
+ }
16
+ function tasksFrom(workflow) {
17
+ const settings = workflow.settings;
18
+ if (settings !== undefined && !isRow(settings))
19
+ throw new ApiError(502, 'Invalid workflow settings');
20
+ const tasks = settings?.scheduledChatTasks ?? [];
21
+ if (!Array.isArray(tasks) || !tasks.every(isRow))
22
+ throw new ApiError(502, 'Invalid scheduled chat tasks');
23
+ return tasks;
24
+ }
25
+ async function preview(id, body) {
26
+ const result = dataRow(await client.post(`${path(id)}/schedule-preview`, body));
27
+ if (body.published && result.publishedVersionId && result.versionId !== result.publishedVersionId)
28
+ throw new ApiError(502, 'API did not resolve the published workflow; refusing draft fallback');
29
+ return result;
30
+ }
31
+ function previewBody(options) {
32
+ if (options.at !== undefined &&
33
+ (!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(options.at) ||
34
+ !Number.isFinite(Date.parse(options.at))))
35
+ throw new ValidationError('at', 'Use an ISO timestamp with an explicit timezone');
36
+ return {
37
+ published: options.published ?? false,
38
+ count: integer(options.count, 3, 1, 10),
39
+ ...(options.at ? { at: options.at } : {}),
40
+ };
41
+ }
42
+ export async function listWorkflowSchedulesAction(id, options) {
43
+ const workflow = dataRow(await client.get(`${path(id)}${options.published ? '?resolvePublished=true' : ''}`));
44
+ if (options.published &&
45
+ workflow.publishedVersionId &&
46
+ workflow.versionId !== workflow.publishedVersionId)
47
+ throw new ApiError(502, 'API did not resolve the published workflow');
48
+ printJson({
49
+ workflowId: id,
50
+ active: workflow.active,
51
+ versionId: workflow.versionId,
52
+ publishedVersionId: workflow.publishedVersionId,
53
+ tasks: tasksFrom(workflow),
54
+ });
55
+ }
56
+ export async function previewWorkflowScheduleAction(id, selected, options) {
57
+ printJson(await preview(id, { ...previewBody(options), taskId: taskId(selected) }));
58
+ }
59
+ export async function editWorkflowScheduleAction(id, options) {
60
+ const endpoint = path(id);
61
+ let task;
62
+ if (options.input) {
63
+ const value = parseJson(await readFile(options.input, 'utf8'));
64
+ if (!isRow(value) || typeof value.id !== 'string')
65
+ throw new ValidationError('input', 'Provide one scheduled chat task with an id');
66
+ taskId(value.id);
67
+ task = value;
68
+ }
69
+ else if (options.remove)
70
+ taskId(options.remove);
71
+ else
72
+ throw new ValidationError('input', 'Provide a task file or a task ID to remove');
73
+ const workflow = dataRow(await client.get(endpoint));
74
+ // PUT is a full workflow replacement, not a settings patch. Validate the
75
+ // response graph and carry forward all editable fields before changing tasks.
76
+ parseWorkflowFile(JSON.stringify(workflow), id);
77
+ if (typeof workflow.checksum !== 'string' || !workflow.checksum.trim())
78
+ throw new ApiError(502, 'Workflow update checksum unavailable; refresh the API before editing');
79
+ const existing = tasksFrom(workflow);
80
+ const selected = task?.id ?? options.remove;
81
+ const index = existing.findIndex((entry) => entry.id === selected);
82
+ if (!task && index < 0)
83
+ throw new ValidationError('taskId', 'Scheduled chat task not found');
84
+ const tasks = existing.filter((entry) => entry.id !== selected);
85
+ if (task)
86
+ tasks.splice(index < 0 ? tasks.length : index, 0, task);
87
+ // The server reuses the scheduler compiler, expression evaluator and chat input validator.
88
+ await preview(id, { tasks, count: 1 });
89
+ const content = Object.fromEntries([
90
+ 'name',
91
+ 'description',
92
+ 'nodes',
93
+ 'connections',
94
+ 'parentFolderId',
95
+ 'pinData',
96
+ 'timeSavedPerExecution',
97
+ 'timeSavedPerMonth',
98
+ ]
99
+ .filter((key) => Object.hasOwn(workflow, key))
100
+ .map((key) => [key, workflow[key]]));
101
+ const payload = {
102
+ ...content,
103
+ settings: {
104
+ ...workflow.settings,
105
+ scheduledChatTasks: tasks,
106
+ },
107
+ expectedChecksum: workflow.checksum,
108
+ };
109
+ if (!options.apply || options.dryRun) {
110
+ printJson({ dryRun: true, method: 'PUT', path: endpoint, payload });
111
+ return;
112
+ }
113
+ const saved = dataRow(await client.put(endpoint, payload));
114
+ printJson({
115
+ workflowId: saved.id,
116
+ versionId: saved.versionId,
117
+ publishedVersionId: saved.publishedVersionId,
118
+ message: saved.publishedVersionId
119
+ ? 'Saved schedule draft. Publish to update scheduled runs; activation is separate.'
120
+ : 'Saved current schedule settings on an unprotected workflow; activation is separate.',
121
+ });
122
+ }
123
+ export async function runWorkflowScheduleAction(id, selected, options) {
124
+ const result = await preview(id, {
125
+ ...previewBody({
126
+ published: true,
127
+ at: options.at ?? new Date().toISOString(),
128
+ count: '1',
129
+ }),
130
+ taskId: taskId(selected),
131
+ });
132
+ const previews = result.previews;
133
+ const first = Array.isArray(previews) && isRow(previews[0]) ? previews[0] : undefined;
134
+ const occurrences = first?.occurrences;
135
+ const occurrence = Array.isArray(occurrences) && isRow(occurrences[0]) ? occurrences[0] : undefined;
136
+ if (!occurrence || !isRow(occurrence.triggerData) || typeof first?.startNodeName !== 'string')
137
+ throw new ApiError(502, 'Schedule preview did not return evaluated inputs');
138
+ const endpoint = `${path(id)}/run`;
139
+ const payload = {
140
+ triggerData: occurrence.triggerData,
141
+ triggerSource: 'chat',
142
+ startNodeName: first.startNodeName,
143
+ };
144
+ const identity = 'CLI caller (manual test), not the scheduled bot';
145
+ if (!options.apply || options.dryRun) {
146
+ printJson({
147
+ dryRun: true,
148
+ method: 'POST',
149
+ path: endpoint,
150
+ payload,
151
+ identity,
152
+ versionId: result.versionId,
153
+ scheduledFor: occurrence.scheduledFor,
154
+ });
155
+ return;
156
+ }
157
+ // Use the existing launch endpoint and its execution permissions; never impersonate a bot.
158
+ printJson({
159
+ ...dataRow(await client.post(endpoint, payload)),
160
+ identity,
161
+ scheduledFor: occurrence.scheduledFor,
162
+ });
163
+ }
164
+ export function registerWorkflowScheduleCommand(workflow) {
165
+ const cmd = workflow
166
+ .command('schedule')
167
+ .description('Manage workflow-owned scheduled chat tasks');
168
+ cmd
169
+ .command('list <id>')
170
+ .option('--published', 'Read published tasks')
171
+ .action(async (id, o) => action(() => listWorkflowSchedulesAction(id, o)));
172
+ cmd
173
+ .command('upsert <id>')
174
+ .requiredOption('--input <file>', 'One scheduled chat task as JSON')
175
+ .option('--apply', 'Save schedule draft')
176
+ .option('--dry-run', 'Validate and preview only')
177
+ .action(async (id, o) => action(() => editWorkflowScheduleAction(id, o)));
178
+ cmd
179
+ .command('remove <id> <task-id>')
180
+ .option('--apply', 'Remove task from draft')
181
+ .option('--dry-run', 'Preview removal')
182
+ .action(async (id, selected, o) => action(() => editWorkflowScheduleAction(id, { ...o, remove: selected })));
183
+ cmd
184
+ .command('preview <id> <task-id>')
185
+ .option('--published', 'Preview published tasks')
186
+ .option('--at <timestamp>', 'Evaluate first occurrence at this ISO timestamp; otherwise use next fire time')
187
+ .option('--count <n>', 'Number of occurrences (1–10)', '3')
188
+ .action(async (id, selected, o) => action(() => previewWorkflowScheduleAction(id, selected, o)));
189
+ cmd
190
+ .command('run <id> <task-id>')
191
+ .description('Test published task inputs as the CLI caller; does not test scheduler bot identity')
192
+ .option('--at <timestamp>', 'Evaluate inputs at this ISO timestamp (default now)')
193
+ .option('--apply', 'Start a real execution')
194
+ .option('--dry-run', 'Preview evaluated inputs only')
195
+ .action(async (id, selected, o) => action(() => runWorkflowScheduleAction(id, selected, o)));
196
+ }
197
+ //# sourceMappingURL=workflow-schedule.js.map
@@ -2,11 +2,24 @@ import { writeFile, stat } from 'node:fs/promises';
2
2
  import { resolve, join } from 'node:path';
3
3
  import { client } from '../client.js';
4
4
  import { readWorkflowFile, serializeWorkflow } from '../workflow-file.js';
5
- import { ValidationError } from '../utils/errors.js';
5
+ import { ApiError, ValidationError } from '../utils/errors.js';
6
6
  import { filterSingle, printJson } from '../utils/output.js';
7
7
  import { action, dataRow, dataRows, fields, isRow, printPage, resourceId, } from '../utils/product-api.js';
8
8
  import { parseJson } from '../utils/validate.js';
9
+ import { registerWorkflowScheduleCommand } from './workflow-schedule.js';
9
10
  import { registerWorkflowEvalCommand } from './workflow-eval.js';
11
+ async function readWorkflow(id, options) {
12
+ const workflow = dataRow(await client.get(`/workflows/${resourceId(id)}${options.published ? '?resolvePublished=true' : ''}`));
13
+ if (!options.published)
14
+ return workflow;
15
+ if (workflow.publishedVersionId && workflow.versionId !== workflow.publishedVersionId) {
16
+ throw new ApiError(502, 'The API did not resolve the published workflow version; refusing to export a draft');
17
+ }
18
+ // The client-facing API retains the current draft's checksum when resolving
19
+ // published content. Never let that token authorize an update with old content.
20
+ const { checksum: _checksum, expectedChecksum: _expectedChecksum, ...snapshot } = workflow;
21
+ return snapshot;
22
+ }
10
23
  function publicationStatus(workflow, publishedNow = false) {
11
24
  const draftVersionId = typeof workflow.versionId === 'string' ? workflow.versionId : undefined;
12
25
  const publishedVersionId = typeof workflow.publishedVersionId === 'string' ? workflow.publishedVersionId : undefined;
@@ -48,12 +61,14 @@ export async function listWorkflowsAction(options) {
48
61
  printPage(dataRows(await client.get(path)), options);
49
62
  }
50
63
  export async function viewWorkflowAction(id, options) {
51
- printJson(filterSingle(dataRow(await client.get(`/workflows/${resourceId(id)}`)), options.fields));
64
+ printJson(filterSingle(await readWorkflow(id, options), options.fields));
52
65
  }
53
66
  export async function exportWorkflowAction(id, options) {
54
67
  const selections = [Boolean(id), Boolean(options.all), Boolean(options.allTeams)].filter(Boolean).length;
55
68
  if (selections !== 1)
56
69
  throw new ValidationError('id', 'Choose a workflow ID, --all, or --all-teams');
70
+ if (options.published && options.allTeams)
71
+ throw new ValidationError('published', '--published cannot be combined with --all-teams; select the owning team and use an ID or --all');
57
72
  if (id)
58
73
  resourceId(id);
59
74
  const output = options.output ? resolve(options.output) : undefined;
@@ -80,7 +95,7 @@ export async function exportWorkflowAction(id, options) {
80
95
  });
81
96
  rows = [];
82
97
  for (const workflowId of ids)
83
- rows.push(filterSingle(dataRow(await client.get(`/workflows/${workflowId}`)), options.fields));
98
+ rows.push(filterSingle(await readWorkflow(workflowId, options), options.fields));
84
99
  }
85
100
  rows.forEach(warnIfWorkflowDraftIsUnpublished);
86
101
  if (options.separate && output) {
@@ -159,6 +174,14 @@ export async function publishWorkflowAction(id, options) {
159
174
  const published = dataRow(await client.post(path));
160
175
  printJson({ workflow: published, publication: publicationStatus(published, true) });
161
176
  }
177
+ export async function activateWorkflowAction(id, options) {
178
+ const path = `/workflows/${resourceId(id)}/activate`;
179
+ if (!options.apply || options.dryRun) {
180
+ printJson({ dryRun: true, method: 'PATCH', path });
181
+ return;
182
+ }
183
+ printJson(dataRow(await client.patch(path, {})));
184
+ }
162
185
  export async function deactivateWorkflowAction(id, options) {
163
186
  const path = `/workflows/${resourceId(id)}/deactivate`;
164
187
  if (!options.apply || options.dryRun) {
@@ -192,6 +215,7 @@ export async function runWorkflowAction(id, options) {
192
215
  export function registerWorkflowCommand(program) {
193
216
  const cmd = program.command('workflow').description('Manage workflows through the regional API');
194
217
  registerWorkflowEvalCommand(cmd, program);
218
+ registerWorkflowScheduleCommand(cmd);
195
219
  cmd
196
220
  .command('list')
197
221
  .option('--all-teams', 'List workflows across every team in the selected region')
@@ -200,11 +224,13 @@ export function registerWorkflowCommand(program) {
200
224
  .action(async (o) => action(() => listWorkflowsAction({ ...o, ...fields(program) })));
201
225
  cmd
202
226
  .command('view <id>')
203
- .action(async (id) => action(() => viewWorkflowAction(id, fields(program))));
227
+ .option('--published', 'Read the definition clients run (current when unprotected)')
228
+ .action(async (id, o) => action(() => viewWorkflowAction(id, { ...o, ...fields(program) })));
204
229
  cmd
205
230
  .command('export [id]')
206
231
  .option('--all', 'Export every accessible workflow')
207
232
  .option('--all-teams', 'Export workflows across every team in the selected region')
233
+ .option('--published', 'Export the definition clients run (current when unprotected); omits update checksum')
208
234
  .option('--output <path>', 'Output file (must not exist)')
209
235
  .option('--pretty', 'Indent JSON')
210
236
  .option('--separate', 'Write ID-named JSON in output directory')
@@ -228,6 +254,11 @@ export function registerWorkflowCommand(program) {
228
254
  .option('--apply', 'Publish workflow')
229
255
  .option('--dry-run', 'Preview publish')
230
256
  .action(async (id, o) => action(() => publishWorkflowAction(id, o)));
257
+ cmd
258
+ .command('activate <id>')
259
+ .option('--apply', 'Activate published workflow schedules')
260
+ .option('--dry-run', 'Preview activation')
261
+ .action(async (id, o) => action(() => activateWorkflowAction(id, o)));
231
262
  cmd
232
263
  .command('deactivate <id>')
233
264
  .option('--apply', 'Deactivate workflow')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.20",
3
+ "version": "0.2.22",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",