@zalosai/zalos-cli 0.2.29 → 0.2.31
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/dist/client.js +8 -0
- package/dist/commands/codepack.js +94 -14
- package/dist/commands/onboard-input.js +138 -27
- package/dist/commands/registry-sample.js +13 -3
- package/dist/utils/codepack.js +117 -8
- package/package.json +1 -1
- package/skills/codepack-authoring/SKILL.md +12 -1
package/dist/client.js
CHANGED
|
@@ -70,6 +70,12 @@ async function request(options, tokenOverride) {
|
|
|
70
70
|
}
|
|
71
71
|
if (response.status === 204)
|
|
72
72
|
return undefined;
|
|
73
|
+
if (options.binaryResponse) {
|
|
74
|
+
return {
|
|
75
|
+
body: Buffer.from(await response.arrayBuffer()),
|
|
76
|
+
headers: response.headers,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
73
79
|
return response.json();
|
|
74
80
|
}
|
|
75
81
|
export const client = {
|
|
@@ -77,6 +83,8 @@ export const client = {
|
|
|
77
83
|
post: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
78
84
|
postForm: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
79
85
|
postBinary: (path, body, options) => request({ method: 'POST', path, body, ...options }),
|
|
86
|
+
putBinary: (path, body, options) => request({ method: 'PUT', path, body, ...options }),
|
|
87
|
+
getBinary: (path, options) => request({ method: 'GET', path, binaryResponse: true, ...options }),
|
|
80
88
|
put: (path, body) => request({ method: 'PUT', path, body }),
|
|
81
89
|
patch: (path, body) => request({ method: 'PATCH', path, body }),
|
|
82
90
|
delete: (path) => request({ method: 'DELETE', path }),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { client } from '../client.js';
|
|
2
|
-
import { packCodepack } from '../utils/codepack.js';
|
|
2
|
+
import { packCodepack, packCodepackSource, unpackCodepack, } from '../utils/codepack.js';
|
|
3
3
|
import { scaffoldCodepack } from '../utils/codepack-scaffold.js';
|
|
4
4
|
import { ApiError, ValidationError } from '../utils/errors.js';
|
|
5
5
|
import { printJson } from '../utils/output.js';
|
|
@@ -20,6 +20,37 @@ function summary(codepack) {
|
|
|
20
20
|
skipped: codepack.skipped,
|
|
21
21
|
};
|
|
22
22
|
}
|
|
23
|
+
function publishSummary(packed, options) {
|
|
24
|
+
return {
|
|
25
|
+
...summary(packed.codepack),
|
|
26
|
+
parentRef: options.parent ?? null,
|
|
27
|
+
label: options.label?.trim() || null,
|
|
28
|
+
sourceFiles: packed.source.files,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function lineageQuery(options) {
|
|
32
|
+
const query = {};
|
|
33
|
+
if (options.parent !== undefined)
|
|
34
|
+
query.parent = options.parent;
|
|
35
|
+
const label = options.label?.trim();
|
|
36
|
+
if (label)
|
|
37
|
+
query.label = label;
|
|
38
|
+
return query;
|
|
39
|
+
}
|
|
40
|
+
function assertCodepackRef(field, ref) {
|
|
41
|
+
if (!CODEPACK_REF_PATTERN.test(ref)) {
|
|
42
|
+
throw new ValidationError(field, 'Expected codepack:sha256:<64 hex>');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async function packForPublish(directory, options) {
|
|
46
|
+
if (options.parent !== undefined)
|
|
47
|
+
assertCodepackRef('parent', options.parent);
|
|
48
|
+
const codepack = await packCodepack(directory);
|
|
49
|
+
if (options.parent === codepack.agentRef) {
|
|
50
|
+
throw new ValidationError('parent', 'A codepack cannot be its own parent');
|
|
51
|
+
}
|
|
52
|
+
return { codepack, source: await packCodepackSource(directory) };
|
|
53
|
+
}
|
|
23
54
|
function templateName(templateKey) {
|
|
24
55
|
return templateKey.slice('TEMPLATE:'.length).replace(/@v\d+$/, '');
|
|
25
56
|
}
|
|
@@ -110,15 +141,22 @@ async function verifyCheckpoint(workflowId, checkpoint, nodeId, agentRef) {
|
|
|
110
141
|
throw new ApiError(409, `Checkpoint ${checkpoint.id} does not pin ${agentRef}; the workflow changed while publishing. Re-run the command.`);
|
|
111
142
|
}
|
|
112
143
|
}
|
|
113
|
-
|
|
144
|
+
/** Publishes the runtime archive with its lineage, then the author's full source. */
|
|
145
|
+
async function uploadCodepack(packed, options) {
|
|
146
|
+
const { codepack, source } = packed;
|
|
114
147
|
const published = dataRow(await client.postBinary('/codepacks', codepack.archive, {
|
|
115
148
|
contentType: 'application/gzip',
|
|
116
149
|
timeoutMs: PUBLISH_TIMEOUT_MS,
|
|
150
|
+
query: lineageQuery(options),
|
|
117
151
|
}));
|
|
118
152
|
if (published.agentRef !== codepack.agentRef) {
|
|
119
153
|
// The server hashes the bytes it stored; a mismatch means they changed in transit.
|
|
120
154
|
throw new ValidationError('codepack', 'Server stored a different archive than was packed');
|
|
121
155
|
}
|
|
156
|
+
await client.putBinary(`/codepacks/${codepack.agentRef}/source`, source.archive, {
|
|
157
|
+
contentType: 'application/gzip',
|
|
158
|
+
timeoutMs: PUBLISH_TIMEOUT_MS,
|
|
159
|
+
});
|
|
122
160
|
return published;
|
|
123
161
|
}
|
|
124
162
|
export async function validateCodepackAction(directory) {
|
|
@@ -141,7 +179,8 @@ export async function initCodepackAction(name, options) {
|
|
|
141
179
|
});
|
|
142
180
|
}
|
|
143
181
|
async function publishAndPinAction(directory, workflowId, options) {
|
|
144
|
-
const
|
|
182
|
+
const packed = await packForPublish(directory, options);
|
|
183
|
+
const { codepack } = packed;
|
|
145
184
|
const pin = await planCodepackPin(workflowId, codepack, options);
|
|
146
185
|
const changed = pin.previousRef !== codepack.agentRef;
|
|
147
186
|
const target = {
|
|
@@ -155,13 +194,13 @@ async function publishAndPinAction(directory, workflowId, options) {
|
|
|
155
194
|
if (!options.apply || options.dryRun) {
|
|
156
195
|
printJson({
|
|
157
196
|
dryRun: true,
|
|
158
|
-
codepack:
|
|
197
|
+
codepack: publishSummary(packed, options),
|
|
159
198
|
workflow: target,
|
|
160
199
|
checkpoint: { name: pin.label, description: checkpointDescription(pin, codepack.agentRef) },
|
|
161
200
|
});
|
|
162
201
|
return;
|
|
163
202
|
}
|
|
164
|
-
const published = await uploadCodepack(
|
|
203
|
+
const published = await uploadCodepack(packed, options);
|
|
165
204
|
let saved = pin.draft;
|
|
166
205
|
if (changed) {
|
|
167
206
|
pin.parameters.codepackRef = codepack.agentRef;
|
|
@@ -186,15 +225,21 @@ export async function publishCodepackAction(directory, options = {}) {
|
|
|
186
225
|
await publishAndPinAction(directory, options.workflow, options);
|
|
187
226
|
return;
|
|
188
227
|
}
|
|
189
|
-
if (options.node !== undefined
|
|
190
|
-
throw new ValidationError('workflow', '--node
|
|
228
|
+
if (options.node !== undefined) {
|
|
229
|
+
throw new ValidationError('workflow', '--node needs --workflow');
|
|
191
230
|
}
|
|
192
|
-
const
|
|
231
|
+
const packed = await packForPublish(directory, options);
|
|
232
|
+
const { codepack } = packed;
|
|
193
233
|
if (options.dryRun) {
|
|
194
|
-
printJson({
|
|
234
|
+
printJson({
|
|
235
|
+
dryRun: true,
|
|
236
|
+
method: 'POST',
|
|
237
|
+
path: '/codepacks',
|
|
238
|
+
codepack: publishSummary(packed, options),
|
|
239
|
+
});
|
|
195
240
|
return;
|
|
196
241
|
}
|
|
197
|
-
const published = await uploadCodepack(
|
|
242
|
+
const published = await uploadCodepack(packed, options);
|
|
198
243
|
printJson({
|
|
199
244
|
data: {
|
|
200
245
|
...published,
|
|
@@ -204,11 +249,36 @@ export async function publishCodepackAction(directory, options = {}) {
|
|
|
204
249
|
});
|
|
205
250
|
}
|
|
206
251
|
export async function viewCodepackManifestAction(agentRef) {
|
|
207
|
-
|
|
208
|
-
throw new ValidationError('agentRef', 'Expected codepack:sha256:<64 hex>');
|
|
209
|
-
}
|
|
252
|
+
assertCodepackRef('agentRef', agentRef);
|
|
210
253
|
printJson({ data: dataRow(await client.get(`/codepacks/${agentRef}/manifest`)) });
|
|
211
254
|
}
|
|
255
|
+
export async function viewCodepackInfoAction(agentRef) {
|
|
256
|
+
assertCodepackRef('agentRef', agentRef);
|
|
257
|
+
printJson({ data: dataRow(await client.get(`/codepacks/${agentRef}`)) });
|
|
258
|
+
}
|
|
259
|
+
/** Download a published codepack's source into a folder to edit, test and republish. */
|
|
260
|
+
export async function fetchCodepackSourceAction(agentRef, options) {
|
|
261
|
+
assertCodepackRef('agentRef', agentRef);
|
|
262
|
+
const directory = options.output ?? agentRef.slice('codepack:sha256:'.length, 'codepack:sha256:'.length + 12);
|
|
263
|
+
const info = dataRow(await client.get(`/codepacks/${agentRef}`));
|
|
264
|
+
const { body, headers } = await client.getBinary(`/codepacks/${agentRef}/source`, {
|
|
265
|
+
timeoutMs: PUBLISH_TIMEOUT_MS,
|
|
266
|
+
});
|
|
267
|
+
const files = await unpackCodepack(body, directory);
|
|
268
|
+
printJson({
|
|
269
|
+
data: {
|
|
270
|
+
...info,
|
|
271
|
+
source: headers.get('x-codepack-source') ?? info.source,
|
|
272
|
+
directory,
|
|
273
|
+
files,
|
|
274
|
+
next: [
|
|
275
|
+
`cd ${JSON.stringify(directory)}`,
|
|
276
|
+
'python -m pytest tests',
|
|
277
|
+
`zl codepack publish ${JSON.stringify(directory)} --parent ${agentRef} --label "<what changed>"`,
|
|
278
|
+
],
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
}
|
|
212
282
|
export function registerCodepackCommand(program) {
|
|
213
283
|
const cmd = program
|
|
214
284
|
.command('codepack')
|
|
@@ -227,10 +297,20 @@ export function registerCodepackCommand(program) {
|
|
|
227
297
|
.description('Publish a codepack folder to the selected team; with --workflow, repin its Codepack node and save a named checkpoint')
|
|
228
298
|
.option('--workflow <id>', 'Repin a Codepack node in this workflow (needs --apply)')
|
|
229
299
|
.option('--node <id-or-name>', 'Codepack node to repin; optional when the workflow has one')
|
|
230
|
-
.option('--
|
|
300
|
+
.option('--parent <ref>', 'Codepack ref this version was changed from (recorded as lineage)')
|
|
301
|
+
.option('--label <text>', 'Label recorded on the codepack, e.g. "threshold 5000"; with --workflow also the checkpoint name')
|
|
231
302
|
.option('--apply', 'With --workflow: publish, save the draft and create the checkpoint')
|
|
232
303
|
.option('--dry-run', 'With --workflow: preview the repin without publishing')
|
|
233
304
|
.action(async (directory, o) => action(() => publishCodepackAction(directory, o)));
|
|
305
|
+
cmd
|
|
306
|
+
.command('info <agentRef>')
|
|
307
|
+
.description('Show a published codepack: template, parent ref, label and publish time')
|
|
308
|
+
.action(async (agentRef) => action(() => viewCodepackInfoAction(agentRef)));
|
|
309
|
+
cmd
|
|
310
|
+
.command('source <agentRef>')
|
|
311
|
+
.description('Download a published codepack folder, tests included, to edit and republish')
|
|
312
|
+
.option('--output <directory>', 'Empty or new folder to write (default: ./<short hash>)')
|
|
313
|
+
.action(async (agentRef, o) => action(() => fetchCodepackSourceAction(agentRef, o)));
|
|
234
314
|
cmd
|
|
235
315
|
.command('manifest <agentRef>')
|
|
236
316
|
.description('Show the runtime manifest Mesh derived for a published codepack')
|
|
@@ -5,11 +5,11 @@ import { readProfile } from '../credentials.js';
|
|
|
5
5
|
import { printJson } from '../utils/output.js';
|
|
6
6
|
import { action, dataRow, resourceId } from '../utils/product-api.js';
|
|
7
7
|
import { profileSample } from './registry-sample.js';
|
|
8
|
-
function matchingHeaders(sample, spec) {
|
|
8
|
+
function matchingHeaders(sample, spec, names) {
|
|
9
9
|
const parser = spec.parser;
|
|
10
10
|
if (!parser ||
|
|
11
11
|
parser.kind !== sample.format.kind ||
|
|
12
|
-
sample.headerRow !== sample.registryHeaderRow)
|
|
12
|
+
(!names && sample.headerRow !== sample.registryHeaderRow))
|
|
13
13
|
return;
|
|
14
14
|
if (sample.format.kind === 'xlsx' && (parser.sheet ?? sample.firstSheet) !== sample.format.sheet)
|
|
15
15
|
return;
|
|
@@ -28,7 +28,7 @@ function matchingHeaders(sample, spec) {
|
|
|
28
28
|
.replace(/[^a-z0-9]+/g, '_')
|
|
29
29
|
.replace(/^_+|_+$/g, '') || 'col';
|
|
30
30
|
const headers = new Map();
|
|
31
|
-
for (const
|
|
31
|
+
for (const fieldName of names ?? sample.columns.map((c) => c.fieldName)) {
|
|
32
32
|
const base = snake(fieldName);
|
|
33
33
|
let key = base;
|
|
34
34
|
for (let n = 2; headers.has(key); n++)
|
|
@@ -60,6 +60,14 @@ function matchingHeaders(sample, spec) {
|
|
|
60
60
|
]);
|
|
61
61
|
return matched.size ? [...matched] : undefined;
|
|
62
62
|
}
|
|
63
|
+
function suggestedWindow(field) {
|
|
64
|
+
const words = field.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
|
|
65
|
+
if (/(?:^|_)(?:subsequent|next|following)_(?:month|period)(?:_|$)/.test(words))
|
|
66
|
+
return 'next_period';
|
|
67
|
+
if (/(?:^|_)(?:previous|prior|last)_(?:month|period)(?:_|$)/.test(words))
|
|
68
|
+
return 'prior_period';
|
|
69
|
+
return 'period';
|
|
70
|
+
}
|
|
63
71
|
export async function onboardInput(o) {
|
|
64
72
|
const ref = o.teamId ?? readProfile(process.env.ZL_PROFILE ?? 'default')?.team?.id;
|
|
65
73
|
if (!ref)
|
|
@@ -95,15 +103,19 @@ export async function onboardInput(o) {
|
|
|
95
103
|
'');
|
|
96
104
|
};
|
|
97
105
|
try {
|
|
106
|
+
const publish = async (request, message, details) => {
|
|
107
|
+
const path = '/developer/finance/registry/onboard-input';
|
|
108
|
+
const options = { timeoutMs: 120_000 };
|
|
109
|
+
const preview = dataRow(await client.post(path, request, options));
|
|
110
|
+
printJson({ ...preview, ...details });
|
|
111
|
+
if (o.preview || (await ask(message + ' Type publish to confirm', 'cancel')) !== 'publish')
|
|
112
|
+
return;
|
|
113
|
+
if (typeof preview.confirmation !== 'string')
|
|
114
|
+
throw new Error('Mesh did not return a confirmed proposal digest');
|
|
115
|
+
printJson(dataRow(await client.post(path, { ...request, confirm: preview.confirmation }, options)));
|
|
116
|
+
};
|
|
98
117
|
const previous = input.binding;
|
|
99
118
|
const sources = registry.sources.filter((s) => !s.retired).map((s) => s.key);
|
|
100
|
-
const source = o.source ??
|
|
101
|
-
previous?.source ??
|
|
102
|
-
(sources.length === 1
|
|
103
|
-
? sources[0]
|
|
104
|
-
: await ask('Choose the source (' + sources.join(', ') + ')'));
|
|
105
|
-
if (!sources.includes(source))
|
|
106
|
-
throw new Error('Choose an existing active source');
|
|
107
119
|
const current = registry.datasets.find((d) => d.key === previous?.datasetKey);
|
|
108
120
|
let sample = await profileSample(o.sample, o, ask, current?.spec.parser?.sheet, input.input.maxFileSizeMb, current?.spec.parser?.headerContains);
|
|
109
121
|
const mime = sample.format.kind === 'csv'
|
|
@@ -112,6 +124,115 @@ export async function onboardInput(o) {
|
|
|
112
124
|
if (input.input.acceptedContentTypes?.length &&
|
|
113
125
|
!input.input.acceptedContentTypes.some((type) => type === mime || type === '*/*' || type === mime.split('/')[0] + '/*'))
|
|
114
126
|
throw new Error('Sample content type does not match the deployed input');
|
|
127
|
+
if (!previous && o.rules !== 'table') {
|
|
128
|
+
if (registry.latestVersion?.version !== input.registryVersion)
|
|
129
|
+
throw new Error('Registry changed while inspecting this input. Run onboarding again.');
|
|
130
|
+
const matches = registry.datasets.flatMap((dataset) => {
|
|
131
|
+
if (dataset.retired ||
|
|
132
|
+
!dataset.spec.contract?.sha256 ||
|
|
133
|
+
!sources.includes(dataset.source) ||
|
|
134
|
+
(o.source && o.source !== dataset.source) ||
|
|
135
|
+
(o.datasetKey && o.datasetKey !== dataset.key))
|
|
136
|
+
return [];
|
|
137
|
+
const header = sample.registryHeader(dataset.spec.parser?.headerContains);
|
|
138
|
+
if (!header)
|
|
139
|
+
return [];
|
|
140
|
+
const headers = matchingHeaders(sample, dataset.spec, header.names);
|
|
141
|
+
return headers
|
|
142
|
+
? [
|
|
143
|
+
{
|
|
144
|
+
datasetKey: dataset.key,
|
|
145
|
+
source: dataset.source,
|
|
146
|
+
matchedHeaders: headers,
|
|
147
|
+
headerRow: header.row,
|
|
148
|
+
contractSha256: dataset.spec.contract.sha256,
|
|
149
|
+
},
|
|
150
|
+
]
|
|
151
|
+
: [];
|
|
152
|
+
});
|
|
153
|
+
if (matches.length) {
|
|
154
|
+
const context = {
|
|
155
|
+
action: 'suggest_existing',
|
|
156
|
+
teamId,
|
|
157
|
+
workflowId,
|
|
158
|
+
field,
|
|
159
|
+
registryVersion: input.registryVersion,
|
|
160
|
+
previousBinding: null,
|
|
161
|
+
published: false,
|
|
162
|
+
};
|
|
163
|
+
if (matches.length > 1 && !terminal) {
|
|
164
|
+
printJson({
|
|
165
|
+
...context,
|
|
166
|
+
candidates: matches,
|
|
167
|
+
confirmationRequired: ['dataset', 'window'],
|
|
168
|
+
message: 'Multiple datasets match. Choose one with --dataset-key.',
|
|
169
|
+
});
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const key = matches.length === 1
|
|
173
|
+
? matches[0].datasetKey
|
|
174
|
+
: await ask('Choose a matching dataset (' + matches.map((m) => m.datasetKey).join(', ') + ')');
|
|
175
|
+
const match = matches.find((m) => m.datasetKey === key);
|
|
176
|
+
if (!match)
|
|
177
|
+
throw new Error('Choose one of the matching datasets');
|
|
178
|
+
const windowHint = suggestedWindow(field);
|
|
179
|
+
const prompt = 'Use ' +
|
|
180
|
+
key +
|
|
181
|
+
' for ' +
|
|
182
|
+
field +
|
|
183
|
+
' in which report window (period, prior_period, next_period)?';
|
|
184
|
+
const window = o.window ?? (terminal ? await ask(prompt, windowHint) : windowHint);
|
|
185
|
+
if (!['period', 'prior_period', 'next_period'].includes(window))
|
|
186
|
+
throw new Error('Choose period, prior_period or next_period');
|
|
187
|
+
const confirmed = Boolean(o.window || terminal);
|
|
188
|
+
const details = {
|
|
189
|
+
...context,
|
|
190
|
+
...match,
|
|
191
|
+
format: sample.format,
|
|
192
|
+
proposedBinding: {
|
|
193
|
+
fieldName: field,
|
|
194
|
+
datasetKey: key,
|
|
195
|
+
window,
|
|
196
|
+
required: input.input.required,
|
|
197
|
+
},
|
|
198
|
+
windowConfirmed: confirmed,
|
|
199
|
+
confirmationRequired: confirmed ? [] : ['window'],
|
|
200
|
+
message: confirmed ? 'Review the proposed input binding.' : prompt,
|
|
201
|
+
};
|
|
202
|
+
if (o.preview || !confirmed) {
|
|
203
|
+
printJson(details);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (sample.headerRow !== match.headerRow)
|
|
207
|
+
sample = await profileSample(o.sample, { ...o, ...sample.format, headerRow: String(match.headerRow) }, ask, undefined, input.input.maxFileSizeMb);
|
|
208
|
+
await publish({
|
|
209
|
+
teamId,
|
|
210
|
+
workflowId,
|
|
211
|
+
field,
|
|
212
|
+
authoredDate: new Date().toISOString().slice(0, 10),
|
|
213
|
+
expectedVersion: input.registryVersion,
|
|
214
|
+
workflowVersionId: input.workflowVersionId,
|
|
215
|
+
archiveSha256: input.package.archiveSha256,
|
|
216
|
+
existingContractSha256: match.contractSha256,
|
|
217
|
+
format: sample.format,
|
|
218
|
+
columns: sample.columns,
|
|
219
|
+
sizeBytes: sample.sizeBytes,
|
|
220
|
+
source: match.source,
|
|
221
|
+
datasetKey: key,
|
|
222
|
+
name: key,
|
|
223
|
+
window,
|
|
224
|
+
rules: 'inherit',
|
|
225
|
+
}, 'Bind ' + key + ' to ' + field + ' for ' + window + ' and publish?', { matchedHeaders: match.matchedHeaders, headerRow: match.headerRow });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const source = o.source ??
|
|
230
|
+
previous?.source ??
|
|
231
|
+
(sources.length === 1
|
|
232
|
+
? sources[0]
|
|
233
|
+
: await ask('Choose the source (' + sources.join(', ') + ')'));
|
|
234
|
+
if (!sources.includes(source))
|
|
235
|
+
throw new Error('Choose an existing active source');
|
|
115
236
|
if (previous &&
|
|
116
237
|
current &&
|
|
117
238
|
!current.retired &&
|
|
@@ -179,7 +300,7 @@ export async function onboardInput(o) {
|
|
|
179
300
|
}
|
|
180
301
|
const window = o.window ??
|
|
181
302
|
previous?.window ??
|
|
182
|
-
(await ask('Input window (period
|
|
303
|
+
(await ask('Input window (period, prior_period, next_period)', 'period'));
|
|
183
304
|
const compatible = current?.spec.parser?.kind === sample.format.kind;
|
|
184
305
|
const rules = o.rules ??
|
|
185
306
|
(compatible
|
|
@@ -202,23 +323,13 @@ export async function onboardInput(o) {
|
|
|
202
323
|
window,
|
|
203
324
|
rules,
|
|
204
325
|
};
|
|
205
|
-
const path = '/developer/finance/registry/onboard-input';
|
|
206
|
-
const preview = dataRow(await client.post(path, request));
|
|
207
|
-
printJson({
|
|
208
|
-
...preview,
|
|
209
|
-
headerRow: sample.headerRow,
|
|
210
|
-
possibleExcelDates: sample.ambiguousDates,
|
|
211
|
-
});
|
|
212
|
-
if (o.preview)
|
|
213
|
-
return;
|
|
214
326
|
const message = previous
|
|
215
327
|
? 'Replace ' + previous.datasetKey + ' with ' + datasetKey + ' for ' + field + ' and publish?'
|
|
216
328
|
: 'Bind ' + datasetKey + ' to ' + field + ' and publish?';
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
printJson(dataRow(await client.post(path, { ...request, confirm: preview.confirmation })));
|
|
329
|
+
await publish(request, message, {
|
|
330
|
+
headerRow: sample.headerRow,
|
|
331
|
+
possibleExcelDates: sample.ambiguousDates,
|
|
332
|
+
});
|
|
222
333
|
}
|
|
223
334
|
finally {
|
|
224
335
|
terminal?.close();
|
|
@@ -233,9 +344,9 @@ export function registerOnboardInput(registry) {
|
|
|
233
344
|
.requiredOption('--field <name>', 'Existing file input')
|
|
234
345
|
.option('--team-id <ref>', 'Team (defaults to selected team)')
|
|
235
346
|
.option('--source <key>', 'Existing registry source')
|
|
236
|
-
.option('--dataset-key <key>', '
|
|
347
|
+
.option('--dataset-key <key>', 'Select a matching dataset for an unbound input, or choose a new dataset key')
|
|
237
348
|
.option('--rules <mode>', 'inherit compatible rules from the bound dataset, or table')
|
|
238
|
-
.option('--window <window>', 'period
|
|
349
|
+
.option('--window <window>', 'Input window (period, prior_period, next_period)')
|
|
239
350
|
.option('--sheet <name>', 'Workbook worksheet')
|
|
240
351
|
.option('--header-row <number>', 'One-based sample header row')
|
|
241
352
|
.option('--delimiter <character>', 'CSV delimiter')
|
|
@@ -104,9 +104,18 @@ export async function profileSample(path, options, ask, preferredSheet, maxMb, h
|
|
|
104
104
|
const widths = rows
|
|
105
105
|
.slice(0, 60)
|
|
106
106
|
.map((row) => row.filter((cell) => String(cell ?? '').trim()).length);
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
107
|
+
const widestIndex = widths.indexOf(Math.max(...widths));
|
|
108
|
+
const findHeader = (anchors) => anchors.length
|
|
109
|
+
? probe.findIndex((headers) => anchors.every((anchor) => headers.has(anchor.trim().toLowerCase())))
|
|
110
|
+
: widestIndex;
|
|
111
|
+
const registryHeader = (anchors = []) => {
|
|
112
|
+
const at = findHeader(anchors);
|
|
113
|
+
if (at < 0 || (options.headerRow !== undefined && at + 1 !== Number(options.headerRow)))
|
|
114
|
+
return;
|
|
115
|
+
const names = rows[at].map((cell) => String(cell ?? '').trim());
|
|
116
|
+
return { row: at + 1, names };
|
|
117
|
+
};
|
|
118
|
+
const registryIndex = findHeader(headerContains);
|
|
110
119
|
const inferred = headerContains.length && registryIndex >= 0 && registryIndex < 50
|
|
111
120
|
? registryIndex
|
|
112
121
|
: candidates.sort((a, b) => b.width - a.width)[0]?.index;
|
|
@@ -161,6 +170,7 @@ export async function profileSample(path, options, ask, preferredSheet, maxMb, h
|
|
|
161
170
|
sizeBytes,
|
|
162
171
|
headerRow: index + 1,
|
|
163
172
|
registryHeaderRow: registryIndex + 1,
|
|
173
|
+
registryHeader,
|
|
164
174
|
firstSheet,
|
|
165
175
|
defaultDelimiter,
|
|
166
176
|
};
|
package/dist/utils/codepack.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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';
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { gunzipSync, gzipSync } from 'node:zlib';
|
|
5
5
|
import { parse as parseYaml } from 'yaml';
|
|
6
6
|
import { ValidationError } from './errors.js';
|
|
7
7
|
/**
|
|
@@ -15,6 +15,10 @@ import { ValidationError } from './errors.js';
|
|
|
15
15
|
* outputs, private validation data, caches and dotfiles stay on the author's
|
|
16
16
|
* machine. The tarball is deterministic, so the same source always gets the
|
|
17
17
|
* same `codepack:sha256:` ref.
|
|
18
|
+
*
|
|
19
|
+
* The author's full folder (`packCodepackSource`) is published next to it, so
|
|
20
|
+
* a Worker or `zl codepack source` can fetch the code with its tests, change
|
|
21
|
+
* it and rerun them.
|
|
18
22
|
*/
|
|
19
23
|
/** agent-studio's EXCLUDED_DIRS, plus local environments it never sees. */
|
|
20
24
|
const EXCLUDED_DIRECTORIES = new Set([
|
|
@@ -28,6 +32,16 @@ const EXCLUDED_DIRECTORIES = new Set([
|
|
|
28
32
|
'venv',
|
|
29
33
|
'node_modules',
|
|
30
34
|
]);
|
|
35
|
+
/** Kept out of the full source too: run outputs, private data and local environments. */
|
|
36
|
+
const SOURCE_EXCLUDED_DIRECTORIES = new Set([
|
|
37
|
+
'outputs',
|
|
38
|
+
'private',
|
|
39
|
+
'private_validation',
|
|
40
|
+
'__pycache__',
|
|
41
|
+
'.venv',
|
|
42
|
+
'venv',
|
|
43
|
+
'node_modules',
|
|
44
|
+
]);
|
|
31
45
|
/** agent-studio's TEXT_BUNDLE_SUFFIXES and BINARY_BUNDLE_SUFFIXES. */
|
|
32
46
|
const INCLUDED_EXTENSIONS = new Set([
|
|
33
47
|
'.csv',
|
|
@@ -42,6 +56,7 @@ const INCLUDED_EXTENSIONS = new Set([
|
|
|
42
56
|
'.xlsx',
|
|
43
57
|
]);
|
|
44
58
|
const MAX_ARCHIVE_BYTES = 25 * 1024 * 1024;
|
|
59
|
+
const MAX_UNPACKED_BYTES = 100 * 1024 * 1024;
|
|
45
60
|
const TEMPLATE_KEY_PATTERN = /^TEMPLATE:[a-z0-9][a-z0-9_]*@v\d+$/;
|
|
46
61
|
const FIELD_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
47
62
|
const TAR_BLOCK = 512;
|
|
@@ -52,7 +67,7 @@ export async function packCodepack(directory) {
|
|
|
52
67
|
}
|
|
53
68
|
const files = [];
|
|
54
69
|
const skipped = [];
|
|
55
|
-
await collect(directory, directory, files, skipped);
|
|
70
|
+
await collect(directory, directory, files, skipped, RUNTIME_SELECTION);
|
|
56
71
|
const config = files.find((file) => file.path === 'config.yaml');
|
|
57
72
|
if (!config)
|
|
58
73
|
throw new ValidationError('config.yaml', 'Codepack folder must contain config.yaml');
|
|
@@ -75,6 +90,43 @@ export async function packCodepack(directory) {
|
|
|
75
90
|
archive,
|
|
76
91
|
};
|
|
77
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* The author's full folder: everything except run outputs, private data,
|
|
95
|
+
* caches, local environments and dotfiles. It always contains the runtime
|
|
96
|
+
* files, so the server can check it matches the published codepack.
|
|
97
|
+
*/
|
|
98
|
+
export async function packCodepackSource(directory) {
|
|
99
|
+
const files = [];
|
|
100
|
+
await collect(directory, directory, files, [], SOURCE_SELECTION);
|
|
101
|
+
const archive = buildTarGz(files);
|
|
102
|
+
if (archive.byteLength > MAX_ARCHIVE_BYTES) {
|
|
103
|
+
throw new ValidationError('codepack', 'Codepack source exceeds 25 MiB; move large fixtures to Team Files or private/');
|
|
104
|
+
}
|
|
105
|
+
return { files: files.map((file) => file.path), archive };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Unpack a codepack or source tarball into an empty (or new) directory.
|
|
109
|
+
* Only regular files and directories with safe relative paths are written.
|
|
110
|
+
*/
|
|
111
|
+
export async function unpackCodepack(archive, directory) {
|
|
112
|
+
const target = resolve(directory);
|
|
113
|
+
const existing = await readdir(target).catch((error) => {
|
|
114
|
+
if (error.code === 'ENOENT')
|
|
115
|
+
return [];
|
|
116
|
+
throw error;
|
|
117
|
+
});
|
|
118
|
+
if (existing.length > 0) {
|
|
119
|
+
throw new ValidationError('output', `Directory is not empty: ${target}`);
|
|
120
|
+
}
|
|
121
|
+
const files = readTarGz(archive);
|
|
122
|
+
await mkdir(target, { recursive: true });
|
|
123
|
+
for (const file of files) {
|
|
124
|
+
const absolute = join(target, ...file.path.split('/'));
|
|
125
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
126
|
+
await writeFile(absolute, file.content, { flag: 'wx' });
|
|
127
|
+
}
|
|
128
|
+
return files.map((file) => file.path);
|
|
129
|
+
}
|
|
78
130
|
/** Local checks that mirror the server's; the server stays the authority. */
|
|
79
131
|
export function validateCodepackConfig(configYaml) {
|
|
80
132
|
let data;
|
|
@@ -113,7 +165,15 @@ export function validateCodepackConfig(configYaml) {
|
|
|
113
165
|
}
|
|
114
166
|
return templateKey;
|
|
115
167
|
}
|
|
116
|
-
|
|
168
|
+
const RUNTIME_SELECTION = {
|
|
169
|
+
excludedDirectories: EXCLUDED_DIRECTORIES,
|
|
170
|
+
extensions: INCLUDED_EXTENSIONS,
|
|
171
|
+
};
|
|
172
|
+
const SOURCE_SELECTION = {
|
|
173
|
+
excludedDirectories: SOURCE_EXCLUDED_DIRECTORIES,
|
|
174
|
+
extensions: null,
|
|
175
|
+
};
|
|
176
|
+
async function collect(root, directory, files, skipped, selection) {
|
|
117
177
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
118
178
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
119
179
|
const absolute = join(directory, entry.name);
|
|
@@ -126,15 +186,15 @@ async function collect(root, directory, files, skipped) {
|
|
|
126
186
|
throw new ValidationError('codepack', `Symlinks are not allowed in a codepack: ${path}`);
|
|
127
187
|
}
|
|
128
188
|
if (entry.isDirectory()) {
|
|
129
|
-
if (
|
|
189
|
+
if (selection.excludedDirectories.has(entry.name))
|
|
130
190
|
skipped.push(`${path}/`);
|
|
131
191
|
else
|
|
132
|
-
await collect(root, absolute, files, skipped);
|
|
192
|
+
await collect(root, absolute, files, skipped, selection);
|
|
133
193
|
continue;
|
|
134
194
|
}
|
|
135
195
|
if (!entry.isFile())
|
|
136
196
|
continue;
|
|
137
|
-
if (!
|
|
197
|
+
if (selection.extensions && !selection.extensions.has(extname(entry.name).toLowerCase())) {
|
|
138
198
|
skipped.push(path);
|
|
139
199
|
continue;
|
|
140
200
|
}
|
|
@@ -171,6 +231,55 @@ export function buildTarGz(files) {
|
|
|
171
231
|
blocks.push(Buffer.alloc(TAR_BLOCK * 2));
|
|
172
232
|
return gzipSync(Buffer.concat(blocks), { level: 9 });
|
|
173
233
|
}
|
|
234
|
+
/** Read a tarball written by `buildTarGz` or the server: regular files and directories only. */
|
|
235
|
+
export function readTarGz(archive) {
|
|
236
|
+
let tar;
|
|
237
|
+
try {
|
|
238
|
+
tar = gunzipSync(archive, { maxOutputLength: MAX_UNPACKED_BYTES });
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
throw new ValidationError('codepack', 'Expected a gzip tarball under 100 MiB unpacked');
|
|
242
|
+
}
|
|
243
|
+
const files = [];
|
|
244
|
+
let offset = 0;
|
|
245
|
+
while (offset + TAR_BLOCK <= tar.length) {
|
|
246
|
+
const header = tar.subarray(offset, offset + TAR_BLOCK);
|
|
247
|
+
if (header.every((byte) => byte === 0))
|
|
248
|
+
break;
|
|
249
|
+
const name = readField(header, 0, 100);
|
|
250
|
+
const prefix = readField(header, 345, 155);
|
|
251
|
+
const path = (prefix ? `${prefix}/${name}` : name).replace(/^\.\//, '').replace(/\/$/, '');
|
|
252
|
+
const size = Number.parseInt(readField(header, 124, 12) || '0', 8);
|
|
253
|
+
const typeflag = header.toString('utf8', 156, 157);
|
|
254
|
+
offset += TAR_BLOCK;
|
|
255
|
+
if (!Number.isFinite(size) || size < 0 || offset + size > tar.length) {
|
|
256
|
+
throw new ValidationError('codepack', `Archive entry has an invalid size: ${path}`);
|
|
257
|
+
}
|
|
258
|
+
const segments = path.split('/');
|
|
259
|
+
if (!path ||
|
|
260
|
+
path.startsWith('/') ||
|
|
261
|
+
path.includes('\\') ||
|
|
262
|
+
segments.some((segment) => !segment || segment === '.' || segment === '..')) {
|
|
263
|
+
throw new ValidationError('codepack', `Archive contains an unsafe path: ${path || '<empty>'}`);
|
|
264
|
+
}
|
|
265
|
+
if (typeflag === '0' || typeflag === '\0') {
|
|
266
|
+
files.push({ path, content: Buffer.from(tar.subarray(offset, offset + size)) });
|
|
267
|
+
}
|
|
268
|
+
else if (typeflag !== '5') {
|
|
269
|
+
throw new ValidationError('codepack', `Archive may contain only regular files: ${path}`);
|
|
270
|
+
}
|
|
271
|
+
offset += Math.ceil(size / TAR_BLOCK) * TAR_BLOCK;
|
|
272
|
+
}
|
|
273
|
+
return files;
|
|
274
|
+
}
|
|
275
|
+
function readField(header, start, length) {
|
|
276
|
+
const raw = header.subarray(start, start + length);
|
|
277
|
+
const end = raw.indexOf(0);
|
|
278
|
+
return raw
|
|
279
|
+
.subarray(0, end >= 0 ? end : raw.length)
|
|
280
|
+
.toString('utf8')
|
|
281
|
+
.trim();
|
|
282
|
+
}
|
|
174
283
|
function writeOctal(buffer, value, offset, length) {
|
|
175
284
|
buffer.write(value.toString(8).padStart(length - 1, '0'), offset, length - 1, 'ascii');
|
|
176
285
|
buffer[offset + length - 1] = 0;
|
package/package.json
CHANGED
|
@@ -26,7 +26,8 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
|
|
|
26
26
|
python -m pytest tests
|
|
27
27
|
```
|
|
28
28
|
- **Inputs and tests:** put sample files in `inputs/` and tests in `tests/`.
|
|
29
|
-
|
|
29
|
+
Runs never get them. They are kept with the team's copy of the source, so
|
|
30
|
+
`zl codepack source` returns them (see "Changing a published codepack").
|
|
30
31
|
- **Matching the sandbox:** use Python 3.12 where you can, with the packages listed
|
|
31
32
|
under Runtime, plus `pytest`:
|
|
32
33
|
`python3.12 -m venv .venv && .venv/bin/pip install pandas openpyxl xlsxwriter pytest`.
|
|
@@ -41,11 +42,21 @@ the selected team (`zl team list`, `zl team switch <tm_…>`).
|
|
|
41
42
|
`zl --environment <env> codepack publish <folder> --workflow <id> [--node <id-or-name>] --label "<what changed>"`.
|
|
42
43
|
It previews without `--apply`. With `--apply` it repins the node and saves a
|
|
43
44
|
named checkpoint.
|
|
45
|
+
- **Lineage:** `--parent <codepack ref>` records which version this one was changed
|
|
46
|
+
from, and `--label` records what changed. `zl codepack info <ref>` shows both.
|
|
44
47
|
6. **Make it live:** a workflow with a published version keeps running that version
|
|
45
48
|
until `zl --environment <env> workflow publish <id> --apply`. Then run it with
|
|
46
49
|
`zl workflow run <id>`, and check the result with `zl execution view <execution-id>`
|
|
47
50
|
and `zl file download <output-file-id> --output <path>`.
|
|
48
51
|
|
|
52
|
+
### Changing a published codepack
|
|
53
|
+
|
|
54
|
+
`zl --environment <env> codepack source <ref> --output <folder>` downloads the
|
|
55
|
+
folder a node pins, tests and sample inputs included, into an empty folder. Edit
|
|
56
|
+
it, run its tests, then publish it with `--parent <ref> --label "<what changed>"`.
|
|
57
|
+
Codepacks published before sources were kept come back without `tests/` and
|
|
58
|
+
`inputs/` (`"source": "runtime"`).
|
|
59
|
+
|
|
49
60
|
Always run locally and validate before publishing. After publishing, run the workflow
|
|
50
61
|
once on real inputs and check the outputs before telling the user it works.
|
|
51
62
|
|