@zalosai/zalos-cli 0.2.35 → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -139,6 +139,9 @@ zl page create --input /tmp/month-end-close.md --apply
139
139
  zl page update <page-id> --input /tmp/month-end-close.md --apply
140
140
  zl workflow run <id> --dry-run
141
141
  zl workflow run <id>
142
+ zl workflow run <id> --json '{"period":"2026-11"}' --file bankReport=./jpm.xlsx
143
+ zl execution respond <execution-id> --dry-run
144
+ zl execution respond <execution-id> --json '{"approved":true}' --file ./reviewed.xlsx
142
145
  zl template list
143
146
  zl credential list
144
147
  zl file list
@@ -163,7 +166,10 @@ zl close registry import-baseline --team-id <team-ref> --expected-version <versi
163
166
  ```
164
167
 
165
168
  Workflow import/update/publish require `--apply`; without it they validate and print a preview.
166
- `workflow run` executes unless `--dry-run` is supplied. Product authorization comes
169
+ `workflow run --file <field>=<path>` uploads a local file to Team Files and passes it to that form
170
+ file field, exactly like choosing a Team File in the web form. `execution respond` completes the
171
+ form step a run is waiting on (review/wait nodes), with optional `--file` uploads; `--dry-run` shows
172
+ the fields it expects. `workflow run` executes unless `--dry-run` is supplied. Product authorization comes
167
173
  from the signed-in human's team membership, role, and token scopes. Credential reads
168
174
  return metadata only. No product command loads database credentials.
169
175
 
package/dist/client.js CHANGED
@@ -61,6 +61,10 @@ async function request(options, tokenOverride) {
61
61
  }
62
62
  throw new AuthError('Unauthorized. Check your API token.');
63
63
  }
64
+ if (options.textResponse && !response.ok) {
65
+ const message = (await response.text()).trim().slice(0, 500);
66
+ throw new ApiError(response.status, message || response.statusText);
67
+ }
64
68
  if (response.status === 404) {
65
69
  throw new NotFoundError('resource', path);
66
70
  }
@@ -70,6 +74,8 @@ async function request(options, tokenOverride) {
70
74
  }
71
75
  if (response.status === 204)
72
76
  return undefined;
77
+ if (options.textResponse)
78
+ return (await response.text());
73
79
  if (options.binaryResponse) {
74
80
  return {
75
81
  body: Buffer.from(await response.arrayBuffer()),
@@ -82,6 +88,7 @@ export const client = {
82
88
  get: (path, query) => request({ method: 'GET', path, query }),
83
89
  post: (path, body, options) => request({ method: 'POST', path, body, ...options }),
84
90
  postForm: (path, body, options) => request({ method: 'POST', path, body, ...options }),
91
+ postFormText: (path, body, options) => request({ method: 'POST', path, body, textResponse: true, ...options }),
85
92
  postBinary: (path, body, options) => request({ method: 'POST', path, body, ...options }),
86
93
  /** POST a binary body and return the raw response, e.g. a streamed NDJSON result. */
87
94
  postBinaryRaw: (path, body, options) => request({ method: 'POST', path, body, binaryResponse: true, ...options }),
@@ -7,6 +7,8 @@ import { currentEnvironment } from '../environments.js';
7
7
  import { downloadToNewFile } from '../utils/download-file.js';
8
8
  import { ApiError, ValidationError } from '../utils/errors.js';
9
9
  import { filterFields, filterSingle, printJson } from '../utils/output.js';
10
+ import { parseJson } from '../utils/validate.js';
11
+ import { readLocalUploadFile, UPLOAD_TIMEOUT_MS } from './file.js';
10
12
  import { action, dataRow, fields, integer, isRow, resourceId, } from '../utils/product-api.js';
11
13
  function isReplayBundleArtifact(value) {
12
14
  if (!isRow(value))
@@ -198,6 +200,93 @@ export async function listExecutionsAction(options) {
198
200
  export async function viewExecutionAction(id, options, summary = false) {
199
201
  printJson(filterSingle(dataRow(await client.get(`/executions/${resourceId(id)}${summary ? '/summary' : ''}`)), options.fields));
200
202
  }
203
+ // Mirrors the server's wait-form multer limits (routes.ts WAIT_FORM_UPLOAD_MAX_BYTES).
204
+ const WAIT_FORM_MAX_FILE_BYTES = 100 * 1024 * 1024;
205
+ const WAIT_FORM_MAX_FILES = 10;
206
+ function waitFormTarget(submitUrl) {
207
+ if (typeof submitUrl !== 'string')
208
+ throw new ApiError(502, 'Waiting form has no submit URL');
209
+ const url = new URL(submitUrl, 'http://zl.invalid');
210
+ const match = /^\/api\/executions\/([^/]+)\/wait-form$/.exec(url.pathname);
211
+ const token = url.searchParams.get('token');
212
+ if (!match || !token)
213
+ throw new ApiError(502, 'Unexpected waiting form submit URL');
214
+ return { executionId: decodeURIComponent(match[1]), token };
215
+ }
216
+ /**
217
+ * Completes a paused form step (wait/review node), uploading local files the same
218
+ * way the web form does. The resume token stays in memory and is never printed.
219
+ */
220
+ export async function respondToExecutionFormAction(id, options) {
221
+ const executionId = resourceId(id);
222
+ const values = parseJson(options.json ?? '{}');
223
+ if (!isRow(values))
224
+ throw new ValidationError('json', 'Form values must be an object');
225
+ const response = await client.get(`/executions/${executionId}/wait-form-config`);
226
+ const config = isRow(response) && isRow(response.data) ? response.data : response;
227
+ if (!isRow(config))
228
+ throw new ApiError(502, 'Invalid waiting form response');
229
+ const target = waitFormTarget(config.submitUrl);
230
+ const files = options.file ?? [];
231
+ const fileField = typeof config.fileUploadFieldName === 'string' && config.fileUploadFieldName
232
+ ? config.fileUploadFieldName
233
+ : 'uploadedFiles';
234
+ const problems = [];
235
+ if (files.length > 0 && config.allowFileUpload !== true)
236
+ problems.push('This form step does not accept file uploads');
237
+ if (files.length === 0 && config.fileUploadRequired === true)
238
+ problems.push('This form step requires a file: pass --file <path>');
239
+ // A dry run is how users discover what the form needs, so report problems instead.
240
+ if (problems.length > 0 && !options.dryRun)
241
+ throw new ValidationError('file', problems[0]);
242
+ if (files.length > WAIT_FORM_MAX_FILES)
243
+ throw new ValidationError('file', `A form step accepts at most ${WAIT_FORM_MAX_FILES} files`);
244
+ const uploads = [];
245
+ for (const path of files)
246
+ uploads.push(await readLocalUploadFile(path, undefined, {
247
+ bytes: WAIT_FORM_MAX_FILE_BYTES,
248
+ label: 'the 100 MiB form upload limit',
249
+ }));
250
+ const summary = {
251
+ executionId: target.executionId,
252
+ waitNodeName: config.waitNodeName ?? null,
253
+ formTitle: config.formTitle ?? null,
254
+ formFields: config.formFields ?? [],
255
+ allowFileUpload: config.allowFileUpload === true,
256
+ fileUploadRequired: config.fileUploadRequired === true,
257
+ ...(config.allowFileUpload === true ? { fileUploadFieldName: fileField } : {}),
258
+ };
259
+ if (options.dryRun) {
260
+ printJson({
261
+ dryRun: true,
262
+ form: summary,
263
+ values,
264
+ files: uploads.map((upload) => ({ name: upload.name, size: upload.size })),
265
+ ...(problems.length > 0 ? { problems } : {}),
266
+ });
267
+ return;
268
+ }
269
+ const form = new FormData();
270
+ for (const [key, value] of Object.entries(values)) {
271
+ if (key === fileField || value === null || value === undefined)
272
+ continue;
273
+ const items = Array.isArray(value) ? value : [value];
274
+ for (const item of items)
275
+ form.append(key, typeof item === 'object' ? JSON.stringify(item) : String(item));
276
+ }
277
+ for (const upload of uploads)
278
+ form.append(fileField, upload.file, upload.name);
279
+ await client.postFormText(`/executions/${encodeURIComponent(target.executionId)}/wait-form`, form, {
280
+ query: { token: target.token },
281
+ timeoutMs: UPLOAD_TIMEOUT_MS,
282
+ });
283
+ printJson({
284
+ executionId: target.executionId,
285
+ waitNodeName: summary.waitNodeName,
286
+ submitted: true,
287
+ files: uploads.length,
288
+ });
289
+ }
201
290
  export async function stopExecutionAction(id) {
202
291
  const executionId = resourceId(id);
203
292
  const result = await client.post(`/executions/${executionId}/stop`);
@@ -218,6 +307,13 @@ export function registerExecutionCommand(program) {
218
307
  cmd
219
308
  .command(`${verb} <id>`)
220
309
  .action(async (id) => action(() => viewExecutionAction(id, fields(program), verb === 'summary')));
310
+ cmd
311
+ .command('respond <execution-id>')
312
+ .description('Complete the form step an execution is waiting on; --dry-run shows the fields it expects')
313
+ .option('--json <values>', 'Form values as JSON')
314
+ .option('--file <path>', 'Upload a local file with the response (repeatable)', (value, previous) => [...previous, value], [])
315
+ .option('--dry-run', 'Show the waiting form and planned response without submitting')
316
+ .action(async (id, options) => action(() => respondToExecutionFormAction(id, options)));
221
317
  cmd
222
318
  .command('stop <execution-id>')
223
319
  .description('Stop a running execution and its downstream work')
@@ -12,7 +12,7 @@ const FOLDER_FIELDS = 'id,name,parentFolderId,createdAt,updatedAt';
12
12
  // Team Files folders live in the `files` folder scope; workflow folders use `workflows`.
13
13
  const FILES_FOLDER_SCOPE = 'files';
14
14
  const MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024;
15
- const UPLOAD_TIMEOUT_MS = 15 * 60_000;
15
+ export const UPLOAD_TIMEOUT_MS = 15 * 60_000;
16
16
  const MIME_TYPES = {
17
17
  '.csv': 'text/csv',
18
18
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
@@ -94,9 +94,12 @@ export async function downloadFileAction(idOrPath, options) {
94
94
  allowDataUrl: options.allowDataUrl,
95
95
  }));
96
96
  }
97
- export async function uploadFileAction(localPath, options) {
98
- const folderId = options.folderId ? resourceId(options.folderId) : 'root';
99
- const mimeType = options.mimeType ?? MIME_TYPES[extname(localPath).toLowerCase()] ?? 'application/octet-stream';
97
+ /** Validates a local file against the Team Files limits and opens it for multipart upload. */
98
+ export async function readLocalUploadFile(localPath, mimeTypeOverride, limit = {
99
+ bytes: MAX_FILE_SIZE_BYTES,
100
+ label: 'the 500 MiB Team Files limit',
101
+ }) {
102
+ const mimeType = mimeTypeOverride ?? MIME_TYPES[extname(localPath).toLowerCase()] ?? 'application/octet-stream';
100
103
  if (!/^[\w.+-]+\/[\w.+-]+$/.test(mimeType)) {
101
104
  throw new ValidationError('mimeType', 'Invalid MIME type');
102
105
  }
@@ -109,21 +112,31 @@ export async function uploadFileAction(localPath, options) {
109
112
  }
110
113
  if (!fileStat.isFile())
111
114
  throw new ValidationError('file', 'Local path must be a regular file');
112
- if (fileStat.size > MAX_FILE_SIZE_BYTES) {
113
- throw new ValidationError('file', 'File exceeds the 500 MiB Team Files limit');
115
+ if (fileStat.size > limit.bytes) {
116
+ throw new ValidationError('file', `${basename(localPath)} exceeds ${limit.label}`);
114
117
  }
115
- let file;
116
118
  try {
117
- file = await openAsBlob(localPath, { type: mimeType });
119
+ return {
120
+ file: await openAsBlob(localPath, { type: mimeType }),
121
+ name: basename(localPath),
122
+ size: fileStat.size,
123
+ };
118
124
  }
119
125
  catch {
120
126
  throw new ValidationError('file', `Unable to read local file: ${localPath}`);
121
127
  }
128
+ }
129
+ export async function uploadLocalTeamFile(localPath, options) {
130
+ const folderId = options.folderId ? resourceId(options.folderId) : 'root';
131
+ const upload = await readLocalUploadFile(localPath, options.mimeType);
122
132
  const form = new FormData();
123
133
  form.append('folderId', folderId);
124
134
  form.append('collisionStrategy', options.overwrite ? 'overwrite' : 'create_unique_name');
125
- form.append('file', file, basename(localPath));
126
- printJson(dataRow(await client.postForm('/team-files/upload', form, { timeoutMs: UPLOAD_TIMEOUT_MS })));
135
+ form.append('file', upload.file, upload.name);
136
+ return dataRow(await client.postForm('/team-files/upload', form, { timeoutMs: UPLOAD_TIMEOUT_MS }));
137
+ }
138
+ export async function uploadFileAction(localPath, options) {
139
+ printJson(await uploadLocalTeamFile(localPath, options));
127
140
  }
128
141
  export async function listFoldersAction(options) {
129
142
  const parentFolderId = options.parentFolderId ? resourceId(options.parentFolderId) : 'root';
@@ -2,10 +2,11 @@ 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 { parseWorkflowFile, readWorkflowFile, serializeWorkflow } from '../workflow-file.js';
5
- import { ApiError, ValidationError } from '../utils/errors.js';
5
+ import { ApiError, NotFoundError, 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 { readLocalUploadFile, uploadLocalTeamFile } from './file.js';
9
10
  import { registerWorkflowScheduleCommand } from './workflow-schedule.js';
10
11
  import { registerWorkflowEvalCommand } from './workflow-eval.js';
11
12
  async function readWorkflow(id, options) {
@@ -217,17 +218,119 @@ export async function deleteWorkflowAction(id, options) {
217
218
  await client.delete(path);
218
219
  printJson({ deleted: true, workflowId });
219
220
  }
221
+ function parseFileInputs(entries) {
222
+ const seen = new Set();
223
+ return entries.map((entry) => {
224
+ const separator = entry.indexOf('=');
225
+ const field = entry.slice(0, separator).trim();
226
+ const path = entry.slice(separator + 1);
227
+ if (separator <= 0 || !field || !path)
228
+ throw new ValidationError('file', 'Use --file <field>=<local-path>');
229
+ if (seen.has(field))
230
+ throw new ValidationError('file', `Only one file per field is supported: ${field}`);
231
+ seen.add(field);
232
+ return { field, path };
233
+ });
234
+ }
235
+ /** Form file field keys as the server names them, or null when there is no form trigger. */
236
+ function formFileFields(workflow) {
237
+ const nodes = Array.isArray(workflow.nodes) ? workflow.nodes.filter(isRow) : [];
238
+ const trigger = nodes.find((node) => typeof node.type === 'string' && node.type.endsWith('.formTrigger'));
239
+ if (!trigger)
240
+ return null;
241
+ const raw = isRow(trigger.parameters) ? trigger.parameters.formFields : undefined;
242
+ let values = isRow(raw) ? raw.values : undefined;
243
+ // Older workflows store the field list as a JSON string.
244
+ if (typeof raw === 'string') {
245
+ try {
246
+ values = JSON.parse(raw);
247
+ }
248
+ catch {
249
+ values = [];
250
+ }
251
+ }
252
+ if (!Array.isArray(values))
253
+ return [];
254
+ // A missing or blank fieldName is keyed by position, as the server's form readers do.
255
+ return values.flatMap((field, index) => isRow(field) && field.fieldType === 'file'
256
+ ? [
257
+ typeof field.fieldName === 'string' && field.fieldName.trim()
258
+ ? field.fieldName
259
+ : `field_${index}`,
260
+ ]
261
+ : []);
262
+ }
263
+ /**
264
+ * Internal workflows are hidden from a plain read but still runnable, so retry the read with
265
+ * includeInternal. A 404 there means no such workflow (the server checks existence before the
266
+ * internal permission), so fail before uploading; only a refused internal read skips the check.
267
+ */
268
+ async function runnableFormFileFields(workflowId) {
269
+ try {
270
+ return formFileFields(dataRow(await client.get(`/workflows/${workflowId}`)));
271
+ }
272
+ catch (error) {
273
+ if (!(error instanceof NotFoundError))
274
+ throw error;
275
+ }
276
+ try {
277
+ return formFileFields(dataRow(await client.get(`/workflows/${workflowId}`, { includeInternal: 'true' })));
278
+ }
279
+ catch (error) {
280
+ if (error instanceof NotFoundError)
281
+ throw error;
282
+ return null;
283
+ }
284
+ }
220
285
  export async function runWorkflowAction(id, options) {
221
- const path = `/workflows/${resourceId(id)}/run`;
286
+ const workflowId = resourceId(id);
287
+ const path = `/workflows/${workflowId}/run`;
222
288
  const triggerData = parseJson(options.json ?? '{}');
223
289
  if (!isRow(triggerData))
224
290
  throw new ValidationError('json', 'Trigger inputs must be an object');
225
- const payload = { triggerData };
291
+ const files = parseFileInputs(options.file ?? []);
292
+ for (const { field } of files) {
293
+ if (Object.hasOwn(triggerData, field))
294
+ throw new ValidationError('file', `Field ${field} is set both in --json and --file`);
295
+ }
296
+ if (files.length > 0) {
297
+ const accepted = await runnableFormFileFields(workflowId);
298
+ for (const { field } of files) {
299
+ if (accepted && !accepted.includes(field)) {
300
+ throw new ValidationError('file', `The form has no file field ${field}. File fields: ${accepted.join(', ') || 'none'}`);
301
+ }
302
+ }
303
+ // Validate every local file before uploading any, so a typo uploads nothing.
304
+ for (const file of files)
305
+ await readLocalUploadFile(file.path);
306
+ }
226
307
  if (options.dryRun) {
227
- printJson({ dryRun: true, method: 'POST', path, payload });
308
+ printJson({
309
+ dryRun: true,
310
+ method: 'POST',
311
+ path,
312
+ payload: { triggerData },
313
+ uploads: files.map(({ field, path: localPath }) => ({
314
+ field,
315
+ localPath,
316
+ to: 'Team Files root, then passed as mesh://team-files/<id>',
317
+ })),
318
+ });
228
319
  return;
229
320
  }
230
- printJson(dataRow(await client.post(path, payload)));
321
+ const fileInputsMeta = {};
322
+ for (const { field, path: localPath } of files) {
323
+ const uploaded = await uploadLocalTeamFile(localPath, {});
324
+ if (typeof uploaded.id !== 'string')
325
+ throw new ApiError(502, 'Team Files upload response did not include a file ID');
326
+ triggerData[field] = `mesh://team-files/${uploaded.id}`;
327
+ fileInputsMeta[field] = {
328
+ fileId: uploaded.id,
329
+ name: typeof uploaded.name === 'string' ? uploaded.name : localPath,
330
+ size: typeof uploaded.fileSize === 'number' ? uploaded.fileSize : 0,
331
+ };
332
+ }
333
+ printJson(dataRow(await client.post(path, files.length > 0 ? { triggerData, fileInputsMeta } : { triggerData })));
231
334
  }
232
335
  function propertyContainer(draft, pointer, target) {
233
336
  if (!pointer.startsWith('/') || /~(?![01])/.test(pointer))
@@ -411,6 +514,7 @@ export function registerWorkflowCommand(program) {
411
514
  cmd
412
515
  .command('run <id>')
413
516
  .option('--json <inputs>', 'Trigger inputs as JSON')
517
+ .option('--file <field=path>', 'Upload a local file for a form file field (repeatable)', (value, previous) => [...previous, value], [])
414
518
  .option('--dry-run', 'Preview execution')
415
519
  .action(async (id, o) => action(() => runWorkflowAction(id, o)));
416
520
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.35",
3
+ "version": "0.2.36",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",
@@ -85,6 +85,17 @@ zl --environment <us-prod|eu-prod> file seed --source-team-id <source-team-ref>
85
85
  zl --environment <us-prod|eu-prod> file seed --source-team-id <source-team-ref> --source-path /Fixtures --target-path /Rehearsal --apply --expected-checksum <sha256>
86
86
  ```
87
87
 
88
+ ## Keep workflow step outputs small
89
+
90
+ When authoring or reviewing a workflow that reads worksheets, loops over rows, or waits for review:
91
+
92
+ 1. Save bulk rows, write plans, and readback evidence once as run-scoped file artifacts. Pass references and only the fields the next step uses, such as worksheet ID, row count, and verification status. Resolve an artifact at the step that consumes it.
93
+ 2. At projection steps, set `includeInputFields: false` on Set nodes and map the required fields explicitly. In Python Code, emit only those fields in each returned item. Check expressions for whole-node reads such as `$('Read Rows').first().json`, especially in loops and before Wait nodes.
94
+ 3. Carry a compact review manifest across a Wait. Preserve the locked environment, the artifact reference and hash, and approved action IDs and hashes where the flow uses them. After a write, retain the verification result and its evidence reference.
95
+ 4. Validate the definition, then run a dedicated test workflow with representative test data and sandbox or mocked write integrations. Exercise approval, resume, and post-write verification. Inspect the largest step outputs and confirm the worksheet data appears only where consumed. `workflow run --dry-run` previews invocation. Measure outputs from the test run.
96
+
97
+ For a workbook verification → journal-source planning handoff, pass the readback artifact reference, worksheet ID, row count, and verification result. The planning node can read the artifact when it needs the rows.
98
+
88
99
  ## Pages and Motion work
89
100
 
90
101
  Pages use Markdown files with a revision marker. Export before editing, then preview