@inneranimalmedia/primetech-procedures 0.0.0-stage → 2.6.19

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.
Files changed (76) hide show
  1. package/.codex-plugin/plugin.json +39 -0
  2. package/LICENSE +110 -0
  3. package/README.md +181 -2
  4. package/agents/openai.yaml +6 -0
  5. package/agentsam.package.json +80 -0
  6. package/assets/architect-icon.svg +10 -0
  7. package/assets/primetech-design-studio.svg +7 -0
  8. package/companion.json +40 -0
  9. package/package.json +56 -4
  10. package/plugin.README.md +37 -0
  11. package/plugin.json +43 -0
  12. package/procedures/arch.assembly.calculate/procedure.json +83 -0
  13. package/procedures/cad.motor-bearing-end-plate/README.md +21 -0
  14. package/procedures/cad.motor-bearing-end-plate/build_freecad.py +514 -0
  15. package/procedures/cad.motor-bearing-end-plate/finalize_bundle.py +26 -0
  16. package/procedures/cad.motor-bearing-end-plate/generate_assets.py +284 -0
  17. package/procedures/cad.motor-bearing-end-plate/generate_toolpaths.py +715 -0
  18. package/procedures/cad.motor-bearing-end-plate/package_artifacts.py +154 -0
  19. package/procedures/cad.motor-bearing-end-plate/parameters.json +51 -0
  20. package/procedures/cad.motor-bearing-end-plate/procedure.json +101 -0
  21. package/procedures/cad.motor-bearing-end-plate/render_preview.py +98 -0
  22. package/procedures/cad.motor-bearing-end-plate/run.py +214 -0
  23. package/procedures/cad.motor-bearing-end-plate/test_generate_toolpaths.py +50 -0
  24. package/procedures/media.asset.preflight/procedure.json +85 -0
  25. package/procedures/media.image.optimize-asset/procedure.json +102 -0
  26. package/procedures/primetech.assets.package/procedure.json +63 -0
  27. package/procedures/primetech.design-system.package/procedure.json +58 -0
  28. package/procedures/primetech.ebook.package/procedure.json +53 -0
  29. package/procedures/primetech.icon-family.build/procedure.json +101 -0
  30. package/procedures/primetech.production-board.manage/procedure.json +156 -0
  31. package/procedures/primetech.sprite-atlas.build/procedure.json +86 -0
  32. package/procedures/primetech.typeface.package/procedure.json +61 -0
  33. package/procedures/primetech.visuals.compare/procedure.json +74 -0
  34. package/procedures/repo.asset.inventory/procedure.json +65 -0
  35. package/procedures/repo.asset.inventory/run.py +116 -0
  36. package/procedures/repo.asset.inventory/run.sh +11 -0
  37. package/procedures/repo.git.status/procedure.json +58 -0
  38. package/procedures/repo.git.status/run.sh +10 -0
  39. package/profiles/PRIMETECH_PROCEDURE_ENGINEER.md +25 -0
  40. package/scripts/generate-procedures.py +112 -0
  41. package/scripts/generate-skills.py +425 -0
  42. package/scripts/package-openai-plugin.py +94 -0
  43. package/skills/primetech-brand-kit/SKILL.md +40 -0
  44. package/skills/primetech-brand-kit/agentsam.skill.json +64 -0
  45. package/skills/primetech-character-sprites/SKILL.md +40 -0
  46. package/skills/primetech-character-sprites/agentsam.skill.json +64 -0
  47. package/skills/primetech-creative-delivery/SKILL.md +39 -0
  48. package/skills/primetech-creative-delivery/agentsam.skill.json +57 -0
  49. package/skills/primetech-design-systems/SKILL.md +43 -0
  50. package/skills/primetech-design-systems/agentsam.skill.json +57 -0
  51. package/skills/primetech-digital-publishing/SKILL.md +39 -0
  52. package/skills/primetech-digital-publishing/agentsam.skill.json +52 -0
  53. package/skills/primetech-iconography/SKILL.md +40 -0
  54. package/skills/primetech-iconography/agentsam.skill.json +53 -0
  55. package/skills/primetech-type-design/SKILL.md +40 -0
  56. package/skills/primetech-type-design/agentsam.skill.json +53 -0
  57. package/skills/primetech-ui-ux-prototypes/SKILL.md +43 -0
  58. package/skills/primetech-ui-ux-prototypes/agentsam.skill.json +64 -0
  59. package/skills/primetech-visual-qa/SKILL.md +39 -0
  60. package/skills/primetech-visual-qa/agentsam.skill.json +56 -0
  61. package/src/creative/asset-package.js +42 -0
  62. package/src/creative/design-system.js +107 -0
  63. package/src/creative/ebook.js +88 -0
  64. package/src/creative/icon-family.js +125 -0
  65. package/src/creative/index.d.ts +157 -0
  66. package/src/creative/index.js +7 -0
  67. package/src/creative/paths.js +64 -0
  68. package/src/creative/sprite-atlas.js +100 -0
  69. package/src/creative/typeface.js +154 -0
  70. package/src/creative/visual-qa.js +88 -0
  71. package/src/index.d.ts +160 -0
  72. package/src/index.js +656 -0
  73. package/src/production-board.d.ts +103 -0
  74. package/src/production-board.js +181 -0
  75. package/src/skills.d.ts +48 -0
  76. package/src/skills.js +101 -0
package/src/index.js ADDED
@@ -0,0 +1,656 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const DEFAULT_CATALOG_ROOT = path.resolve(fileURLToPath(new URL('../procedures/', import.meta.url)));
7
+ const ID_RE = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
8
+ const VERSION_RE = /^\d+\.\d+\.\d+$/;
9
+ const EFFECTS = new Set(['read', 'local_write', 'project_write', 'export', 'external_action']);
10
+ const VERIFICATION_KINDS = new Set(['output_schema', 'fixture_suite', 'native_validation']);
11
+ const PYTHON_EXECUTABLE_RE = /^python3(?:\.\d+)?$/;
12
+ const RUNTIME_KINDS = new Set(['python', 'bash', 'sam_operation', 'native_tool']);
13
+ const OPERATION_ID_RE = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/;
14
+ const DIRECT_EXECUTION_DENYLIST = new Set(['primetech.procedure.run', 'sam.superbash', 'terminal.exec']);
15
+
16
+ export class PrimetechProcedureError extends Error {
17
+ constructor(code, message = code, details = undefined) {
18
+ super(message);
19
+ this.name = 'PrimetechProcedureError';
20
+ this.code = code;
21
+ this.details = details;
22
+ }
23
+ }
24
+
25
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
26
+ const hash = value => createHash('sha256').update(value).digest('hex');
27
+ function stableStringify(value) {
28
+ if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']';
29
+ if (isObject(value)) return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + stableStringify(value[key])).join(',') + '}';
30
+ return JSON.stringify(value);
31
+ }
32
+ const jsonHash = value => hash(Buffer.from(stableStringify(value), 'utf8'));
33
+ const iso = ms => new Date(ms).toISOString();
34
+
35
+ function inside(parent, candidate) {
36
+ const relative = path.relative(parent, candidate);
37
+ return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
38
+ }
39
+
40
+ function safeProcedureId(value) {
41
+ return typeof value === 'string' && ID_RE.test(value) && !value.includes('..');
42
+ }
43
+
44
+ function validateValue(value, schema, location = '$', errors = []) {
45
+ if (!isObject(schema)) {
46
+ errors.push({ path: location, code: 'schema_object_required' });
47
+ return errors;
48
+ }
49
+ const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);
50
+ const matches = type => {
51
+ if (type === 'null') return value === null;
52
+ if (type === 'array') return Array.isArray(value);
53
+ if (type === 'object') return isObject(value);
54
+ if (type === 'integer') return Number.isInteger(value) && typeof value === 'number';
55
+ if (type === 'number') return typeof value === 'number' && Number.isFinite(value);
56
+ if (type === 'boolean') return typeof value === 'boolean';
57
+ if (type === 'string') return typeof value === 'string';
58
+ return true;
59
+ };
60
+ if (types.length && !types.some(matches)) {
61
+ errors.push({ path: location, code: 'schema_type_mismatch', expected: types });
62
+ return errors;
63
+ }
64
+ if (Object.hasOwn(schema, 'const') && value !== schema.const) {
65
+ errors.push({ path: location, code: 'schema_const_mismatch' });
66
+ }
67
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
68
+ errors.push({ path: location, code: 'schema_enum_mismatch' });
69
+ }
70
+ if (typeof value === 'string') {
71
+ if (Number.isInteger(schema.minLength) && value.length < schema.minLength) errors.push({ path: location, code: 'schema_min_length' });
72
+ if (Number.isInteger(schema.maxLength) && value.length > schema.maxLength) errors.push({ path: location, code: 'schema_max_length' });
73
+ if (schema.pattern && !(new RegExp(schema.pattern)).test(value)) errors.push({ path: location, code: 'schema_pattern_mismatch' });
74
+ }
75
+ if (typeof value === 'number') {
76
+ if (Number.isFinite(schema.minimum) && value < schema.minimum) errors.push({ path: location, code: 'schema_minimum' });
77
+ if (Number.isFinite(schema.maximum) && value > schema.maximum) errors.push({ path: location, code: 'schema_maximum' });
78
+ }
79
+ if (Array.isArray(value)) {
80
+ if (Number.isInteger(schema.minItems) && value.length < schema.minItems) errors.push({ path: location, code: 'schema_min_items' });
81
+ if (Number.isInteger(schema.maxItems) && value.length > schema.maxItems) errors.push({ path: location, code: 'schema_max_items' });
82
+ if (schema.uniqueItems && new Set(value.map(item => JSON.stringify(item))).size !== value.length) errors.push({ path: location, code: 'schema_items_not_unique' });
83
+ if (schema.items) value.forEach((item, index) => validateValue(item, schema.items, location + '[' + index + ']', errors));
84
+ }
85
+ if (isObject(value)) {
86
+ for (const key of schema.required || []) {
87
+ if (!Object.hasOwn(value, key)) errors.push({ path: location + '.' + key, code: 'schema_required_property_missing' });
88
+ }
89
+ if (isObject(schema.properties)) {
90
+ for (const [key, item] of Object.entries(value)) {
91
+ if (Object.hasOwn(schema.properties, key)) validateValue(item, schema.properties[key], location + '.' + key, errors);
92
+ else if (schema.additionalProperties === false) errors.push({ path: location + '.' + key, code: 'schema_additional_property_not_allowed' });
93
+ }
94
+ } else if (schema.additionalProperties === false && Object.keys(value).length) {
95
+ errors.push({ path: location, code: 'schema_additional_property_not_allowed' });
96
+ }
97
+ }
98
+ return errors;
99
+ }
100
+
101
+ const SUPPORTED_SCHEMA_KEYS = new Set([
102
+ 'type', 'const', 'enum', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum',
103
+ 'minItems', 'maxItems', 'uniqueItems', 'items', 'required', 'properties', 'additionalProperties',
104
+ ]);
105
+ const SUPPORTED_SCHEMA_TYPES = new Set(['object', 'array', 'string', 'integer', 'number', 'boolean', 'null']);
106
+
107
+ function validateSchemaDefinition(schema, location, errors) {
108
+ if (!isObject(schema)) {
109
+ errors.push({ path: location, code: 'procedure_json_schema_object_required' });
110
+ return;
111
+ }
112
+ for (const key of Object.keys(schema)) {
113
+ if (!SUPPORTED_SCHEMA_KEYS.has(key)) errors.push({ path: location + '.' + key, code: 'procedure_json_schema_keyword_not_supported' });
114
+ }
115
+ const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);
116
+ if (types.some(type => !SUPPORTED_SCHEMA_TYPES.has(type))) errors.push({ path: location + '.type', code: 'procedure_json_schema_type_not_supported' });
117
+ if (schema.properties !== undefined) {
118
+ if (!isObject(schema.properties)) errors.push({ path: location + '.properties', code: 'procedure_json_schema_properties_invalid' });
119
+ else for (const [key, child] of Object.entries(schema.properties)) validateSchemaDefinition(child, location + '.properties.' + key, errors);
120
+ }
121
+ if (schema.items !== undefined) validateSchemaDefinition(schema.items, location + '.items', errors);
122
+ if (schema.required !== undefined && (!Array.isArray(schema.required) || schema.required.some(key => typeof key !== 'string'))) {
123
+ errors.push({ path: location + '.required', code: 'procedure_json_schema_required_invalid' });
124
+ }
125
+ if (schema.enum !== undefined && !Array.isArray(schema.enum)) errors.push({ path: location + '.enum', code: 'procedure_json_schema_enum_invalid' });
126
+ if (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== 'boolean') {
127
+ errors.push({ path: location + '.additionalProperties', code: 'procedure_json_schema_additional_properties_invalid' });
128
+ }
129
+ }
130
+
131
+ export function validateProcedureManifest(manifest) {
132
+ const errors = [];
133
+ if (!isObject(manifest)) return { ok: false, errors: [{ path: '$', code: 'procedure_manifest_object_required' }] };
134
+ const required = ['schema', 'id', 'version', 'summary', 'effect', 'capabilities', 'runtime', 'input_schema', 'output_schema', 'verification', 'flags'];
135
+ for (const key of required) if (!Object.hasOwn(manifest, key)) errors.push({ path: '$.' + key, code: 'procedure_manifest_required_property_missing' });
136
+ const allowed = new Set(required);
137
+ for (const key of Object.keys(manifest)) if (!allowed.has(key)) errors.push({ path: '$.' + key, code: 'procedure_manifest_additional_property_not_allowed' });
138
+ if (manifest.schema !== 'inneranimalmedia.primetech.procedure.v1') errors.push({ path: '$.schema', code: 'procedure_schema_unsupported' });
139
+ if (!safeProcedureId(manifest.id)) errors.push({ path: '$.id', code: 'procedure_id_invalid' });
140
+ if (typeof manifest.version !== 'string' || !VERSION_RE.test(manifest.version)) errors.push({ path: '$.version', code: 'procedure_version_invalid' });
141
+ if (typeof manifest.summary !== 'string' || !manifest.summary.trim() || manifest.summary.length > 280) errors.push({ path: '$.summary', code: 'procedure_summary_invalid' });
142
+ if (!EFFECTS.has(manifest.effect)) errors.push({ path: '$.effect', code: 'procedure_effect_invalid' });
143
+ if (!Array.isArray(manifest.capabilities) || manifest.capabilities.some(item => typeof item !== 'string' || !/^[a-z][a-z0-9_.-]+$/.test(item)) || new Set(manifest.capabilities).size !== manifest.capabilities.length) {
144
+ errors.push({ path: '$.capabilities', code: 'procedure_capabilities_invalid' });
145
+ }
146
+ if (!isObject(manifest.runtime)) {
147
+ errors.push({ path: '$.runtime', code: 'procedure_runtime_object_required' });
148
+ } else {
149
+ const runtime = manifest.runtime;
150
+ const kind = runtime.kind;
151
+ if (!RUNTIME_KINDS.has(kind)) errors.push({ path: '$.runtime.kind', code: 'procedure_runtime_kind_invalid' });
152
+ const fileRuntime = kind === 'python' || kind === 'bash';
153
+ if (fileRuntime && !manifest.capabilities?.includes('sam.superbash')) {
154
+ errors.push({ path: '$.capabilities', code: 'procedure_shell_capability_not_declared' });
155
+ }
156
+ if (fileRuntime) {
157
+ if (typeof runtime.entrypoint !== 'string' || !runtime.entrypoint || path.isAbsolute(runtime.entrypoint) ||
158
+ runtime.entrypoint.split(/[\\/]/).includes('..') || runtime.entrypoint.includes('\0')) {
159
+ errors.push({ path: '$.runtime.entrypoint', code: 'procedure_entrypoint_invalid' });
160
+ }
161
+ } else if (runtime.entrypoint !== undefined) {
162
+ errors.push({ path: '$.runtime.entrypoint', code: 'procedure_runtime_entrypoint_not_applicable' });
163
+ }
164
+ if (kind === 'sam_operation') {
165
+ if (typeof runtime.operation !== 'string' || !OPERATION_ID_RE.test(runtime.operation) ||
166
+ DIRECT_EXECUTION_DENYLIST.has(runtime.operation) || !manifest.capabilities?.includes(runtime.operation)) {
167
+ errors.push({ path: '$.runtime.operation', code: 'procedure_runtime_operation_invalid' });
168
+ }
169
+ } else if (runtime.operation !== undefined) {
170
+ errors.push({ path: '$.runtime.operation', code: 'procedure_runtime_operation_not_applicable' });
171
+ }
172
+ if (kind === 'native_tool') {
173
+ if (typeof runtime.tool_key !== 'string' || !OPERATION_ID_RE.test(runtime.tool_key) ||
174
+ DIRECT_EXECUTION_DENYLIST.has(runtime.tool_key) || !manifest.capabilities?.includes(runtime.tool_key)) {
175
+ errors.push({ path: '$.runtime.tool_key', code: 'procedure_runtime_tool_invalid' });
176
+ }
177
+ } else if (runtime.tool_key !== undefined) {
178
+ errors.push({ path: '$.runtime.tool_key', code: 'procedure_runtime_tool_not_applicable' });
179
+ }
180
+ if (kind === 'python') {
181
+ if (typeof runtime.min_python !== 'string' || !/^\d+\.\d+$/.test(runtime.min_python)) errors.push({ path: '$.runtime.min_python', code: 'procedure_min_python_invalid' });
182
+ if (runtime.interpreter_candidates !== undefined && (
183
+ !Array.isArray(runtime.interpreter_candidates) || runtime.interpreter_candidates.length < 1 ||
184
+ runtime.interpreter_candidates.length > 8 ||
185
+ runtime.interpreter_candidates.some(item => typeof item !== 'string' || !PYTHON_EXECUTABLE_RE.test(item)) ||
186
+ new Set(runtime.interpreter_candidates).size !== runtime.interpreter_candidates.length
187
+ )) errors.push({ path: '$.runtime.interpreter_candidates', code: 'procedure_interpreter_candidates_invalid' });
188
+ } else if (runtime.min_python !== undefined || runtime.interpreter_candidates !== undefined) {
189
+ errors.push({ path: '$.runtime', code: 'procedure_python_config_not_applicable' });
190
+ }
191
+ if (runtime.dependencies !== undefined && (!Array.isArray(runtime.dependencies) || runtime.dependencies.some(item => typeof item !== 'string'))) {
192
+ errors.push({ path: '$.runtime.dependencies', code: 'procedure_dependencies_invalid' });
193
+ }
194
+ const runtimeAllowed = new Set(['kind', 'entrypoint', 'operation', 'tool_key', 'min_python', 'dependencies', 'interpreter_candidates']);
195
+ for (const key of Object.keys(runtime)) if (!runtimeAllowed.has(key)) errors.push({ path: '$.runtime.' + key, code: 'procedure_runtime_additional_property_not_allowed' });
196
+ }
197
+ if (!isObject(manifest.input_schema) || !isObject(manifest.output_schema) || manifest.input_schema.type !== 'object' || manifest.output_schema.type !== 'object') {
198
+ errors.push({ path: '$.input_schema', code: 'procedure_json_schemas_required' });
199
+ } else {
200
+ validateSchemaDefinition(manifest.input_schema, '$.input_schema', errors);
201
+ validateSchemaDefinition(manifest.output_schema, '$.output_schema', errors);
202
+ }
203
+ if (!isObject(manifest.verification) || !VERIFICATION_KINDS.has(manifest.verification.kind)) {
204
+ errors.push({ path: '$.verification', code: 'procedure_verification_invalid' });
205
+ } else {
206
+ for (const key of Object.keys(manifest.verification)) {
207
+ if (!['kind', 'expected', 'fixture_id'].includes(key)) errors.push({ path: '$.verification.' + key, code: 'procedure_verification_additional_property_not_allowed' });
208
+ }
209
+ }
210
+ if (!isObject(manifest.flags)) {
211
+ errors.push({ path: '$.flags', code: 'procedure_flags_required' });
212
+ } else {
213
+ for (const key of ['network', 'physical_hardware', 'requires_operator_review']) {
214
+ if (typeof manifest.flags[key] !== 'boolean') errors.push({ path: '$.flags.' + key, code: 'procedure_flag_boolean_required' });
215
+ }
216
+ for (const key of Object.keys(manifest.flags)) {
217
+ if (!['network', 'physical_hardware', 'requires_operator_review'].includes(key)) errors.push({ path: '$.flags.' + key, code: 'procedure_flags_additional_property_not_allowed' });
218
+ }
219
+ }
220
+ return { ok: errors.length === 0, errors };
221
+ }
222
+
223
+ function loadProcedure(root, id, requestedVersion = undefined) {
224
+ if (!safeProcedureId(id)) throw new PrimetechProcedureError('primetech_procedure_id_invalid');
225
+ const catalogRoot = fs.realpathSync(root);
226
+ const procedureDir = path.resolve(catalogRoot, id);
227
+ if (!inside(catalogRoot, procedureDir)) throw new PrimetechProcedureError('primetech_procedure_path_outside_catalog');
228
+ let realDir;
229
+ try { realDir = fs.realpathSync(procedureDir); }
230
+ catch { throw new PrimetechProcedureError('primetech_procedure_not_found'); }
231
+ if (!inside(catalogRoot, realDir)) throw new PrimetechProcedureError('primetech_procedure_path_outside_catalog');
232
+ const manifestPath = path.join(realDir, 'procedure.json');
233
+ let raw;
234
+ let manifest;
235
+ try {
236
+ raw = fs.readFileSync(manifestPath);
237
+ manifest = JSON.parse(raw.toString('utf8'));
238
+ } catch (error) {
239
+ throw new PrimetechProcedureError('primetech_procedure_manifest_invalid', 'Procedure manifest is missing or invalid JSON.');
240
+ }
241
+ const validation = validateProcedureManifest(manifest);
242
+ if (!validation.ok || manifest.id !== id) {
243
+ throw new PrimetechProcedureError('primetech_procedure_manifest_invalid', 'Procedure manifest failed contract validation.', validation.errors);
244
+ }
245
+ if (requestedVersion !== undefined && requestedVersion !== manifest.version) {
246
+ throw new PrimetechProcedureError('primetech_procedure_version_not_found');
247
+ }
248
+ let entrypointPath = null;
249
+ if (manifest.runtime.kind === 'python' || manifest.runtime.kind === 'bash') {
250
+ const lexicalEntry = path.resolve(realDir, manifest.runtime.entrypoint);
251
+ if (!inside(realDir, lexicalEntry)) throw new PrimetechProcedureError('primetech_procedure_entrypoint_outside_package');
252
+ try { entrypointPath = fs.realpathSync(lexicalEntry); }
253
+ catch { throw new PrimetechProcedureError('primetech_procedure_entrypoint_not_found'); }
254
+ if (!inside(realDir, entrypointPath) || !fs.statSync(entrypointPath).isFile()) {
255
+ throw new PrimetechProcedureError('primetech_procedure_entrypoint_outside_package');
256
+ }
257
+ }
258
+ return {
259
+ manifest,
260
+ manifestPath,
261
+ procedureDir: realDir,
262
+ entrypointPath,
263
+ manifestSha256: hash(raw),
264
+ entrypointSha256: entrypointPath ? hash(fs.readFileSync(entrypointPath)) : null,
265
+ };
266
+ }
267
+
268
+ export function createProcedureCatalog({ root = DEFAULT_CATALOG_ROOT } = {}) {
269
+ const catalogRoot = path.resolve(root);
270
+ return Object.freeze({
271
+ list() {
272
+ let dirs;
273
+ try { dirs = fs.readdirSync(catalogRoot, { withFileTypes: true }).filter(item => item.isDirectory()).map(item => item.name).sort(); }
274
+ catch { throw new PrimetechProcedureError('primetech_procedure_catalog_unavailable'); }
275
+ return dirs.map(id => {
276
+ try {
277
+ const row = loadProcedure(catalogRoot, id);
278
+ return { id, version: row.manifest.version, summary: row.manifest.summary, effect: row.manifest.effect, available: true };
279
+ } catch (error) {
280
+ return { id, available: false, error: error.code || 'primetech_procedure_manifest_invalid' };
281
+ }
282
+ });
283
+ },
284
+ get(id, version) {
285
+ return loadProcedure(catalogRoot, id, version);
286
+ },
287
+ root: catalogRoot,
288
+ });
289
+ }
290
+
291
+ function shellQuote(value) {
292
+ return "'" + String(value).replace(/'/g, "'\\''") + "'";
293
+ }
294
+
295
+ function buildPythonCommand(manifest, entrypointPath, input) {
296
+ const candidates = manifest.runtime.interpreter_candidates || ['python3.12', 'python3.11', 'python3.10', 'python3'];
297
+ if (candidates.some(candidate => !PYTHON_EXECUTABLE_RE.test(candidate))) {
298
+ throw new PrimetechProcedureError('primetech_procedure_interpreter_invalid');
299
+ }
300
+ const lines = ['set -euo pipefail'];
301
+ for (const candidate of candidates) {
302
+ lines.push('if command -v ' + shellQuote(candidate) + ' >/dev/null 2>&1; then');
303
+ lines.push(' exec ' + shellQuote(candidate) + ' -B -I -S ' + shellQuote(entrypointPath) + ' ' + shellQuote(JSON.stringify(input)));
304
+ lines.push('fi');
305
+ }
306
+ lines.push("printf '%s\\n' '{\"schema\":\"inneranimalmedia.primetech.asset-inventory.v1\",\"ok\":false,\"error\":\"python_interpreter_not_found\"}' >&2");
307
+ lines.push('exit 127');
308
+ return lines.join('\n');
309
+ }
310
+
311
+ function buildBashCommand(entrypointPath, input) {
312
+ // The command is composed solely from the manifest-pinned, catalog-validated
313
+ // entrypoint and a schema-validated JSON argument. No caller shell source.
314
+ return 'set -euo pipefail\nexec bash -- ' + shellQuote(entrypointPath) + ' ' + shellQuote(JSON.stringify(input));
315
+ }
316
+
317
+ function writeJsonAtomic(target, value) {
318
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
319
+ const temporary = target + '.' + randomUUID() + '.tmp';
320
+ try {
321
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
322
+ try { fs.chmodSync(temporary, 0o600); } catch {}
323
+ fs.renameSync(temporary, target);
324
+ } finally {
325
+ try { fs.unlinkSync(temporary); } catch {}
326
+ }
327
+ }
328
+
329
+ export function summarizeProcedureRuns({ receiptDir, procedureId = null, limit = 1000 } = {}) {
330
+ if (typeof receiptDir !== 'string' || !receiptDir) throw new PrimetechProcedureError('primetech_receipt_directory_required');
331
+ if (!Number.isInteger(limit) || limit < 1 || limit > 10000) throw new PrimetechProcedureError('primetech_receipt_limit_invalid');
332
+ let root;
333
+ try { root = fs.realpathSync(receiptDir); }
334
+ catch { throw new PrimetechProcedureError('primetech_receipt_directory_unavailable'); }
335
+ const files = fs.readdirSync(root)
336
+ .filter(name => /^receipt-primetech\.procedure\.run-ptr_[a-f0-9]+\.json$/.test(name))
337
+ .sort()
338
+ .slice(-limit);
339
+ const groups = new Map();
340
+ let scanned = 0;
341
+ let ignored = 0;
342
+ for (const name of files) {
343
+ let row;
344
+ try { row = JSON.parse(fs.readFileSync(path.join(root, name), 'utf8')); }
345
+ catch { ignored++; continue; }
346
+ if (row?.schema !== 'agentsam.primetech.procedure-receipt.v1' || !isObject(row.procedure) ||
347
+ typeof row.procedure.id !== 'string' || typeof row.procedure.version !== 'string') {
348
+ ignored++;
349
+ continue;
350
+ }
351
+ if (procedureId && row.procedure.id !== procedureId) continue;
352
+ scanned++;
353
+ const key = row.procedure.id + '@' + row.procedure.version;
354
+ if (!groups.has(key)) groups.set(key, {
355
+ id: row.procedure.id, version: row.procedure.version, run_count: 0, completed: 0, failed: 0,
356
+ durations: [], failures: new Map(), last_run_at: null,
357
+ });
358
+ const group = groups.get(key);
359
+ group.run_count++;
360
+ if (row.status === 'completed') group.completed++;
361
+ else {
362
+ group.failed++;
363
+ const code = row.error?.code || 'unknown';
364
+ group.failures.set(code, (group.failures.get(code) || 0) + 1);
365
+ }
366
+ if (Number.isFinite(row.duration_ms) && row.duration_ms >= 0) group.durations.push(row.duration_ms);
367
+ const at = row.completed_at || row.started_at || null;
368
+ if (at && (!group.last_run_at || at > group.last_run_at)) group.last_run_at = at;
369
+ }
370
+ const percentile = (values, p) => {
371
+ if (!values.length) return null;
372
+ const sorted = [...values].sort((a, b) => a - b);
373
+ return sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)];
374
+ };
375
+ const by_procedure = [...groups.values()].map(group => {
376
+ const durations = group.durations;
377
+ return {
378
+ id: group.id,
379
+ version: group.version,
380
+ run_count: group.run_count,
381
+ completed: group.completed,
382
+ failed: group.failed,
383
+ success_rate: group.run_count ? Number((group.completed / group.run_count).toFixed(4)) : 0,
384
+ mean_duration_ms: durations.length ? Math.round(durations.reduce((sum, value) => sum + value, 0) / durations.length) : null,
385
+ p50_duration_ms: percentile(durations, 0.5),
386
+ p95_duration_ms: percentile(durations, 0.95),
387
+ last_run_at: group.last_run_at,
388
+ failures: [...group.failures.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([code, count]) => ({ code, count })),
389
+ };
390
+ }).sort((a, b) => a.id.localeCompare(b.id) || a.version.localeCompare(b.version));
391
+ return { schema: 'inneranimalmedia.primetech.procedure-performance.v1', scanned, ignored, by_procedure };
392
+ }
393
+
394
+ export function createPrimeTechProcedureHandler({
395
+ catalog = createProcedureCatalog(),
396
+ projectRoot,
397
+ receiptDir = null,
398
+ invokeSamOperation,
399
+ invokeNativeTool = null,
400
+ isCapabilityAvailable = () => false,
401
+ isNativeToolAvailable = () => false,
402
+ verifyProcedureOutput = null,
403
+ authorizeProcedure = null,
404
+ now = () => Date.now(),
405
+ } = {}) {
406
+ return async function runPrimeTechProcedure(input = {}) {
407
+ const started = now();
408
+ const runId = 'ptr_' + randomUUID().replaceAll('-', '');
409
+ let procedure = null;
410
+ let execution = null;
411
+ let executedOperation = null;
412
+ let sourceReceipt = null;
413
+ let output = null;
414
+ let outputSha256 = null;
415
+ let artifactRef = null;
416
+ let artifactBytes = 0;
417
+ let verification = { kind: 'output_schema', ok: false };
418
+ let errorCode = null;
419
+ let errorMessage = null;
420
+ const data = isObject(input) ? input : {};
421
+ const receiptRoot = receiptDir
422
+ ? path.resolve(receiptDir)
423
+ : (projectRoot ? path.resolve(projectRoot, '.agentsam', 'receipts') : null);
424
+ const record = {
425
+ schema: 'agentsam.primetech.procedure-receipt.v1',
426
+ id: runId,
427
+ status: 'running',
428
+ started_at: iso(started),
429
+ procedure: null,
430
+ input_sha256: jsonHash(data),
431
+ manifest_sha256: null,
432
+ entrypoint_sha256: null,
433
+ output_sha256: null,
434
+ output_bytes: null,
435
+ artifact_bytes: 0,
436
+ timings_ms: { preflight: 0, execution: 0, verification: 0, persistence: 0 },
437
+ verification,
438
+ execution: null,
439
+ };
440
+ const persistReceipt = status => {
441
+ if (!receiptRoot) return null;
442
+ record.status = status;
443
+ record.completed_at = iso(now());
444
+ record.duration_ms = Math.max(0, now() - started);
445
+ record.procedure = procedure ? { id: procedure.manifest.id, version: procedure.manifest.version, effect: procedure.manifest.effect } : null;
446
+ record.manifest_sha256 = procedure?.manifestSha256 || null;
447
+ record.entrypoint_sha256 = procedure?.entrypointSha256 || null;
448
+ record.output_sha256 = outputSha256;
449
+ record.verification = verification;
450
+ record.execution = execution ? {
451
+ operation: executedOperation,
452
+ runtime_kind: procedure?.manifest.runtime.kind || null,
453
+ execution_id: execution.executionId || execution.execution_id || null,
454
+ source_receipt_id: sourceReceipt?.id || null,
455
+ script_sha256: execution.scriptHash || execution.script_sha256 || null,
456
+ status: execution.status || null,
457
+ exit_code: execution.exitCode ?? execution.exit_code ?? null,
458
+ duration_ms: execution.durationMs ?? execution.duration_ms ?? null,
459
+ script_bytes: execution.scriptBytes ?? execution.script_bytes ?? null,
460
+ } : null;
461
+ record.output_bytes = output ? Buffer.byteLength(stableStringify(output), 'utf8') : null;
462
+ record.artifact_bytes = artifactBytes;
463
+ record.artifact_ref = artifactRef;
464
+ record.error = errorCode ? { code: errorCode, message: errorMessage } : null;
465
+ try {
466
+ const relative = 'receipt-primetech.procedure.run-' + runId + '.json';
467
+ const target = path.resolve(receiptRoot, relative);
468
+ if (!inside(receiptRoot, target)) throw new Error('receipt_path_outside_root');
469
+ writeJsonAtomic(target, record);
470
+ return { ref: relative, sha256: hash(fs.readFileSync(target)) };
471
+ } catch {
472
+ return null;
473
+ }
474
+ };
475
+
476
+ try {
477
+ if (!isObject(input)) throw new PrimetechProcedureError('primetech_procedure_input_object_required');
478
+ const allowed = new Set(['id', 'version', 'input']);
479
+ if (Object.keys(input).some(key => !allowed.has(key))) throw new PrimetechProcedureError('primetech_procedure_input_additional_property_not_allowed');
480
+ if (!safeProcedureId(input.id) || typeof input.version !== 'string' || !VERSION_RE.test(input.version) || !isObject(input.input)) {
481
+ throw new PrimetechProcedureError('primetech_procedure_input_invalid');
482
+ }
483
+ if (!projectRoot) throw new PrimetechProcedureError('primetech_procedure_host_binding_required');
484
+ const canonicalProjectRoot = fs.realpathSync(projectRoot);
485
+ if (!fs.statSync(canonicalProjectRoot).isDirectory()) throw new PrimetechProcedureError('primetech_procedure_project_root_invalid');
486
+ procedure = catalog.get(input.id, input.version);
487
+ const manifest = procedure.manifest;
488
+ record.procedure = { id: manifest.id, version: manifest.version, effect: manifest.effect };
489
+ const inputErrors = validateValue(input.input, manifest.input_schema);
490
+ if (inputErrors.length) throw new PrimetechProcedureError('primetech_procedure_input_schema_invalid', 'Procedure input did not match its schema.', inputErrors);
491
+ if (manifest.flags.physical_hardware) throw new PrimetechProcedureError('primetech_physical_hardware_not_supported');
492
+ const runtime = manifest.runtime;
493
+ const toolId = runtime.kind === 'native_tool' ? runtime.tool_key : null;
494
+ const directOperation = runtime.kind === 'sam_operation' ? runtime.operation : null;
495
+ if (runtime.kind === 'native_tool' && typeof invokeNativeTool !== 'function') {
496
+ throw new PrimetechProcedureError('primetech_native_tool_host_not_bound');
497
+ }
498
+ if (runtime.kind !== 'native_tool' && typeof invokeSamOperation !== 'function') {
499
+ throw new PrimetechProcedureError('primetech_procedure_host_binding_required');
500
+ }
501
+ for (const capability of manifest.capabilities) {
502
+ const available = toolId === capability
503
+ ? await isNativeToolAvailable(capability)
504
+ : await isCapabilityAvailable(capability);
505
+ if (available !== true) {
506
+ throw new PrimetechProcedureError('primetech_required_capability_unavailable', 'A required capability is not bound: ' + capability);
507
+ }
508
+ }
509
+ if (manifest.effect !== 'read' || manifest.flags.network || manifest.flags.requires_operator_review) {
510
+ if (typeof authorizeProcedure !== 'function' || await authorizeProcedure({
511
+ id: manifest.id, version: manifest.version, effect: manifest.effect,
512
+ network: manifest.flags.network, requires_operator_review: manifest.flags.requires_operator_review,
513
+ input_sha256: record.input_sha256,
514
+ }) !== true) {
515
+ throw new PrimetechProcedureError('primetech_procedure_operator_approval_required');
516
+ }
517
+ }
518
+ const fileRunner = runtime.kind === 'python' || runtime.kind === 'bash';
519
+ const script = runtime.kind === 'python'
520
+ ? buildPythonCommand(manifest, procedure.entrypointPath, input.input)
521
+ : runtime.kind === 'bash' ? buildBashCommand(procedure.entrypointPath, input.input) : null;
522
+ executedOperation = fileRunner ? 'sam.superbash' : (directOperation || toolId);
523
+ record.timings_ms.preflight = Math.max(0, now() - started);
524
+ const executionStarted = now();
525
+ const invocation = fileRunner ? {
526
+ script,
527
+ relativeCwd: '.',
528
+ idempotencyKey: 'primetech:' + manifest.id + ':' + manifest.version + ':' + record.input_sha256,
529
+ } : input.input;
530
+ const invocationResult = toolId
531
+ ? await invokeNativeTool(toolId, invocation)
532
+ : await invokeSamOperation(executedOperation, invocation);
533
+ if (!isObject(invocationResult) || invocationResult.ok !== true) {
534
+ const code = invocationResult?.error?.code || invocationResult?.error || 'primetech_procedure_execution_failed';
535
+ throw new PrimetechProcedureError(String(code), 'The authorized host operation did not complete successfully.');
536
+ }
537
+ sourceReceipt = isObject(invocationResult.receipt) ? invocationResult.receipt : null;
538
+ const resultData = invocationResult.data || invocationResult;
539
+ record.timings_ms.execution = Math.max(0, now() - executionStarted);
540
+ if (fileRunner) {
541
+ execution = resultData;
542
+ if (execution.ok === false || execution.status !== 'completed' || (execution.exitCode ?? execution.exit_code) !== 0) {
543
+ const code = execution.error?.code || 'primetech_procedure_execution_failed';
544
+ throw new PrimetechProcedureError(code, 'The existing SAM process operation did not complete successfully.');
545
+ }
546
+ try { output = JSON.parse(String(execution.stdout || '').trim()); }
547
+ catch { throw new PrimetechProcedureError('primetech_procedure_output_invalid', 'Procedure stdout was not one valid JSON document.'); }
548
+ } else {
549
+ // Direct operations return a structured result, never a shell stdout
550
+ // or an arbitrary unverified message. The host owns authorization.
551
+ output = resultData;
552
+ execution = {
553
+ status: sourceReceipt?.status || 'completed',
554
+ executionId: sourceReceipt?.id || null,
555
+ durationMs: sourceReceipt?.duration_ms ?? null,
556
+ };
557
+ if (execution.status !== 'completed') {
558
+ throw new PrimetechProcedureError('primetech_procedure_execution_failed');
559
+ }
560
+ }
561
+ if (!isObject(output) || output.ok === false) throw new PrimetechProcedureError('primetech_procedure_output_failed');
562
+ const verificationStarted = now();
563
+ const outputErrors = validateValue(output, manifest.output_schema);
564
+ if (outputErrors.length) throw new PrimetechProcedureError('primetech_procedure_output_verification_failed', 'Procedure output failed schema verification.', outputErrors);
565
+ if (manifest.verification.kind === 'output_schema' && manifest.verification.expected && output.schema !== manifest.verification.expected) {
566
+ throw new PrimetechProcedureError('primetech_procedure_output_verification_failed');
567
+ }
568
+ if (manifest.verification.kind === 'output_schema') {
569
+ verification = { kind: 'output_schema', ok: true };
570
+ } else {
571
+ if (typeof verifyProcedureOutput !== 'function') {
572
+ throw new PrimetechProcedureError('primetech_procedure_verifier_not_bound');
573
+ }
574
+ const checked = await verifyProcedureOutput({
575
+ manifest, projectRoot: canonicalProjectRoot, input: input.input, output,
576
+ execution: { operation: executedOperation, source_receipt: sourceReceipt },
577
+ });
578
+ if (!isObject(checked) || checked.ok !== true || checked.kind !== manifest.verification.kind) {
579
+ throw new PrimetechProcedureError('primetech_procedure_verification_failed');
580
+ }
581
+ verification = { kind: checked.kind, ok: true, ...(checked.evidence ? { evidence: checked.evidence } : {}) };
582
+ }
583
+ record.timings_ms.verification = Math.max(0, now() - verificationStarted);
584
+ outputSha256 = jsonHash(output);
585
+ const warnings = [];
586
+ let artifactSha256 = null;
587
+ const artifact = JSON.stringify(output, null, 2) + '\n';
588
+ const persistenceStarted = now();
589
+ if (receiptRoot) {
590
+ artifactRef = path.join('artifacts', 'primetech', manifest.id, manifest.version, runId + '.json').split(path.sep).join('/');
591
+ const artifactPath = path.resolve(receiptRoot, artifactRef);
592
+ if (!inside(receiptRoot, artifactPath)) throw new PrimetechProcedureError('primetech_artifact_path_outside_receipts');
593
+ try {
594
+ writeJsonAtomic(artifactPath, output);
595
+ const bytes = fs.readFileSync(artifactPath);
596
+ artifactSha256 = hash(bytes);
597
+ artifactBytes = bytes.length;
598
+ } catch {
599
+ artifactRef = null;
600
+ artifactBytes = 0;
601
+ warnings.push({ code: 'primetech_artifact_write_failed', message: 'The procedure succeeded, but its JSON artifact could not be persisted.' });
602
+ }
603
+ }
604
+ record.timings_ms.persistence = Math.max(0, now() - persistenceStarted);
605
+ const receipt = persistReceipt('completed');
606
+ if (!receipt) warnings.push({ code: 'sam_receipt_write_failed', message: 'The procedure succeeded, but its local receipt could not be persisted.' });
607
+ const response = {
608
+ schema: 'inneranimalmedia.primetech.procedure-run.v1',
609
+ id: manifest.id,
610
+ version: manifest.version,
611
+ status: 'completed',
612
+ effect: manifest.effect,
613
+ output,
614
+ artifact: artifactRef ? { ref: artifactRef, sha256: artifactSha256, bytes: artifactBytes } : null,
615
+ verification,
616
+ execution: {
617
+ operation: executedOperation,
618
+ runtime_kind: manifest.runtime.kind,
619
+ execution_id: execution.executionId || execution.execution_id || null,
620
+ source_receipt_id: sourceReceipt?.id || null,
621
+ script_sha256: execution.scriptHash || execution.script_sha256 || null,
622
+ status: execution.status,
623
+ exit_code: execution.exitCode ?? execution.exit_code ?? null,
624
+ duration_ms: execution.durationMs ?? execution.duration_ms ?? null,
625
+ script_bytes: execution.scriptBytes ?? execution.script_bytes ?? null,
626
+ },
627
+ receipt: receipt ? { id: runId, ...receipt } : { id: runId, written: false },
628
+ duration_ms: Math.max(0, now() - started),
629
+ };
630
+ if (warnings.length) response.warnings = warnings;
631
+ return response;
632
+ } catch (error) {
633
+ errorCode = error.code || 'primetech_procedure_failed';
634
+ errorMessage = error.message || errorCode;
635
+ const receipt = persistReceipt('failed');
636
+ const wrapped = new PrimetechProcedureError(errorCode, errorMessage, {
637
+ receipt: receipt ? { id: runId, ...receipt } : { id: runId, written: false },
638
+ ...(!receipt ? { warnings: [{ code: 'sam_receipt_write_failed', message: 'The failed procedure could not persist its receipt.' }] } : {}),
639
+ ...(error.details ? { details: error.details } : {}),
640
+ });
641
+ throw wrapped;
642
+ }
643
+ };
644
+ }
645
+
646
+ export { DEFAULT_CATALOG_ROOT };
647
+
648
+ export { buildIconFamily, PRIMETECH_ICON_COLORWAY_IDS, PRIMETECH_ICON_SHAPES, PRIMETECH_ICON_SIZES } from './creative/icon-family.js';
649
+ export { buildTypefacePackage } from './creative/typeface.js';
650
+ export { buildSpriteAtlas } from './creative/sprite-atlas.js';
651
+ export { compareVisuals } from './creative/visual-qa.js';
652
+ export { buildDesignSystemPackage } from './creative/design-system.js';
653
+ export { packageCreativeAssets } from './creative/asset-package.js';
654
+ export { buildEpubPackage } from './creative/ebook.js';
655
+ export { createProductionBoard, getProductionBoard, listProductionBoards, beginGeneration, completeGeneration, failGeneration, resumeProductionBoard, productionBoardContract } from './production-board.js';
656
+ export { loadPrimeTechSkillCatalog, validatePrimeTechSkillPackage, getPrimeTechSkill, PRIMETECH_SKILL_CONTRACT_SECTIONS } from './skills.js';