@zalosai/zalos-cli 0.2.24 → 0.2.25
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 +6 -0
- package/dist/client.js +10 -2
- package/dist/commands/codepack.js +239 -0
- package/dist/commands/skills.js +14 -16
- package/dist/commands/workflow.js +14 -7
- package/dist/main.js +4 -0
- package/dist/utils/codepack-scaffold.js +240 -0
- package/dist/utils/codepack.js +181 -0
- package/package.json +1 -1
- package/skills/codepack-authoring/SKILL.md +182 -0
package/PUBLISHING.md
CHANGED
|
@@ -59,6 +59,12 @@ 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.25 adds `zl codepack init|validate|publish|manifest` and the bundled
|
|
63
|
+
`codepack-authoring` skill. `init`, `validate`, and the skill work offline.
|
|
64
|
+
`publish` and `manifest` need the `/codepacks` API and its scoped-token route
|
|
65
|
+
grants deployed in the selected region, and `publish --workflow` also needs the
|
|
66
|
+
workflow-history route grants.
|
|
67
|
+
|
|
62
68
|
Version 0.2.24 adds `zl file folder list` and `zl file folder create` for
|
|
63
69
|
organizing Team Files through the existing `/api/folders` API (`files` scope).
|
|
64
70
|
`create` accepts `--parent-folder-id` for nesting and `--dry-run` to preview.
|
package/dist/client.js
CHANGED
|
@@ -36,14 +36,21 @@ async function request(options, tokenOverride) {
|
|
|
36
36
|
const headers = {
|
|
37
37
|
'X-Mesh-API-Key': token,
|
|
38
38
|
};
|
|
39
|
-
|
|
39
|
+
const binary = body instanceof Uint8Array;
|
|
40
|
+
if (binary)
|
|
41
|
+
headers['Content-Type'] = options.contentType ?? 'application/octet-stream';
|
|
42
|
+
else if (body != null && !isFormData(body))
|
|
40
43
|
headers['Content-Type'] = 'application/json';
|
|
41
44
|
const response = await fetch(url.toString(), {
|
|
42
45
|
method,
|
|
43
46
|
signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
|
|
44
47
|
redirect: 'error',
|
|
45
48
|
headers,
|
|
46
|
-
body: body
|
|
49
|
+
body: body == null
|
|
50
|
+
? undefined
|
|
51
|
+
: binary || isFormData(body)
|
|
52
|
+
? body
|
|
53
|
+
: JSON.stringify(body),
|
|
47
54
|
});
|
|
48
55
|
if (response.status === 401 || response.status === 403) {
|
|
49
56
|
if (options.detailedAuthErrors) {
|
|
@@ -69,6 +76,7 @@ export const client = {
|
|
|
69
76
|
get: (path, query) => request({ method: 'GET', path, query }),
|
|
70
77
|
post: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
71
78
|
postForm: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
79
|
+
postBinary: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
72
80
|
put: (path, body) => request({ method: 'PUT', path, body }),
|
|
73
81
|
patch: (path, body) => request({ method: 'PATCH', path, body }),
|
|
74
82
|
delete: (path) => request({ method: 'DELETE', path }),
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { client } from '../client.js';
|
|
2
|
+
import { packCodepack } from '../utils/codepack.js';
|
|
3
|
+
import { scaffoldCodepack } from '../utils/codepack-scaffold.js';
|
|
4
|
+
import { ApiError, ValidationError } from '../utils/errors.js';
|
|
5
|
+
import { printJson } from '../utils/output.js';
|
|
6
|
+
import { action, dataRow, isRow, resourceId } from '../utils/product-api.js';
|
|
7
|
+
import { parseWorkflowFile } from '../workflow-file.js';
|
|
8
|
+
import { publicationStatus, putWorkflowDraft } from './workflow.js';
|
|
9
|
+
const PUBLISH_TIMEOUT_MS = 120_000;
|
|
10
|
+
const CODEPACK_REF_PATTERN = /^codepack:sha256:[0-9a-f]{64}$/;
|
|
11
|
+
const CODEPACK_NODE_TYPE = 'mesh-nodes-base.codepack';
|
|
12
|
+
const MAX_CHECKPOINT_NAME_LENGTH = 200;
|
|
13
|
+
function summary(codepack) {
|
|
14
|
+
return {
|
|
15
|
+
templateKey: codepack.templateKey,
|
|
16
|
+
agentRef: codepack.agentRef,
|
|
17
|
+
archiveSha256: codepack.archiveSha256,
|
|
18
|
+
archiveSizeBytes: codepack.archiveSizeBytes,
|
|
19
|
+
files: codepack.files,
|
|
20
|
+
skipped: codepack.skipped,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function templateName(templateKey) {
|
|
24
|
+
return templateKey.slice('TEMPLATE:'.length).replace(/@v\d+$/, '');
|
|
25
|
+
}
|
|
26
|
+
/** The Codepack node that runs a published codepack, ready to paste into workflow JSON. */
|
|
27
|
+
function codepackNode(agentRef, templateKey) {
|
|
28
|
+
return {
|
|
29
|
+
name: templateName(templateKey),
|
|
30
|
+
type: CODEPACK_NODE_TYPE,
|
|
31
|
+
typeVersion: 1,
|
|
32
|
+
position: [0, 0],
|
|
33
|
+
parameters: {
|
|
34
|
+
codepackRef: agentRef,
|
|
35
|
+
fileInputs: '{}',
|
|
36
|
+
parameters: '{}',
|
|
37
|
+
outputFolderPath: '',
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function nodeLabel(node) {
|
|
42
|
+
return typeof node.name === 'string' ? node.name : String(node.id);
|
|
43
|
+
}
|
|
44
|
+
/** Resolves the node to repin: an exact id match wins over a name match. */
|
|
45
|
+
export function findCodepackNode(workflow, selector) {
|
|
46
|
+
const nodes = workflow.nodes.filter(isRow);
|
|
47
|
+
if (selector === undefined) {
|
|
48
|
+
const candidates = nodes.filter((node) => node.type === CODEPACK_NODE_TYPE);
|
|
49
|
+
if (candidates.length === 1)
|
|
50
|
+
return candidates[0];
|
|
51
|
+
throw new ValidationError('node', candidates.length === 0
|
|
52
|
+
? 'Workflow has no Codepack node; add one or pass --node'
|
|
53
|
+
: `Workflow has several Codepack nodes; pass --node with one of: ${candidates.map(nodeLabel).join(', ')}`);
|
|
54
|
+
}
|
|
55
|
+
const byId = nodes.filter((node) => node.id === selector);
|
|
56
|
+
const matches = byId.length > 0 ? byId : nodes.filter((node) => node.name === selector);
|
|
57
|
+
if (matches.length !== 1) {
|
|
58
|
+
throw new ValidationError('node', matches.length === 0
|
|
59
|
+
? `No node with id or name "${selector}"`
|
|
60
|
+
: `Several nodes are named "${selector}"; pass the node id`);
|
|
61
|
+
}
|
|
62
|
+
const [node] = matches;
|
|
63
|
+
if (node.type !== CODEPACK_NODE_TYPE) {
|
|
64
|
+
throw new ValidationError('node', `Node "${nodeLabel(node)}" is ${String(node.type)}, not a Codepack node`);
|
|
65
|
+
}
|
|
66
|
+
return node;
|
|
67
|
+
}
|
|
68
|
+
function checkpointLabel(label, codepack) {
|
|
69
|
+
const shortHash = codepack.agentRef.slice('codepack:sha256:'.length, 'codepack:sha256:'.length + 12);
|
|
70
|
+
const name = (label ?? `${templateName(codepack.templateKey)} ${shortHash}`).trim();
|
|
71
|
+
if (!name)
|
|
72
|
+
throw new ValidationError('label', 'Checkpoint name must not be empty');
|
|
73
|
+
if (name.length > MAX_CHECKPOINT_NAME_LENGTH) {
|
|
74
|
+
throw new ValidationError('label', `Checkpoint name must be at most ${MAX_CHECKPOINT_NAME_LENGTH} characters`);
|
|
75
|
+
}
|
|
76
|
+
return name;
|
|
77
|
+
}
|
|
78
|
+
async function planCodepackPin(workflowId, codepack, options) {
|
|
79
|
+
const draft = parseWorkflowFile(JSON.stringify(dataRow(await client.get(`/workflows/${resourceId(workflowId)}`))), workflowId);
|
|
80
|
+
const node = findCodepackNode(draft, options.node);
|
|
81
|
+
if (node.parameters !== undefined && !isRow(node.parameters)) {
|
|
82
|
+
throw new ValidationError('node', `Node "${nodeLabel(node)}" has malformed parameters`);
|
|
83
|
+
}
|
|
84
|
+
const parameters = isRow(node.parameters) ? node.parameters : {};
|
|
85
|
+
node.parameters = parameters;
|
|
86
|
+
return {
|
|
87
|
+
draft,
|
|
88
|
+
node,
|
|
89
|
+
parameters,
|
|
90
|
+
previousRef: parameters.codepackRef,
|
|
91
|
+
label: checkpointLabel(options.label, codepack),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function checkpointDescription(pin, agentRef) {
|
|
95
|
+
const previous = typeof pin.previousRef === 'string' && pin.previousRef && pin.previousRef !== agentRef
|
|
96
|
+
? ` (was ${pin.previousRef})`
|
|
97
|
+
: '';
|
|
98
|
+
return `Pins Codepack node "${nodeLabel(pin.node)}" to ${agentRef}${previous}.`;
|
|
99
|
+
}
|
|
100
|
+
/** Confirms the sealed checkpoint holds the new pin, so a concurrent edit cannot go unnoticed. */
|
|
101
|
+
async function verifyCheckpoint(workflowId, checkpoint, nodeId, agentRef) {
|
|
102
|
+
if (typeof checkpoint.id !== 'string') {
|
|
103
|
+
throw new ApiError(502, 'Checkpoint response did not include an id');
|
|
104
|
+
}
|
|
105
|
+
const version = dataRow(await client.get(`/workflows/${resourceId(workflowId)}/history/${resourceId(checkpoint.id)}`));
|
|
106
|
+
const nodes = Array.isArray(version.nodes) ? version.nodes.filter(isRow) : [];
|
|
107
|
+
const pinned = nodes.find((node) => node.id === nodeId);
|
|
108
|
+
const pinnedRef = isRow(pinned?.parameters) ? pinned.parameters.codepackRef : undefined;
|
|
109
|
+
if (pinnedRef !== agentRef) {
|
|
110
|
+
throw new ApiError(409, `Checkpoint ${checkpoint.id} does not pin ${agentRef}; the workflow changed while publishing. Re-run the command.`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function uploadCodepack(codepack) {
|
|
114
|
+
const published = dataRow(await client.postBinary('/codepacks', codepack.archive, {
|
|
115
|
+
contentType: 'application/gzip',
|
|
116
|
+
timeoutMs: PUBLISH_TIMEOUT_MS,
|
|
117
|
+
}));
|
|
118
|
+
if (published.agentRef !== codepack.agentRef) {
|
|
119
|
+
// The server hashes the bytes it stored; a mismatch means they changed in transit.
|
|
120
|
+
throw new ValidationError('codepack', 'Server stored a different archive than was packed');
|
|
121
|
+
}
|
|
122
|
+
return published;
|
|
123
|
+
}
|
|
124
|
+
export async function validateCodepackAction(directory) {
|
|
125
|
+
printJson({ data: summary(await packCodepack(directory)) });
|
|
126
|
+
}
|
|
127
|
+
export async function initCodepackAction(name, options) {
|
|
128
|
+
const scaffold = await scaffoldCodepack(name, options.directory);
|
|
129
|
+
const dir = scaffold.directory;
|
|
130
|
+
printJson({
|
|
131
|
+
data: {
|
|
132
|
+
...scaffold,
|
|
133
|
+
next: [
|
|
134
|
+
`cd ${JSON.stringify(dir)}`,
|
|
135
|
+
'python process.py inputs/sample.csv --period_end 2026-10-31',
|
|
136
|
+
'python -m pytest tests',
|
|
137
|
+
`zl codepack validate ${JSON.stringify(dir)}`,
|
|
138
|
+
`zl codepack publish ${JSON.stringify(dir)}`,
|
|
139
|
+
],
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
async function publishAndPinAction(directory, workflowId, options) {
|
|
144
|
+
const codepack = await packCodepack(directory);
|
|
145
|
+
const pin = await planCodepackPin(workflowId, codepack, options);
|
|
146
|
+
const changed = pin.previousRef !== codepack.agentRef;
|
|
147
|
+
const target = {
|
|
148
|
+
workflowId,
|
|
149
|
+
nodeId: pin.node.id,
|
|
150
|
+
nodeName: pin.node.name,
|
|
151
|
+
previousRef: pin.previousRef ?? null,
|
|
152
|
+
codepackRef: codepack.agentRef,
|
|
153
|
+
changed,
|
|
154
|
+
};
|
|
155
|
+
if (!options.apply || options.dryRun) {
|
|
156
|
+
printJson({
|
|
157
|
+
dryRun: true,
|
|
158
|
+
codepack: summary(codepack),
|
|
159
|
+
workflow: target,
|
|
160
|
+
checkpoint: { name: pin.label, description: checkpointDescription(pin, codepack.agentRef) },
|
|
161
|
+
});
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const published = await uploadCodepack(codepack);
|
|
165
|
+
let saved = pin.draft;
|
|
166
|
+
if (changed) {
|
|
167
|
+
pin.parameters.codepackRef = codepack.agentRef;
|
|
168
|
+
saved = await putWorkflowDraft(workflowId, pin.draft);
|
|
169
|
+
}
|
|
170
|
+
const checkpoint = dataRow(await client.post(`/workflows/${resourceId(workflowId)}/history`, {
|
|
171
|
+
name: pin.label,
|
|
172
|
+
description: checkpointDescription(pin, codepack.agentRef),
|
|
173
|
+
}));
|
|
174
|
+
await verifyCheckpoint(workflowId, checkpoint, pin.node.id, codepack.agentRef);
|
|
175
|
+
printJson({
|
|
176
|
+
data: {
|
|
177
|
+
codepack: { ...published, files: codepack.files },
|
|
178
|
+
workflow: target,
|
|
179
|
+
checkpoint,
|
|
180
|
+
publication: publicationStatus(saved),
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
export async function publishCodepackAction(directory, options = {}) {
|
|
185
|
+
if (options.workflow !== undefined) {
|
|
186
|
+
await publishAndPinAction(directory, options.workflow, options);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (options.node !== undefined || options.label !== undefined) {
|
|
190
|
+
throw new ValidationError('workflow', '--node and --label need --workflow');
|
|
191
|
+
}
|
|
192
|
+
const codepack = await packCodepack(directory);
|
|
193
|
+
if (options.dryRun) {
|
|
194
|
+
printJson({ dryRun: true, method: 'POST', path: '/codepacks', codepack: summary(codepack) });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const published = await uploadCodepack(codepack);
|
|
198
|
+
printJson({
|
|
199
|
+
data: {
|
|
200
|
+
...published,
|
|
201
|
+
files: codepack.files,
|
|
202
|
+
node: codepackNode(codepack.agentRef, codepack.templateKey),
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
export async function viewCodepackManifestAction(agentRef) {
|
|
207
|
+
if (!CODEPACK_REF_PATTERN.test(agentRef)) {
|
|
208
|
+
throw new ValidationError('agentRef', 'Expected codepack:sha256:<64 hex>');
|
|
209
|
+
}
|
|
210
|
+
printJson({ data: dataRow(await client.get(`/codepacks/${agentRef}/manifest`)) });
|
|
211
|
+
}
|
|
212
|
+
export function registerCodepackCommand(program) {
|
|
213
|
+
const cmd = program
|
|
214
|
+
.command('codepack')
|
|
215
|
+
.description('Package and publish Python codepacks that Codepack nodes run');
|
|
216
|
+
cmd
|
|
217
|
+
.command('init <name>')
|
|
218
|
+
.description('Create a runnable codepack folder (snake_case name) to start from')
|
|
219
|
+
.option('--directory <path>', 'Folder to create (default: ./<name>); must be empty')
|
|
220
|
+
.action(async (name, o) => action(() => initCodepackAction(name, o)));
|
|
221
|
+
cmd
|
|
222
|
+
.command('validate <directory>')
|
|
223
|
+
.description('Check a codepack folder and print the codepack ref it would publish as')
|
|
224
|
+
.action(async (directory) => action(() => validateCodepackAction(directory)));
|
|
225
|
+
cmd
|
|
226
|
+
.command('publish <directory>')
|
|
227
|
+
.description('Publish a codepack folder to the selected team; with --workflow, repin its Codepack node and save a named checkpoint')
|
|
228
|
+
.option('--workflow <id>', 'Repin a Codepack node in this workflow (needs --apply)')
|
|
229
|
+
.option('--node <id-or-name>', 'Codepack node to repin; optional when the workflow has one')
|
|
230
|
+
.option('--label <name>', 'Checkpoint name (default: template name and short hash)')
|
|
231
|
+
.option('--apply', 'With --workflow: publish, save the draft and create the checkpoint')
|
|
232
|
+
.option('--dry-run', 'With --workflow: preview the repin without publishing')
|
|
233
|
+
.action(async (directory, o) => action(() => publishCodepackAction(directory, o)));
|
|
234
|
+
cmd
|
|
235
|
+
.command('manifest <agentRef>')
|
|
236
|
+
.description('Show the runtime manifest Mesh derived for a published codepack')
|
|
237
|
+
.action(async (agentRef) => action(() => viewCodepackManifestAction(agentRef)));
|
|
238
|
+
}
|
|
239
|
+
//# sourceMappingURL=codepack.js.map
|
package/dist/commands/skills.js
CHANGED
|
@@ -5,17 +5,23 @@ import { fileURLToPath } from 'node:url';
|
|
|
5
5
|
import { ValidationError } from '../utils/errors.js';
|
|
6
6
|
import { printJson } from '../utils/output.js';
|
|
7
7
|
import { action } from '../utils/product-api.js';
|
|
8
|
-
|
|
9
|
-
const
|
|
8
|
+
/** Skills shipped in the package under skills/<name>/SKILL.md. */
|
|
9
|
+
const BUNDLED_SKILLS = [
|
|
10
|
+
{ name: 'zl-ops', description: 'Zalos production operations' },
|
|
11
|
+
{ name: 'update-zalos', description: 'Check and download verified Zalos Desktop updates' },
|
|
12
|
+
{
|
|
13
|
+
name: 'codepack-authoring',
|
|
14
|
+
description: 'Build, test, and publish Python codepacks that Codepack nodes run',
|
|
15
|
+
},
|
|
16
|
+
];
|
|
10
17
|
function isSkillTarget(value) {
|
|
11
18
|
return value === 'claude' || value === 'codex';
|
|
12
19
|
}
|
|
13
20
|
function skillPath(name) {
|
|
14
|
-
if (name ===
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return OPS_SKILL_PATH;
|
|
21
|
+
if (!BUNDLED_SKILLS.some((skill) => skill.name === name))
|
|
22
|
+
throw new ValidationError('skill', `Unknown skill: ${name}. Available: ${BUNDLED_SKILLS.map((skill) => skill.name).join(', ')}`);
|
|
23
|
+
// The name is one of the fixed entries above, never caller-supplied path text.
|
|
24
|
+
return fileURLToPath(new URL(`../../skills/${name}/SKILL.md`, import.meta.url));
|
|
19
25
|
}
|
|
20
26
|
export function resolveDefaultSkillsDirectory(target, home = homedir()) {
|
|
21
27
|
if (target === 'codex') {
|
|
@@ -72,15 +78,7 @@ export function registerSkillsCommand(program) {
|
|
|
72
78
|
command
|
|
73
79
|
.command('list')
|
|
74
80
|
.description('List bundled skills (no network or authentication required)')
|
|
75
|
-
.action(() => printJson({
|
|
76
|
-
skills: [
|
|
77
|
-
{ name: OPS_SKILL_NAME, description: 'Zalos production operations' },
|
|
78
|
-
{
|
|
79
|
-
name: 'update-zalos',
|
|
80
|
-
description: 'Check and download verified Zalos Desktop updates',
|
|
81
|
-
},
|
|
82
|
-
],
|
|
83
|
-
}));
|
|
81
|
+
.action(() => printJson({ skills: BUNDLED_SKILLS }));
|
|
84
82
|
command
|
|
85
83
|
.command('read <name>')
|
|
86
84
|
.description('Print a bundled SKILL.md (no network or authentication required)')
|
|
@@ -25,7 +25,7 @@ async function readWorkflow(id, options) {
|
|
|
25
25
|
const { checksum: _checksum, expectedChecksum: _expectedChecksum, ...snapshot } = workflow;
|
|
26
26
|
return snapshot;
|
|
27
27
|
}
|
|
28
|
-
function publicationStatus(workflow, publishedNow = false) {
|
|
28
|
+
export function publicationStatus(workflow, publishedNow = false) {
|
|
29
29
|
const draftVersionId = typeof workflow.versionId === 'string' ? workflow.versionId : undefined;
|
|
30
30
|
const publishedVersionId = typeof workflow.publishedVersionId === 'string' ? workflow.publishedVersionId : undefined;
|
|
31
31
|
const published = publishedVersionId === undefined ||
|
|
@@ -149,8 +149,8 @@ export async function importWorkflowAction(path, options) {
|
|
|
149
149
|
export async function updateWorkflowAction(id, options) {
|
|
150
150
|
await saveWorkflowDraft(id, await readWorkflowFile(options.input, id), options);
|
|
151
151
|
}
|
|
152
|
-
|
|
153
|
-
|
|
152
|
+
/** The PUT body for a draft, carrying its checksum as the optimistic-concurrency baseline. */
|
|
153
|
+
function draftUpdatePayload(draft, requireBaseline) {
|
|
154
154
|
const { checksum, expectedChecksum, versionId: _versionId, publishedVersionId: _publishedVersionId, ...workflow } = draft;
|
|
155
155
|
for (const value of [checksum, expectedChecksum]) {
|
|
156
156
|
if (value !== undefined && (typeof value !== 'string' || !value.trim())) {
|
|
@@ -161,18 +161,25 @@ async function saveWorkflowDraft(id, draft, options) {
|
|
|
161
161
|
throw new ValidationError('checksum', 'expectedChecksum does not match the exported checksum');
|
|
162
162
|
}
|
|
163
163
|
const baseline = expectedChecksum ?? checksum;
|
|
164
|
-
if (
|
|
164
|
+
if (requireBaseline && baseline === undefined) {
|
|
165
165
|
throw new ValidationError('checksum', 'Update requires checksum or expectedChecksum; export the current workflow before editing');
|
|
166
166
|
}
|
|
167
|
-
|
|
167
|
+
return {
|
|
168
168
|
...workflow,
|
|
169
169
|
...(baseline !== undefined ? { expectedChecksum: baseline } : {}),
|
|
170
170
|
};
|
|
171
|
+
}
|
|
172
|
+
/** Saves a draft read from the API, refusing it if the workflow changed since that read. */
|
|
173
|
+
export async function putWorkflowDraft(id, draft) {
|
|
174
|
+
return dataRow(await client.put(`/workflows/${resourceId(id)}`, draftUpdatePayload(draft, true)));
|
|
175
|
+
}
|
|
176
|
+
async function saveWorkflowDraft(id, draft, options) {
|
|
171
177
|
if (!options.apply || options.dryRun) {
|
|
172
|
-
|
|
178
|
+
const path = `/workflows/${resourceId(id)}`;
|
|
179
|
+
printJson({ dryRun: true, method: 'PUT', path, payload: draftUpdatePayload(draft, false) });
|
|
173
180
|
return;
|
|
174
181
|
}
|
|
175
|
-
const saved =
|
|
182
|
+
const saved = await putWorkflowDraft(id, draft);
|
|
176
183
|
printJson({ workflow: saved, publication: publicationStatus(saved) });
|
|
177
184
|
}
|
|
178
185
|
export async function publishWorkflowAction(id, options) {
|
package/dist/main.js
CHANGED
|
@@ -5,6 +5,7 @@ import { registerDesktopCommand } from './commands/desktop.js';
|
|
|
5
5
|
import { registerSetupCommand } from './commands/setup.js';
|
|
6
6
|
import { registerDoctorCommand } from './commands/doctor.js';
|
|
7
7
|
import { registerWorkflowCommand } from './commands/workflow.js';
|
|
8
|
+
import { registerCodepackCommand } from './commands/codepack.js';
|
|
8
9
|
import { registerDataTableCommand } from './commands/data-table.js';
|
|
9
10
|
import { registerExecutionCommand } from './commands/execution.js';
|
|
10
11
|
import { registerTemplateCommand } from './commands/template.js';
|
|
@@ -49,6 +50,8 @@ program
|
|
|
49
50
|
actionCommand.name() === 'skills' ||
|
|
50
51
|
(actionCommand.name() === 'validate' && actionCommand.parent?.name() === 'workflow') ||
|
|
51
52
|
(actionCommand.name() === 'validate' && actionCommand.parent?.name() === 'data-table') ||
|
|
53
|
+
((actionCommand.name() === 'validate' || actionCommand.name() === 'init') &&
|
|
54
|
+
actionCommand.parent?.name() === 'codepack') ||
|
|
52
55
|
((actionCommand.name() === 'validate' || actionCommand.name() === 'starter') &&
|
|
53
56
|
actionCommand.parent?.name() === 'custom-page') ||
|
|
54
57
|
actionCommand.parent?.name() === 'schema' ||
|
|
@@ -70,6 +73,7 @@ registerApiTokenCommand(program);
|
|
|
70
73
|
registerSetupCommand(program);
|
|
71
74
|
registerDoctorCommand(program);
|
|
72
75
|
registerWorkflowCommand(program);
|
|
76
|
+
registerCodepackCommand(program);
|
|
73
77
|
registerDataTableCommand(program);
|
|
74
78
|
registerExecutionCommand(program);
|
|
75
79
|
registerTemplateCommand(program);
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { mkdir, readdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { ValidationError } from './errors.js';
|
|
4
|
+
/**
|
|
5
|
+
* Scaffold a runnable codepack (`zl codepack init`).
|
|
6
|
+
*
|
|
7
|
+
* The folder runs locally with plain Python: `codepack_runtime.py` stands in
|
|
8
|
+
* for agent-studio's private `zalosai.agent_tools`, writing the same
|
|
9
|
+
* `OUTPUT_DIR` registration manifest and progress lines the Mesh executor
|
|
10
|
+
* reads. `inputs/` and `tests/` help the author iterate but are never packed.
|
|
11
|
+
*/
|
|
12
|
+
const CODEPACK_NAME_PATTERN = /^[a-z][a-z0-9_]{1,62}$/;
|
|
13
|
+
function titleCase(name) {
|
|
14
|
+
return name
|
|
15
|
+
.split('_')
|
|
16
|
+
.filter(Boolean)
|
|
17
|
+
.map((word) => word[0].toUpperCase() + word.slice(1))
|
|
18
|
+
.join(' ');
|
|
19
|
+
}
|
|
20
|
+
function configYaml(name) {
|
|
21
|
+
const templateKey = `TEMPLATE:${name}@v1`;
|
|
22
|
+
return `${templateKey}:
|
|
23
|
+
canonical_key: ${templateKey}
|
|
24
|
+
name: "${titleCase(name)}"
|
|
25
|
+
description: Summarise a CSV or Excel file of amounts
|
|
26
|
+
category: Codepack
|
|
27
|
+
script_path: process.py
|
|
28
|
+
|
|
29
|
+
# Required file inputs reach process.py as positional arguments, in this
|
|
30
|
+
# order. Optional ones (required: false) arrive as --<fieldName> <path>.
|
|
31
|
+
file_inputs:
|
|
32
|
+
- fieldName: source
|
|
33
|
+
fieldLabel: Source file
|
|
34
|
+
fieldType: file
|
|
35
|
+
description: CSV or Excel file with an Amount column
|
|
36
|
+
acceptFileTypes:
|
|
37
|
+
- .csv
|
|
38
|
+
- .xlsx
|
|
39
|
+
required: true
|
|
40
|
+
|
|
41
|
+
# Parameters arrive as --<fieldName> <value>; booleans as a bare --<fieldName>.
|
|
42
|
+
parameters:
|
|
43
|
+
- fieldName: period_end
|
|
44
|
+
fieldLabel: Period end
|
|
45
|
+
fieldType: date
|
|
46
|
+
description: Period end date to stamp on the summary (optional)
|
|
47
|
+
format: YYYY-MM-DD
|
|
48
|
+
required: false
|
|
49
|
+
|
|
50
|
+
# Every declared output must be written under OUTPUT_DIR and registered with
|
|
51
|
+
# register_output(fieldName, path); its extension must match fileType.
|
|
52
|
+
output_contract:
|
|
53
|
+
files:
|
|
54
|
+
- fieldName: summary
|
|
55
|
+
fieldLabel: Summary
|
|
56
|
+
fieldType: file
|
|
57
|
+
required: true
|
|
58
|
+
fileType: csv
|
|
59
|
+
`;
|
|
60
|
+
}
|
|
61
|
+
const PROCESS_PY = `#!/usr/bin/env python3
|
|
62
|
+
"""Summarise a CSV or Excel file: row count and total of its Amount column."""
|
|
63
|
+
|
|
64
|
+
import argparse
|
|
65
|
+
import sys
|
|
66
|
+
from pathlib import Path
|
|
67
|
+
|
|
68
|
+
import pandas as pd
|
|
69
|
+
|
|
70
|
+
from codepack_runtime import get_output_dir, register_output, step_begin, step_detail
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_table(path: Path) -> pd.DataFrame:
|
|
74
|
+
if path.suffix.lower() in {".xlsx", ".xls"}:
|
|
75
|
+
return pd.read_excel(path)
|
|
76
|
+
return pd.read_csv(path)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main() -> int:
|
|
80
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
81
|
+
parser.add_argument("source", type=Path, help="CSV or Excel file with an Amount column")
|
|
82
|
+
parser.add_argument("--period_end", default=None, help="Period end date (YYYY-MM-DD)")
|
|
83
|
+
args = parser.parse_args()
|
|
84
|
+
|
|
85
|
+
step_begin(1, 2, "Reading the source file", category="Input")
|
|
86
|
+
table = read_table(args.source)
|
|
87
|
+
amount_column = next((c for c in table.columns if str(c).strip().lower() == "amount"), None)
|
|
88
|
+
if amount_column is None:
|
|
89
|
+
# A plain error exits non-zero; Mesh shows the run as failed.
|
|
90
|
+
raise ValueError(f"No Amount column in {list(table.columns)}")
|
|
91
|
+
amounts = pd.to_numeric(table[amount_column], errors="coerce")
|
|
92
|
+
step_detail(f"{len(table)} rows")
|
|
93
|
+
|
|
94
|
+
step_begin(2, 2, "Writing the summary", category="Output")
|
|
95
|
+
summary = pd.DataFrame(
|
|
96
|
+
[
|
|
97
|
+
{
|
|
98
|
+
"period_end": args.period_end or "",
|
|
99
|
+
"rows": int(len(table)),
|
|
100
|
+
"total_amount": round(float(amounts.sum()), 2),
|
|
101
|
+
}
|
|
102
|
+
]
|
|
103
|
+
)
|
|
104
|
+
output = get_output_dir() / "summary.csv"
|
|
105
|
+
summary.to_csv(output, index=False)
|
|
106
|
+
register_output("summary", output)
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
sys.exit(main())
|
|
112
|
+
`;
|
|
113
|
+
const RUNTIME_PY = `"""Codepack runtime helpers, compatible with the Mesh executor.
|
|
114
|
+
|
|
115
|
+
The executor runs process.py with OUTPUT_DIR set, collects the files
|
|
116
|
+
registered in OUTPUT_DIR/.zalos_outputs.json against output_contract, and
|
|
117
|
+
shows the JSON progress lines printed to stdout as run steps.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
import json
|
|
121
|
+
import os
|
|
122
|
+
from pathlib import Path
|
|
123
|
+
|
|
124
|
+
REGISTRATION_MANIFEST = ".zalos_outputs.json"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def get_output_dir() -> Path:
|
|
128
|
+
"""Folder for output files: OUTPUT_DIR, or ./outputs when run by hand."""
|
|
129
|
+
output_dir = Path(os.getenv("OUTPUT_DIR", Path.cwd() / "outputs"))
|
|
130
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
return output_dir
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def register_output(field_name: str, path: str | Path) -> None:
|
|
135
|
+
"""Register a written file against an output_contract fieldName."""
|
|
136
|
+
output_dir = get_output_dir().resolve()
|
|
137
|
+
output_path = Path(path).resolve()
|
|
138
|
+
if not output_path.is_file():
|
|
139
|
+
raise FileNotFoundError(f"Registered output does not exist: {output_path}")
|
|
140
|
+
relative_path = output_path.relative_to(output_dir)
|
|
141
|
+
manifest_path = output_dir / REGISTRATION_MANIFEST
|
|
142
|
+
manifest = (
|
|
143
|
+
json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
144
|
+
if manifest_path.exists()
|
|
145
|
+
else {"files": []}
|
|
146
|
+
)
|
|
147
|
+
entry = {"fieldName": field_name, "path": str(relative_path)}
|
|
148
|
+
if entry in manifest["files"]:
|
|
149
|
+
return # re-running locally into the same folder registers each file once
|
|
150
|
+
manifest["files"].append(entry)
|
|
151
|
+
manifest_path.write_text(json.dumps(manifest, indent=2) + "\\n", encoding="utf-8")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def step_begin(step: int, of: int, label: str, *, category: str = "", description: str = "") -> None:
|
|
155
|
+
"""Start a progress step shown on the run in Mesh."""
|
|
156
|
+
print(
|
|
157
|
+
json.dumps(
|
|
158
|
+
{
|
|
159
|
+
"__type": "step_begin",
|
|
160
|
+
"step": step,
|
|
161
|
+
"of": of,
|
|
162
|
+
"label": label,
|
|
163
|
+
"category": category,
|
|
164
|
+
"description": description,
|
|
165
|
+
}
|
|
166
|
+
),
|
|
167
|
+
flush=True,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def step_detail(value: str) -> None:
|
|
172
|
+
"""Add a detail line under the current progress step."""
|
|
173
|
+
print(json.dumps({"__type": "step_detail", "value": value}), flush=True)
|
|
174
|
+
`;
|
|
175
|
+
const TEST_PY = `"""Runs process.py the way the Mesh executor does. Not packed into the codepack."""
|
|
176
|
+
|
|
177
|
+
import csv
|
|
178
|
+
import json
|
|
179
|
+
import os
|
|
180
|
+
import subprocess
|
|
181
|
+
import sys
|
|
182
|
+
from pathlib import Path
|
|
183
|
+
|
|
184
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def test_summarises_the_sample(tmp_path: Path) -> None:
|
|
188
|
+
result = subprocess.run(
|
|
189
|
+
[sys.executable, str(ROOT / "process.py"), str(ROOT / "inputs" / "sample.csv"), "--period_end", "2026-10-31"],
|
|
190
|
+
cwd=ROOT, # the executor runs process.py from the codepack folder
|
|
191
|
+
env={**os.environ, "OUTPUT_DIR": str(tmp_path)},
|
|
192
|
+
capture_output=True,
|
|
193
|
+
text=True,
|
|
194
|
+
check=True,
|
|
195
|
+
)
|
|
196
|
+
assert '"__type": "step_begin"' in result.stdout
|
|
197
|
+
registered = json.loads((tmp_path / ".zalos_outputs.json").read_text())
|
|
198
|
+
assert registered == {"files": [{"fieldName": "summary", "path": "summary.csv"}]}
|
|
199
|
+
with open(tmp_path / "summary.csv", newline="") as handle:
|
|
200
|
+
rows = list(csv.DictReader(handle))
|
|
201
|
+
assert rows == [{"period_end": "2026-10-31", "rows": "3", "total_amount": "1750.5"}]
|
|
202
|
+
`;
|
|
203
|
+
const SAMPLE_CSV = `Customer,Amount
|
|
204
|
+
Acme Ltd,1000.00
|
|
205
|
+
Globex,500.50
|
|
206
|
+
Initech,250.00
|
|
207
|
+
`;
|
|
208
|
+
const GITIGNORE = `outputs/
|
|
209
|
+
__pycache__/
|
|
210
|
+
.venv/
|
|
211
|
+
`;
|
|
212
|
+
export async function scaffoldCodepack(name, directory) {
|
|
213
|
+
if (!CODEPACK_NAME_PATTERN.test(name)) {
|
|
214
|
+
throw new ValidationError('name', 'Codepack name must be snake_case: a lowercase letter, then lowercase letters, digits or _');
|
|
215
|
+
}
|
|
216
|
+
const target = resolve(directory ?? name);
|
|
217
|
+
const existing = await readdir(target).catch((error) => {
|
|
218
|
+
if (error.code === 'ENOENT')
|
|
219
|
+
return [];
|
|
220
|
+
throw error;
|
|
221
|
+
});
|
|
222
|
+
if (existing.length > 0) {
|
|
223
|
+
throw new ValidationError('directory', `Directory is not empty: ${target}`);
|
|
224
|
+
}
|
|
225
|
+
const files = {
|
|
226
|
+
'config.yaml': configYaml(name),
|
|
227
|
+
'process.py': PROCESS_PY,
|
|
228
|
+
'codepack_runtime.py': RUNTIME_PY,
|
|
229
|
+
'inputs/sample.csv': SAMPLE_CSV,
|
|
230
|
+
'tests/test_process.py': TEST_PY,
|
|
231
|
+
'.gitignore': GITIGNORE,
|
|
232
|
+
};
|
|
233
|
+
for (const [path, contents] of Object.entries(files)) {
|
|
234
|
+
const absolute = join(target, path);
|
|
235
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
236
|
+
await writeFile(absolute, contents, { flag: 'wx' });
|
|
237
|
+
}
|
|
238
|
+
return { directory: target, templateKey: `TEMPLATE:${name}@v1`, files: Object.keys(files) };
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=codepack-scaffold.js.map
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat, readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { extname, join, relative, sep } from 'node:path';
|
|
4
|
+
import { gzipSync } from 'node:zlib';
|
|
5
|
+
import { parse as parseYaml } from 'yaml';
|
|
6
|
+
import { ValidationError } from './errors.js';
|
|
7
|
+
/**
|
|
8
|
+
* Pack a codepack folder into the codepack Mesh runs.
|
|
9
|
+
*
|
|
10
|
+
* The folder follows the agent-studio layout: `config.yaml` and `process.py`
|
|
11
|
+
* at the root, plus any modules and assets they read. File selection mirrors
|
|
12
|
+
* agent-studio's execution bundles (`zalosai/packaging/manifest.py`), so a
|
|
13
|
+
* codepack ships exactly the files the same agent gets in agent-studio:
|
|
14
|
+
* runtime assets such as `fixtures/*.pptx` go in; tests, sample inputs,
|
|
15
|
+
* outputs, private validation data, caches and dotfiles stay on the author's
|
|
16
|
+
* machine. The tarball is deterministic, so the same source always gets the
|
|
17
|
+
* same `codepack:sha256:` ref.
|
|
18
|
+
*/
|
|
19
|
+
/** agent-studio's EXCLUDED_DIRS, plus local environments it never sees. */
|
|
20
|
+
const EXCLUDED_DIRECTORIES = new Set([
|
|
21
|
+
'inputs',
|
|
22
|
+
'outputs',
|
|
23
|
+
'tests',
|
|
24
|
+
'private',
|
|
25
|
+
'private_validation',
|
|
26
|
+
'__pycache__',
|
|
27
|
+
'.venv',
|
|
28
|
+
'venv',
|
|
29
|
+
'node_modules',
|
|
30
|
+
]);
|
|
31
|
+
/** agent-studio's TEXT_BUNDLE_SUFFIXES and BINARY_BUNDLE_SUFFIXES. */
|
|
32
|
+
const INCLUDED_EXTENSIONS = new Set([
|
|
33
|
+
'.csv',
|
|
34
|
+
'.json',
|
|
35
|
+
'.py',
|
|
36
|
+
'.txt',
|
|
37
|
+
'.yaml',
|
|
38
|
+
'.yml',
|
|
39
|
+
'.pptx',
|
|
40
|
+
'.xls',
|
|
41
|
+
'.xlsb',
|
|
42
|
+
'.xlsx',
|
|
43
|
+
]);
|
|
44
|
+
const MAX_ARCHIVE_BYTES = 25 * 1024 * 1024;
|
|
45
|
+
const TEMPLATE_KEY_PATTERN = /^TEMPLATE:[a-z0-9][a-z0-9_]*@v\d+$/;
|
|
46
|
+
const FIELD_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
47
|
+
const TAR_BLOCK = 512;
|
|
48
|
+
export async function packCodepack(directory) {
|
|
49
|
+
const root = await lstat(directory).catch(() => null);
|
|
50
|
+
if (!root?.isDirectory()) {
|
|
51
|
+
throw new ValidationError('directory', `Not a directory: ${directory}`);
|
|
52
|
+
}
|
|
53
|
+
const files = [];
|
|
54
|
+
const skipped = [];
|
|
55
|
+
await collect(directory, directory, files, skipped);
|
|
56
|
+
const config = files.find((file) => file.path === 'config.yaml');
|
|
57
|
+
if (!config)
|
|
58
|
+
throw new ValidationError('config.yaml', 'Codepack folder must contain config.yaml');
|
|
59
|
+
if (!files.some((file) => file.path === 'process.py')) {
|
|
60
|
+
throw new ValidationError('process.py', 'Codepack folder must contain process.py');
|
|
61
|
+
}
|
|
62
|
+
const templateKey = validateCodepackConfig(config.content.toString('utf8'));
|
|
63
|
+
const archive = buildTarGz(files);
|
|
64
|
+
if (archive.byteLength > MAX_ARCHIVE_BYTES) {
|
|
65
|
+
throw new ValidationError('codepack', 'Packed codepack exceeds 25 MiB');
|
|
66
|
+
}
|
|
67
|
+
const hex = createHash('sha256').update(archive).digest('hex');
|
|
68
|
+
return {
|
|
69
|
+
templateKey,
|
|
70
|
+
agentRef: `codepack:sha256:${hex}`,
|
|
71
|
+
archiveSha256: `sha256:${hex}`,
|
|
72
|
+
archiveSizeBytes: archive.byteLength,
|
|
73
|
+
files: files.map((file) => file.path),
|
|
74
|
+
skipped,
|
|
75
|
+
archive,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Local checks that mirror the server's; the server stays the authority. */
|
|
79
|
+
export function validateCodepackConfig(configYaml) {
|
|
80
|
+
let data;
|
|
81
|
+
try {
|
|
82
|
+
data = parseYaml(configYaml);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
throw new ValidationError('config.yaml', `config.yaml is not valid YAML: ${error instanceof Error ? error.message : String(error)}`);
|
|
86
|
+
}
|
|
87
|
+
if (!isRecord(data) || Object.keys(data).length !== 1) {
|
|
88
|
+
throw new ValidationError('config.yaml', 'config.yaml must have exactly one TEMPLATE key');
|
|
89
|
+
}
|
|
90
|
+
const templateKey = Object.keys(data)[0];
|
|
91
|
+
if (!TEMPLATE_KEY_PATTERN.test(templateKey)) {
|
|
92
|
+
throw new ValidationError('config.yaml', `Template key must look like TEMPLATE:<snake_name>@v<N>, got ${templateKey}`);
|
|
93
|
+
}
|
|
94
|
+
const config = data[templateKey];
|
|
95
|
+
if (!isRecord(config))
|
|
96
|
+
throw new ValidationError('config.yaml', `${templateKey} must be a mapping`);
|
|
97
|
+
if (config.script_path !== undefined && config.script_path !== 'process.py') {
|
|
98
|
+
throw new ValidationError('config.yaml', 'script_path must be process.py');
|
|
99
|
+
}
|
|
100
|
+
for (const section of ['file_inputs', 'parameters']) {
|
|
101
|
+
const entries = config[section] ?? [];
|
|
102
|
+
if (!Array.isArray(entries)) {
|
|
103
|
+
throw new ValidationError('config.yaml', `${section} must be a list`);
|
|
104
|
+
}
|
|
105
|
+
for (const [index, entry] of entries.entries()) {
|
|
106
|
+
if (!isRecord(entry) || typeof entry.fieldName !== 'string') {
|
|
107
|
+
throw new ValidationError('config.yaml', `${section}[${index}] needs a fieldName`);
|
|
108
|
+
}
|
|
109
|
+
if (!FIELD_NAME_PATTERN.test(entry.fieldName)) {
|
|
110
|
+
throw new ValidationError('config.yaml', `${section}[${index}].fieldName must be a Python identifier`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return templateKey;
|
|
115
|
+
}
|
|
116
|
+
async function collect(root, directory, files, skipped) {
|
|
117
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
118
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
119
|
+
const absolute = join(directory, entry.name);
|
|
120
|
+
const path = relative(root, absolute).split(sep).join('/');
|
|
121
|
+
if (entry.name.startsWith('.')) {
|
|
122
|
+
skipped.push(entry.isDirectory() ? `${path}/` : path);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (entry.isSymbolicLink()) {
|
|
126
|
+
throw new ValidationError('codepack', `Symlinks are not allowed in a codepack: ${path}`);
|
|
127
|
+
}
|
|
128
|
+
if (entry.isDirectory()) {
|
|
129
|
+
if (EXCLUDED_DIRECTORIES.has(entry.name))
|
|
130
|
+
skipped.push(`${path}/`);
|
|
131
|
+
else
|
|
132
|
+
await collect(root, absolute, files, skipped);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (!entry.isFile())
|
|
136
|
+
continue;
|
|
137
|
+
if (!INCLUDED_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
|
138
|
+
skipped.push(path);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (Buffer.byteLength(path, 'utf8') > 100) {
|
|
142
|
+
throw new ValidationError('codepack', `Path is longer than 100 bytes: ${path}`);
|
|
143
|
+
}
|
|
144
|
+
files.push({ path, content: await readFile(absolute) });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Deterministic ustar: sorted paths, zero mtimes/owners, fixed modes. */
|
|
148
|
+
export function buildTarGz(files) {
|
|
149
|
+
const blocks = [];
|
|
150
|
+
for (const file of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
|
|
151
|
+
const header = Buffer.alloc(TAR_BLOCK);
|
|
152
|
+
header.write(file.path, 0, 100, 'utf8');
|
|
153
|
+
writeOctal(header, 0o644, 100, 8);
|
|
154
|
+
writeOctal(header, 0, 108, 8);
|
|
155
|
+
writeOctal(header, 0, 116, 8);
|
|
156
|
+
writeOctal(header, file.content.byteLength, 124, 12);
|
|
157
|
+
writeOctal(header, 0, 136, 12);
|
|
158
|
+
header.fill(0x20, 148, 156);
|
|
159
|
+
header.write('0', 156, 1, 'ascii');
|
|
160
|
+
header.write('ustar', 257, 6, 'ascii');
|
|
161
|
+
header.write('00', 263, 2, 'ascii');
|
|
162
|
+
let checksum = 0;
|
|
163
|
+
for (const byte of header)
|
|
164
|
+
checksum += byte;
|
|
165
|
+
writeOctal(header, checksum, 148, 8);
|
|
166
|
+
blocks.push(header, file.content);
|
|
167
|
+
const padding = (TAR_BLOCK - (file.content.byteLength % TAR_BLOCK)) % TAR_BLOCK;
|
|
168
|
+
if (padding > 0)
|
|
169
|
+
blocks.push(Buffer.alloc(padding));
|
|
170
|
+
}
|
|
171
|
+
blocks.push(Buffer.alloc(TAR_BLOCK * 2));
|
|
172
|
+
return gzipSync(Buffer.concat(blocks), { level: 9 });
|
|
173
|
+
}
|
|
174
|
+
function writeOctal(buffer, value, offset, length) {
|
|
175
|
+
buffer.write(value.toString(8).padStart(length - 1, '0'), offset, length - 1, 'ascii');
|
|
176
|
+
buffer[offset + length - 1] = 0;
|
|
177
|
+
}
|
|
178
|
+
function isRecord(value) {
|
|
179
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
180
|
+
}
|
|
181
|
+
//# sourceMappingURL=codepack.js.map
|
package/package.json
CHANGED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: codepack-authoring
|
|
3
|
+
description: Build, test, and publish a codepack — a Python agent that runs on files in a Zalos workflow's Codepack node — with `zl codepack`. Use when someone wants Python that processes uploaded or upstream files (reconciliations, billing, reports) to run inside a Zalos workflow.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Codepack Authoring
|
|
7
|
+
|
|
8
|
+
A codepack is a folder of Python that a Codepack node runs in a Mesh sandbox. It takes
|
|
9
|
+
files and string parameters, and writes output files that later nodes can use. You
|
|
10
|
+
build it locally, publish it with `zl`, and pin it in a workflow. No agent-studio
|
|
11
|
+
access is needed.
|
|
12
|
+
|
|
13
|
+
Select the region explicitly on every remote command (`--environment us-prod` or
|
|
14
|
+
`eu-prod`). Ask when it is not given; never infer it. Publishing needs a member role or above in
|
|
15
|
+
the selected team (`zl team list`, `zl team switch <tm_…>`).
|
|
16
|
+
|
|
17
|
+
## Workflow
|
|
18
|
+
|
|
19
|
+
1. **Scaffold:** `zl codepack init <snake_name>` creates a runnable folder. It is
|
|
20
|
+
offline and needs no login.
|
|
21
|
+
2. **Build:** edit `config.yaml` and `process.py`, using the contract below.
|
|
22
|
+
3. **Run locally:** run it on sample files exactly as the executor will:
|
|
23
|
+
```bash
|
|
24
|
+
cd <snake_name>
|
|
25
|
+
python process.py inputs/<file> --<parameter> <value> # writes ./outputs
|
|
26
|
+
python -m pytest tests
|
|
27
|
+
```
|
|
28
|
+
- **Inputs and tests:** put sample files in `inputs/` and tests in `tests/`.
|
|
29
|
+
Neither is published.
|
|
30
|
+
- **Matching the sandbox:** use Python 3.12 where you can, with the packages listed
|
|
31
|
+
under Runtime, plus `pytest`:
|
|
32
|
+
`python3.12 -m venv .venv && .venv/bin/pip install pandas openpyxl xlsxwriter pytest`.
|
|
33
|
+
- **Clean runs:** delete `outputs/` between runs, or set `OUTPUT_DIR` to a fresh
|
|
34
|
+
folder, so stale files don't hide a missing output.
|
|
35
|
+
4. **Validate:** `zl codepack validate <folder>` checks the config and prints the
|
|
36
|
+
`codepack:sha256:…` ref it would publish as, plus the files it packs and skips.
|
|
37
|
+
5. **Publish:**
|
|
38
|
+
- **First time:** `zl --environment <env> codepack publish <folder>` prints a
|
|
39
|
+
Codepack node to paste into workflow JSON (`zl workflow import`/`update`).
|
|
40
|
+
- **New version of an existing node:** use
|
|
41
|
+
`zl --environment <env> codepack publish <folder> --workflow <id> [--node <id-or-name>] --label "<what changed>"`.
|
|
42
|
+
It previews without `--apply`. With `--apply` it repins the node and saves a
|
|
43
|
+
named checkpoint.
|
|
44
|
+
6. **Make it live:** a workflow with a published version keeps running that version
|
|
45
|
+
until `zl --environment <env> workflow publish <id> --apply`. Then run it with
|
|
46
|
+
`zl workflow run <id>`, and check the result with `zl execution view <execution-id>`
|
|
47
|
+
and `zl file download <output-file-id> --output <path>`.
|
|
48
|
+
|
|
49
|
+
Always run locally and validate before publishing. After publishing, run the workflow
|
|
50
|
+
once on real inputs and check the outputs before telling the user it works.
|
|
51
|
+
|
|
52
|
+
## The contract
|
|
53
|
+
|
|
54
|
+
### `config.yaml`
|
|
55
|
+
|
|
56
|
+
The file has exactly one top-level key, `TEMPLATE:<snake_name>@v<N>`:
|
|
57
|
+
|
|
58
|
+
```yaml
|
|
59
|
+
TEMPLATE:cash_summary@v1:
|
|
60
|
+
canonical_key: TEMPLATE:cash_summary@v1
|
|
61
|
+
name: 'Cash Summary'
|
|
62
|
+
description: What the agent does, for the node form
|
|
63
|
+
script_path: process.py # must be process.py
|
|
64
|
+
file_inputs: # files; required defaults to true
|
|
65
|
+
- fieldName: source # Python identifier, unique
|
|
66
|
+
fieldLabel: Source file
|
|
67
|
+
fieldType: file
|
|
68
|
+
acceptFileTypes: [.csv, .xlsx]
|
|
69
|
+
required: true
|
|
70
|
+
parameters: # strings; required defaults to false
|
|
71
|
+
- fieldName: period_end
|
|
72
|
+
fieldLabel: Period end
|
|
73
|
+
fieldType: date # date | text | number | boolean; add options: for a select
|
|
74
|
+
format: YYYY-MM-DD
|
|
75
|
+
required: false
|
|
76
|
+
output_contract:
|
|
77
|
+
files:
|
|
78
|
+
- fieldName: summary # the output's logicalName downstream
|
|
79
|
+
fieldLabel: Summary
|
|
80
|
+
fieldType: file
|
|
81
|
+
required: true
|
|
82
|
+
fileType: csv # must match the written file's extension
|
|
83
|
+
resources:
|
|
84
|
+
timeoutSeconds: 600 # optional; at least 30, capped at 1800
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
- **Node form:** the workflow editor builds it from `file_inputs` and `parameters`.
|
|
88
|
+
Only declared parameters are accepted.
|
|
89
|
+
- **Required parameters:** a run without a `required: true` parameter fails before
|
|
90
|
+
`process.py` starts. Still mirror it with `required=True` in argparse, so local runs
|
|
91
|
+
fail the same way.
|
|
92
|
+
- **`format`:** only a hint for the form. Values can be typed or come from
|
|
93
|
+
expressions, so parse and validate them in `process.py`, and fail with a clear
|
|
94
|
+
message.
|
|
95
|
+
- **Other keys:** `category` (and agent-studio keys such as `output_directory`) are
|
|
96
|
+
optional metadata that the runtime ignores. Outputs always go to `OUTPUT_DIR`.
|
|
97
|
+
|
|
98
|
+
### How `process.py` is called
|
|
99
|
+
|
|
100
|
+
The executor runs `python process.py …` from the codepack folder:
|
|
101
|
+
|
|
102
|
+
- **Required file inputs:** positional arguments, in `file_inputs` order.
|
|
103
|
+
- **Optional file inputs:** `--<fieldName> <path>`, only when provided.
|
|
104
|
+
- **Parameters:** `--<fieldName> <value>`, always as strings. A `boolean` parameter
|
|
105
|
+
is a bare `--<fieldName>` flag, passed only when true.
|
|
106
|
+
- **Output folder:** `OUTPUT_DIR` is set to the folder for outputs.
|
|
107
|
+
- **Input paths:** each file arrives as `/mesh/inputs/<fieldName>/<original file name>`,
|
|
108
|
+
so the name and extension are kept. Choosing a CSV or Excel reader by suffix works.
|
|
109
|
+
|
|
110
|
+
Use `argparse` with exactly these shapes. Positional names must match the `fieldName`s.
|
|
111
|
+
|
|
112
|
+
### Outputs
|
|
113
|
+
|
|
114
|
+
- **Write and register:** write each output under `get_output_dir()`, then call
|
|
115
|
+
`register_output("<output fieldName>", path)`. Unregistered files are not matched
|
|
116
|
+
to `output_contract`.
|
|
117
|
+
- **Helpers:** both come from the scaffold's `codepack_runtime.py`. Keep that file in
|
|
118
|
+
the folder; it is published with the codepack.
|
|
119
|
+
- **Progress:** `step_begin(step, of, label)` and `step_detail(text)` show as progress
|
|
120
|
+
on the run in Mesh. Use them for the main phases.
|
|
121
|
+
- **Failure:** exit non-zero, or raise, to fail the run. Put a clear message on stderr
|
|
122
|
+
or in the exception.
|
|
123
|
+
- **File names:** each output is saved to the node's `outputFolderPath` under the name
|
|
124
|
+
you wrote. If that name already exists there, Mesh saves a numbered copy such as
|
|
125
|
+
`summary (2).csv`, unless the node's Override Existing File option is on. Include
|
|
126
|
+
the period in the name when runs should coexist.
|
|
127
|
+
- **Determinism:**
|
|
128
|
+
- **Row order:** sort before writing. pandas `groupby`/`unique` and polars
|
|
129
|
+
`unique`/`group_by` without `maintain_order=True` can change row order between
|
|
130
|
+
runs.
|
|
131
|
+
- **Workbook bytes:** `.xlsx` files carry creation timestamps, so two identical runs
|
|
132
|
+
differ in bytes but not in cell content. If you need byte-identical workbooks, write
|
|
133
|
+
them with xlsxwriter and set a fixed creation date
|
|
134
|
+
(`workbook.set_properties({"created": <fixed datetime>})`).
|
|
135
|
+
|
|
136
|
+
## Runtime
|
|
137
|
+
|
|
138
|
+
- **Python and packages:** Python 3.12, with pandas 2, polars, openpyxl, xlrd,
|
|
139
|
+
xlsxwriter, fastexcel, lxml, pypdf, python-dateutil, PyYAML, jsonschema, pillow and
|
|
140
|
+
httpx. You cannot install other packages. Use the standard library otherwise.
|
|
141
|
+
- **What the agent gets:** its input files, parameters and `OUTPUT_DIR`. Do not read
|
|
142
|
+
credentials or environment secrets, or call external services, unless the user
|
|
143
|
+
confirms the workflow is designed for it.
|
|
144
|
+
- **Sibling modules:** `process.py` can import other `.py` files in the folder.
|
|
145
|
+
agent-studio `shared_modules` are not available.
|
|
146
|
+
|
|
147
|
+
### What gets published
|
|
148
|
+
|
|
149
|
+
- **Packed:** `.py`, `.yaml`, `.yml`, `.json`, `.csv`, `.txt`, `.xlsx`, `.xls`,
|
|
150
|
+
`.xlsb` and `.pptx` files, including reference files the code reads at run time
|
|
151
|
+
(for example under `fixtures/`).
|
|
152
|
+
- **Skipped:** `tests/`, `inputs/`, `outputs/`, `private/`, `private_validation/`,
|
|
153
|
+
`__pycache__/`, dotfiles, virtualenvs and other file types.
|
|
154
|
+
- **Limits:** symlinks are refused, paths must be at most 100 bytes, and the archive
|
|
155
|
+
must be at most 25 MiB.
|
|
156
|
+
|
|
157
|
+
The ref is a hash of the packed bytes. The same source always gives the same ref, and
|
|
158
|
+
any change gives a new one.
|
|
159
|
+
|
|
160
|
+
## Using it in a workflow
|
|
161
|
+
|
|
162
|
+
```json
|
|
163
|
+
{
|
|
164
|
+
"name": "Cash Summary",
|
|
165
|
+
"type": "mesh-nodes-base.codepack",
|
|
166
|
+
"typeVersion": 1,
|
|
167
|
+
"parameters": {
|
|
168
|
+
"codepackRef": "codepack:sha256:<64 hex>",
|
|
169
|
+
"fileInputs": "{\"source\": \"mesh://team-files/<file-id>\"}",
|
|
170
|
+
"parameters": "{\"period_end\": \"2026-10-31\"}",
|
|
171
|
+
"outputFolderPath": "/Reports/Cash Summary"
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
- **`codepackRef`:** must be a literal ref, never an expression. It is resolved
|
|
177
|
+
before the run starts.
|
|
178
|
+
- **Chaining:** to feed an upstream node's output in, set a file input to an
|
|
179
|
+
expression such as
|
|
180
|
+
`{{ $json.outputFiles.find((file) => file.logicalName === 'summary').fileRef }}`.
|
|
181
|
+
Each output appears in `outputFiles` with its `logicalName` and `fileRef`.
|
|
182
|
+
- **Outputs:** they are saved to `outputFolderPath` in Team Files.
|