openyida 2026.10.13 → 2026.10.14

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 (62) hide show
  1. package/README.md +76 -23
  2. package/bin/yida.js +32 -2
  3. package/lib/agent/PROTOCOL.md +201 -0
  4. package/lib/agent/ask-human-help.js +19 -0
  5. package/lib/agent/ask-human.js +222 -0
  6. package/lib/agent/cmd.js +405 -0
  7. package/lib/agent/command-receipt.js +84 -0
  8. package/lib/agent/connection-store.js +148 -0
  9. package/lib/agent/diagnostic-log.js +133 -0
  10. package/lib/agent/frozen-bundle.js +298 -0
  11. package/lib/agent/managed-command-map.js +47 -0
  12. package/lib/agent/managed-context.js +40 -0
  13. package/lib/agent/managed-run.js +84 -0
  14. package/lib/agent/mutation-receipt.js +82 -0
  15. package/lib/agent/private-directory.js +63 -0
  16. package/lib/agent/provider-preflight.js +257 -0
  17. package/lib/agent/providers.js +4 -0
  18. package/lib/agent/runtime-catalog.json +42 -0
  19. package/lib/agent/runtime-manifest.js +96 -0
  20. package/lib/agent/runtime-package.js +155 -0
  21. package/lib/agent/stdio.js +321 -0
  22. package/lib/app/check-prd-completeness.js +15 -4
  23. package/lib/app/create-form/batch.js +30 -9
  24. package/lib/app/create-form.js +7 -2
  25. package/lib/app/custom-theme.js +13 -3
  26. package/lib/app/get-schema.js +6 -1
  27. package/lib/app/update-app.js +13 -1
  28. package/lib/app/update-form-config.js +71 -80
  29. package/lib/asset/asset-plan.js +6 -4
  30. package/lib/auth/profile-lock.js +89 -0
  31. package/lib/auth/token-auth.js +57 -6
  32. package/lib/auth/token-store.js +26 -2
  33. package/lib/core/command-manifest.js +202 -118
  34. package/lib/core/locales/en.js +48 -4
  35. package/lib/core/locales/zh.js +48 -4
  36. package/lib/core/managed-policy.js +88 -0
  37. package/lib/core/query-data.js +22 -3
  38. package/lib/core/sample.js +1 -0
  39. package/lib/core/update.js +3 -1
  40. package/lib/core/utils.js +34 -1
  41. package/lib/design-plan/materialize.js +4 -21
  42. package/lib/design-plan/render-html.js +299 -0
  43. package/lib/page-config/save-share-config.js +16 -5
  44. package/lib/samples/yida-data-management/empty-query.js +69 -0
  45. package/package.json +10 -1
  46. package/scripts/postinstall.js +2 -2
  47. package/yida-skills/SKILL.md +32 -2
  48. package/yida-skills/references/local-agent-diagnostics.md +154 -0
  49. package/yida-skills/references/local-agent-preflight.md +56 -0
  50. package/yida-skills/references/query-condition-guide.md +223 -195
  51. package/yida-skills/skills/yida-app/workflow/plan/step-4-deliver.md +11 -3
  52. package/yida-skills/skills/yida-canvas-data-binding/SKILL.md +8 -5
  53. package/yida-skills/skills/yida-data-management/SKILL.md +64 -19
  54. package/yida-skills/skills/yida-data-management/references/data-format-guide.md +61 -25
  55. package/yida-skills/skills/yida-data-source-connectors/SKILL.md +6 -0
  56. package/yida-skills/skills/yida-design/SKILL.md +2 -0
  57. package/yida-skills/skills/yida-design/references/ask-human-interaction-contract.md +2 -0
  58. package/yida-skills/skills/yida-design/templates/design-themes/README.md +1 -1
  59. package/yida-skills/skills/yida-document-markdown/SKILL.md +6 -0
  60. package/yida-skills/skills/yida-image-assets/SKILL.md +1 -1
  61. package/yida-skills/skills/yida-tingji/SKILL.md +4 -0
  62. package/yida-skills/skills-index.json +52 -7
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { TextDecoder } = require('util');
5
+ const { CliError } = require('../core/cli-error');
6
+ const { t } = require('../core/i18n');
7
+
8
+ const MAX_MANIFEST_BYTES = 64 * 1024;
9
+ const MAX_BINARY_BYTES = 256 * 1024 * 1024;
10
+ const SHA256 = /^[a-f0-9]{64}$/;
11
+ const PRODUCTION_RUNTIME_PLATFORMS = Object.freeze(['darwin', 'win32']);
12
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
13
+
14
+ function invalid(code = 'AGENT_RUNTIME_INVALID_MANIFEST', key = 'manifest_invalid') {
15
+ return new CliError(t(`agent.${key}`), { code });
16
+ }
17
+
18
+ function exactKeys(value, keys) {
19
+ return value !== null && typeof value === 'object' && !Array.isArray(value) &&
20
+ Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
21
+ }
22
+
23
+ // JSON.parse alone silently accepts duplicate keys. Keep signed metadata
24
+ // unambiguous across Go and Node JSON implementations, including escaped keys.
25
+ function parseStrictJson(bytes, maxBytes = MAX_MANIFEST_BYTES) {
26
+ if (!Buffer.isBuffer(bytes) || bytes.length > maxBytes || !bytes.length) {throw invalid();}
27
+ try {
28
+ const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
29
+ const result = JSON.parse(source);
30
+ const tokens = source.match(/"(?:[^"\\]|\\.)*"|[{}[\]:,]|true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g);
31
+ let index = 0;
32
+ const visit = (depth) => {
33
+ if (depth > 32) {throw invalid();}
34
+ const token = tokens[index++];
35
+ if (token === '{') {
36
+ const keys = new Set();
37
+ while (tokens[index] !== '}') {
38
+ const key = JSON.parse(tokens[index++]);
39
+ if (keys.has(key) || ['__proto__', 'constructor', 'prototype'].includes(key)) {throw invalid();}
40
+ keys.add(key);
41
+ index++; // colon; JSON.parse has already checked the grammar
42
+ visit(depth + 1);
43
+ if (tokens[index] !== ',') {break;}
44
+ index++;
45
+ }
46
+ index++;
47
+ } else if (token === '[') {
48
+ while (tokens[index] !== ']') {
49
+ visit(depth + 1);
50
+ if (tokens[index] !== ',') {break;}
51
+ index++;
52
+ }
53
+ index++;
54
+ }
55
+ };
56
+ visit(0);
57
+ return result;
58
+ } catch {throw invalid();}
59
+ }
60
+
61
+ function positive(value) {return Number.isSafeInteger(value) && value >= 1;}
62
+ function range(value) {return exactKeys(value, ['min', 'max']) && positive(value.min) && positive(value.max) && value.min <= value.max;}
63
+
64
+ function decodeManifestV2(bytes) {
65
+ const m = parseStrictJson(bytes);
66
+ if (!exactKeys(m, ['schemaVersion', 'product', 'runtimeVersion', 'sourceRevision', 'platform', 'arch', 'launcherProtocol', 'wireProtocol', 'stateSchema', 'binary', 'releaseId', 'keyId']) ||
67
+ m.schemaVersion !== 2 || m.product !== 'openyida-local-agent-runtime' ||
68
+ typeof m.runtimeVersion !== 'string' || m.runtimeVersion.length > 100 || !VERSION.test(m.runtimeVersion) ||
69
+ typeof m.sourceRevision !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(m.sourceRevision) ||
70
+ !PRODUCTION_RUNTIME_PLATFORMS.includes(m.platform) || !['arm64', 'x64'].includes(m.arch) ||
71
+ !range(m.launcherProtocol) || !range(m.wireProtocol) ||
72
+ !exactKeys(m.stateSchema, ['write', 'readMin', 'readMax']) ||
73
+ !positive(m.stateSchema.write) || !positive(m.stateSchema.readMin) || !positive(m.stateSchema.readMax) ||
74
+ m.stateSchema.readMin > m.stateSchema.write || m.stateSchema.write > m.stateSchema.readMax ||
75
+ !exactKeys(m.binary, ['file', 'size', 'sha256']) ||
76
+ m.binary.file !== `bin/openyida-agent-runtime${m.platform === 'win32' ? '.exe' : ''}` ||
77
+ !positive(m.binary.size) || m.binary.size > MAX_BINARY_BYTES || !SHA256.test(m.binary.sha256) ||
78
+ typeof m.releaseId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(m.releaseId) ||
79
+ typeof m.keyId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(m.keyId)) {throw invalid();}
80
+ return m;
81
+ }
82
+
83
+ function verifyManifestSignature(bytes, signatureBytes, manifest, trustedKeys) {
84
+ const key = trustedKeys && Object.hasOwn(trustedKeys, manifest.keyId) && trustedKeys[manifest.keyId];
85
+ if (!key || key.revoked || typeof key.publicKey !== 'string') {throw invalid('AGENT_RUNTIME_SIGNATURE_FAILED', 'signature_failed');}
86
+ try {
87
+ const encoded = signatureBytes.toString('ascii');
88
+ if (!/^[A-Za-z0-9+/]{86}==\n?$/.test(encoded)) {throw invalid();}
89
+ const signature = Buffer.from(encoded.trim(), 'base64');
90
+ const publicKey = crypto.createPublicKey(key.publicKey);
91
+ if (signature.toString('base64') !== encoded.trim() || publicKey.asymmetricKeyType !== 'ed25519' ||
92
+ !crypto.verify(null, bytes, publicKey, signature)) {throw invalid();}
93
+ } catch {throw invalid('AGENT_RUNTIME_SIGNATURE_FAILED', 'signature_failed');}
94
+ }
95
+
96
+ module.exports = { MAX_MANIFEST_BYTES, MAX_BINARY_BYTES, SHA256, PRODUCTION_RUNTIME_PLATFORMS, decodeManifestV2, verifyManifestSignature, parseStrictJson, exactKeys };
@@ -0,0 +1,155 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+ const { createRequire } = require('module');
7
+ const { CliError } = require('../core/cli-error');
8
+ const { t } = require('../core/i18n');
9
+ const { MAX_MANIFEST_BYTES, MAX_BINARY_BYTES, SHA256, PRODUCTION_RUNTIME_PLATFORMS, decodeManifestV2, verifyManifestSignature, parseStrictJson, exactKeys } = require('./runtime-manifest');
10
+ const bundledCatalog = require('./runtime-catalog.json');
11
+
12
+ const PROTOCOL_VERSION = 1;
13
+
14
+ function runtimeError(code, key) {
15
+ return new CliError(t(`agent.${key}`), { code });
16
+ }
17
+
18
+ function requireAbsoluteFile(value, code) {
19
+ if (typeof value !== 'string' || !path.isAbsolute(value)) {
20
+ throw runtimeError(code, 'absolute_path_required');
21
+ }
22
+ let stat;
23
+ try {
24
+ stat = fs.lstatSync(value);
25
+ } catch {
26
+ throw runtimeError(code, 'runtime_missing');
27
+ }
28
+ if (!stat.isFile() || stat.isSymbolicLink()) {
29
+ throw runtimeError(code, 'unsafe_file');
30
+ }
31
+ return { path: fs.realpathSync(value), stat };
32
+ }
33
+
34
+ function readRegularFile(filename, maxBytes, code = 'AGENT_RUNTIME_INVALID_PATH') {
35
+ const file = requireAbsoluteFile(filename, code);
36
+ if (file.stat.size > maxBytes) {throw runtimeError(code, 'unsafe_file');}
37
+ let descriptor;
38
+ try {
39
+ descriptor = fs.openSync(file.path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
40
+ const opened = fs.fstatSync(descriptor);
41
+ if (!opened.isFile() || opened.size > maxBytes || opened.ino !== file.stat.ino || opened.dev !== file.stat.dev) {throw new Error('changed file');}
42
+ const bytes = fs.readFileSync(descriptor);
43
+ if (bytes.length > maxBytes || bytes.length !== opened.size) {throw new Error('changed file');}
44
+ return { ...file, bytes };
45
+ } catch {throw runtimeError(code, 'unsafe_file');}
46
+ finally {if (descriptor !== undefined) {fs.closeSync(descriptor);}}
47
+ }
48
+
49
+ function checkExecutable(binary, platform) {
50
+ if (platform !== 'win32') {
51
+ try {fs.accessSync(binary.path, fs.constants.X_OK);}
52
+ catch {throw runtimeError('AGENT_RUNTIME_NOT_EXECUTABLE', 'runtime_not_executable');}
53
+ }
54
+ }
55
+
56
+ function digest(bytes) {return crypto.createHash('sha256').update(bytes).digest('hex');}
57
+
58
+ function resolveDevelopment(options) {
59
+ if (!options.runtimePath || !options.manifestPath) {throw runtimeError('AGENT_RUNTIME_NOT_CONFIGURED', 'runtime_not_configured');}
60
+ const binary = readRegularFile(options.runtimePath, MAX_BINARY_BYTES);
61
+ const file = readRegularFile(options.manifestPath, MAX_MANIFEST_BYTES, 'AGENT_RUNTIME_INVALID_MANIFEST');
62
+ const manifest = parseStrictJson(file.bytes);
63
+ if (!exactKeys(manifest, ['schemaVersion', 'version', 'protocolVersion', 'platform', 'arch', 'binary']) || manifest.schemaVersion !== 1 ||
64
+ typeof manifest.version !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9.+_-]{0,99}$/.test(manifest.version) ||
65
+ !exactKeys(manifest.binary, ['file', 'sha256']) || typeof manifest.binary.file !== 'string' ||
66
+ path.basename(manifest.binary.file) !== manifest.binary.file ||
67
+ manifest.binary.file !== path.basename(binary.path) ||
68
+ !/^[a-f0-9]{64}$/i.test(manifest.binary.sha256 || '')) {
69
+ throw runtimeError('AGENT_RUNTIME_INVALID_MANIFEST', 'manifest_invalid');
70
+ }
71
+ if (manifest.protocolVersion !== PROTOCOL_VERSION) {
72
+ throw runtimeError('AGENT_RUNTIME_PROTOCOL_UNSUPPORTED', 'protocol_unsupported');
73
+ }
74
+ if (manifest.platform !== (options.platform || process.platform) ||
75
+ manifest.arch !== (options.arch || process.arch)) {
76
+ throw runtimeError('AGENT_RUNTIME_PLATFORM_UNSUPPORTED', 'platform_unsupported');
77
+ }
78
+ checkExecutable(binary, options.platform || process.platform);
79
+ const sha256 = digest(binary.bytes);
80
+ if (sha256 !== manifest.binary.sha256.toLowerCase()) {
81
+ throw runtimeError('AGENT_RUNTIME_INTEGRITY_FAILED', 'integrity_failed');
82
+ }
83
+ return { executable: binary.path, manifestPath: file.path, manifest, sha256, binaryBytes: binary.bytes, manifestBytes: file.bytes, runtimeVersion: manifest.version, development: true };
84
+ }
85
+
86
+ function platformPackageName(platform, arch) {
87
+ if (!PRODUCTION_RUNTIME_PLATFORMS.includes(platform) || !['arm64', 'x64'].includes(arch)) {
88
+ throw runtimeError('AGENT_RUNTIME_PLATFORM_UNSUPPORTED', 'platform_unsupported');
89
+ }
90
+ // Public runtime packages are pinned by the signed release catalog.
91
+ return `@openyida/local-agent-runtime-${platform}-${arch}`;
92
+ }
93
+
94
+ function safePackageFile(root, relative) {
95
+ let current = root;
96
+ for (const component of relative.split('/')) {
97
+ if (!component || component === '.' || component === '..' || component.includes('\\')) {throw runtimeError('AGENT_RUNTIME_INVALID_PATH', 'unsafe_file');}
98
+ current = path.join(current, component);
99
+ let stat;
100
+ try {stat = fs.lstatSync(current);} catch {throw runtimeError('AGENT_RUNTIME_INVALID_PATH', 'runtime_missing');}
101
+ if (stat.isSymbolicLink()) {throw runtimeError('AGENT_RUNTIME_INVALID_PATH', 'unsafe_file');}
102
+ }
103
+ return current;
104
+ }
105
+
106
+ function resolveProduction(options) {
107
+ const platform = options.platform || process.platform;
108
+ const arch = options.arch || process.arch;
109
+ const name = platformPackageName(platform, arch);
110
+ // The catalog and roots are part of the Node host, never read from a platform
111
+ // package or network. Injection is an internal unit-test seam, not a CLI flag.
112
+ const catalog = options.catalog || bundledCatalog;
113
+ const releases = catalog.schemaVersion === 1 && Array.isArray(catalog.releases) ? catalog.releases.filter((entry) => entry.platform === platform && entry.arch === arch) : [];
114
+ if (releases.length !== 1) {throw runtimeError('AGENT_RUNTIME_NOT_CONFIGURED', 'runtime_not_configured');}
115
+ const release = releases[0];
116
+ if (release.packageName !== name || !SHA256.test(release.manifestSha256 || '') || !release.packageVersion || !release.runtimeVersion) {
117
+ throw runtimeError('AGENT_RUNTIME_INVALID_MANIFEST', 'manifest_invalid');
118
+ }
119
+ const packageRoot = path.resolve(options.packageRoot || path.join(__dirname, '..', '..'));
120
+ let installedRoot;
121
+ try {
122
+ const main = parseStrictJson(readRegularFile(path.join(packageRoot, 'package.json'), MAX_MANIFEST_BYTES).bytes);
123
+ if (!main.optionalDependencies || main.optionalDependencies[name] !== release.packageVersion) {throw new Error('unapproved dependency');}
124
+ const localRequire = createRequire(path.join(packageRoot, 'package.json'));
125
+ installedRoot = path.dirname(fs.realpathSync(localRequire.resolve(`${name}/package.json`)));
126
+ const metadata = parseStrictJson(readRegularFile(safePackageFile(installedRoot, 'package.json'), MAX_MANIFEST_BYTES).bytes);
127
+ if (metadata.name !== name || metadata.version !== release.packageVersion ||
128
+ !Array.isArray(metadata.os) || metadata.os.length !== 1 || metadata.os[0] !== platform ||
129
+ !Array.isArray(metadata.cpu) || metadata.cpu.length !== 1 || metadata.cpu[0] !== arch ||
130
+ metadata.scripts && Object.keys(metadata.scripts).length) {throw new Error('wrong platform package');}
131
+ } catch {throw runtimeError('AGENT_RUNTIME_PACKAGE_UNAVAILABLE', 'runtime_not_configured');}
132
+ const file = readRegularFile(safePackageFile(installedRoot, 'runtime-manifest.json'), MAX_MANIFEST_BYTES, 'AGENT_RUNTIME_INVALID_MANIFEST');
133
+ const manifest = decodeManifestV2(file.bytes);
134
+ const signature = readRegularFile(safePackageFile(installedRoot, 'runtime-manifest.sig'), 128, 'AGENT_RUNTIME_SIGNATURE_FAILED');
135
+ verifyManifestSignature(file.bytes, signature.bytes, manifest, catalog.keys);
136
+ if (digest(file.bytes) !== release.manifestSha256 || manifest.runtimeVersion !== release.runtimeVersion) {throw runtimeError('AGENT_RUNTIME_INTEGRITY_FAILED', 'integrity_failed');}
137
+ if (manifest.platform !== platform || manifest.arch !== arch) {throw runtimeError('AGENT_RUNTIME_PLATFORM_UNSUPPORTED', 'platform_unsupported');}
138
+ if ([manifest.launcherProtocol, manifest.wireProtocol].some((range) => range.min > PROTOCOL_VERSION || range.max < PROTOCOL_VERSION)) {
139
+ throw runtimeError('AGENT_RUNTIME_PROTOCOL_UNSUPPORTED', 'protocol_unsupported');
140
+ }
141
+ const binary = readRegularFile(safePackageFile(installedRoot, manifest.binary.file), MAX_BINARY_BYTES);
142
+ checkExecutable(binary, platform);
143
+ const sha256 = digest(binary.bytes);
144
+ if (binary.bytes.length !== manifest.binary.size || sha256 !== manifest.binary.sha256) {throw runtimeError('AGENT_RUNTIME_INTEGRITY_FAILED', 'integrity_failed');}
145
+ return { executable: binary.path, manifestPath: file.path, signaturePath: signature.path, manifest, sha256, binaryBytes: binary.bytes,
146
+ manifestBytes: file.bytes, signatureBytes: signature.bytes, runtimeVersion: manifest.runtimeVersion, development: false };
147
+ }
148
+
149
+ function resolveRuntime(options = {}) {
150
+ if (options.developmentRuntime === true) {return resolveDevelopment(options);}
151
+ if (options.runtimePath || options.manifestPath) {throw runtimeError('AGENT_RUNTIME_DEVELOPMENT_REQUIRED', 'development_required');}
152
+ return resolveProduction(options);
153
+ }
154
+
155
+ module.exports = { PROTOCOL_VERSION, resolveRuntime, requireAbsoluteFile, readRegularFile, digest, platformPackageName };
@@ -0,0 +1,321 @@
1
+ 'use strict';
2
+
3
+ const { spawn } = require('child_process');
4
+ const fs = require('fs');
5
+ const { randomUUID } = require('crypto');
6
+ const path = require('path');
7
+ const { EventEmitter } = require('events');
8
+ const { StringDecoder } = require('string_decoder');
9
+ const { CliError } = require('../core/cli-error');
10
+ const { t } = require('../core/i18n');
11
+
12
+ const MAX_CONFIG_BYTES = 64 * 1024;
13
+ const MAX_OUTPUT_LINE_BYTES = 256 * 1024;
14
+ const BACKGROUND_LOG_NAME = 'agent-run.log';
15
+ const ENV_KEYS = [
16
+ 'USERPROFILE', 'DBUS_SESSION_BUS_ADDRESS', 'XDG_RUNTIME_DIR', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'PATH', 'TMPDIR', 'TMP', 'TEMP',
17
+ 'SystemRoot', 'SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'APPDATA', 'LOCALAPPDATA',
18
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
19
+ 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy', 'SSL_CERT_FILE',
20
+ 'NODE_EXTRA_CA_CERTS', 'OPENYIDA_AUTH_DIR', 'OPENYIDA_LANG',
21
+ // Go needs the original provider home before creating its isolated home.
22
+ // Only its location crosses this boundary; provider token env does not.
23
+ 'CODEX_HOME', 'QODER_CONFIG_DIR',
24
+ ];
25
+
26
+ function runtimeEnvironment(env = process.env) {
27
+ const result = {};
28
+ for (const key of ENV_KEYS) {
29
+ if (env[key] !== undefined) {result[key] = env[key];}
30
+ }
31
+ // npm CLI shebangs must find the same Node that successfully started OpenYida,
32
+ // even when OpenYida itself was launched through an absolute Node path.
33
+ result.PATH = [path.dirname(process.execPath), env.PATH || env.Path || env.path || ''].filter(Boolean).join(path.delimiter);
34
+ result.OPENYIDA_NO_AUTO_UPDATE = '1';
35
+ result.OPENYIDA_MANAGED_RUNTIME = 'local';
36
+ return result;
37
+ }
38
+
39
+ function readStdinJson(input = process.stdin, limit = MAX_CONFIG_BYTES) {
40
+ return new Promise((resolve, reject) => {
41
+ const chunks = [];
42
+ let size = 0;
43
+ let failed = false;
44
+ function fail() {
45
+ if (failed) {return;}
46
+ failed = true;
47
+ reject(new CliError(t('agent.input_invalid'), { code: 'AGENT_INPUT_INVALID' }));
48
+ }
49
+ input.on('data', (chunk) => {
50
+ size += Buffer.byteLength(chunk);
51
+ if (size > limit) {fail(); input.pause(); return;}
52
+ chunks.push(Buffer.from(chunk));
53
+ });
54
+ input.once('error', fail);
55
+ input.once('end', () => {
56
+ if (failed) {return;}
57
+ try {
58
+ const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
59
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {fail(); return;}
60
+ resolve(data);
61
+ } catch {fail();}
62
+ });
63
+ });
64
+ }
65
+
66
+ // The launcher forwards signals; only Go owns provider cancellation, journal,
67
+ // reconnection and child processes. No cloud transport or retry loop lives here.
68
+ function launchRuntime(runtime, config, options = {}) {
69
+ const watchesParent = ['connect', 'run'].includes(config.command);
70
+ if (watchesParent) {config = process.platform === 'win32'
71
+ ? { ...config, parentPID: process.pid } : { ...config, parentWatchFD: 3 };}
72
+ const payload = JSON.stringify(config);
73
+ if (Buffer.byteLength(payload) > MAX_CONFIG_BYTES) {
74
+ throw new CliError(t('agent.input_invalid'), { code: 'AGENT_INPUT_INVALID' });
75
+ }
76
+ const stdout = options.stdout || process.stdout;
77
+ const signals = options.signals || process;
78
+ return new Promise((resolve, reject) => {
79
+ const diagnostic = typeof options.diagnostic === 'function' ? options.diagnostic : () => {};
80
+ let child;
81
+ let failure;
82
+ let pending = '';
83
+ let killTimer;
84
+ let stopping = false;
85
+ let closed = false;
86
+ let receivedEvent = false;
87
+ const decoder = new StringDecoder('utf8');
88
+ function stop(signal) {
89
+ if (closed) {return;}
90
+ if (stopping) {return;}
91
+ stopping = true;
92
+ if (process.platform === 'win32' && config.command === 'run') {
93
+ // Windows child.kill does not deliver a catchable Unix signal. Ask the
94
+ // owning Runtime to drain through its authenticated loopback control.
95
+ const stopConfig = { ...config, command: 'disconnect', parentPID: 0, parentWatchFD: 0 };
96
+ launchRuntime(runtime, stopConfig, { ...options, signals: new EventEmitter(), stdout: { write() {} } })
97
+ .catch(() => { /* Bounded force-stop below preserves unknown status. */ });
98
+ } else {
99
+ child.kill(signal);
100
+ }
101
+ if (killTimer) {return;}
102
+ killTimer = setTimeout(() => {
103
+ failure = new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_STOP_UNCONFIRMED', details: { executionState: 'unknown' } });
104
+ child.kill('SIGKILL');
105
+ }, options.stopGraceMs === undefined ? 15000 : options.stopGraceMs);
106
+ killTimer.unref();
107
+ }
108
+ const forwardInterrupt = () => stop('SIGINT');
109
+ const forwardTerminate = () => stop('SIGTERM');
110
+ function fail(code = 'AGENT_RUNTIME_OUTPUT_INVALID') {
111
+ if (failure) {return;}
112
+ diagnostic('error', 'runtime_output_failed', { command: config.command, component: 'node', errorCode: code });
113
+ failure = new CliError(t('agent.runtime_failed'), { code });
114
+ stop('SIGTERM');
115
+ }
116
+ function emitLine(line) {
117
+ if (!line.trim() || failure) {return;}
118
+ try {
119
+ if (Buffer.byteLength(line) > MAX_OUTPUT_LINE_BYTES) {fail(); return;}
120
+ const event = JSON.parse(line);
121
+ if (!event || typeof event.type !== 'string' || !event.type || Array.isArray(event)) {fail(); return;}
122
+ receivedEvent = true;
123
+ if (event.type === 'error') {
124
+ const code = typeof event.code === 'string' && /^[A-Z0-9_]{1,100}$/.test(event.code)
125
+ ? event.code : 'AGENT_RUNTIME_FAILED';
126
+ diagnostic('error', 'runtime_action_failed', {
127
+ command: config.command, component: 'node', errorCode: code, retryable: event.retryable === true,
128
+ });
129
+ failure = new CliError(t('agent.runtime_failed'), { code, details: { retryable: event.retryable === true } });
130
+ stop('SIGTERM');
131
+ return;
132
+ }
133
+ stdout.write(`${JSON.stringify(event)}\n`);
134
+ } catch {fail();}
135
+ }
136
+ try {
137
+ child = (options.spawn || spawn)(runtime.executable, [config.command, '--stdio-config'], {
138
+ cwd: config.node.packageRoot,
139
+ env: runtimeEnvironment(options.env),
140
+ stdio: watchesParent ? ['pipe', 'pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe'],
141
+ windowsHide: true,
142
+ shell: false,
143
+ });
144
+ diagnostic('info', 'runtime_spawned', { command: config.command, component: 'node' });
145
+ } catch {
146
+ diagnostic('error', 'runtime_spawn_failed', { command: config.command, component: 'node', errorCode: 'AGENT_RUNTIME_START_FAILED' });
147
+ reject(new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_START_FAILED' }));
148
+ return;
149
+ }
150
+ signals.on('SIGINT', forwardInterrupt);
151
+ signals.on('SIGTERM', forwardTerminate);
152
+ // Config stdin intentionally reaches EOF after one JSON. This distinct
153
+ // pipe remains open for the parent lifetime; Go treats EOF as stop/drain,
154
+ // not successful completion. Do not send credentials on the watch pipe.
155
+ const parentWatch = watchesParent && child.stdio && child.stdio[3];
156
+ if (parentWatch) {parentWatch.on('error', () => {if (!closed) {fail('AGENT_RUNTIME_PARENT_WATCH_FAILED');}});}
157
+ child.stdout.on('data', (chunk) => {
158
+ pending += decoder.write(chunk);
159
+ let newline;
160
+ while ((newline = pending.indexOf('\n')) !== -1) {
161
+ const line = pending.slice(0, newline);
162
+ pending = pending.slice(newline + 1);
163
+ emitLine(line);
164
+ }
165
+ if (Buffer.byteLength(pending) > MAX_OUTPUT_LINE_BYTES) {pending = ''; fail();}
166
+ });
167
+ // Runtime diagnostics must be structured on stdout. Drain untrusted stderr
168
+ // without echoing potential credentials or uncontrolled provider output.
169
+ child.stderr.on('data', () => {});
170
+ child.stdin.on('error', () => fail('AGENT_RUNTIME_INPUT_FAILED'));
171
+ child.once('error', () => {
172
+ diagnostic('error', 'runtime_spawn_failed', { command: config.command, component: 'node', errorCode: 'AGENT_RUNTIME_START_FAILED' });
173
+ failure = new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_START_FAILED' });
174
+ });
175
+ child.once('close', (code, signal) => {
176
+ diagnostic(code === 0 ? 'info' : 'error', 'runtime_closed', { command: config.command, component: 'node', closeCode: typeof code === 'number' ? code : -1, status: signal || (code === 0 ? 'completed' : 'failed') });
177
+ closed = true;
178
+ signals.removeListener('SIGINT', forwardInterrupt);
179
+ signals.removeListener('SIGTERM', forwardTerminate);
180
+ pending += decoder.end();
181
+ if (pending) {emitLine(pending);}
182
+ clearTimeout(killTimer);
183
+ if (parentWatch) {parentWatch.destroy();}
184
+ if (failure) {reject(failure); return;}
185
+ if (!receivedEvent) {reject(new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_OUTPUT_INVALID' })); return;}
186
+ if (code !== 0 || signal) {
187
+ reject(new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_FAILED', details: { exitCode: code, signal } }));
188
+ return;
189
+ }
190
+ resolve();
191
+ });
192
+ child.stdin.end(`${payload}\n`);
193
+ });
194
+ }
195
+
196
+ // The per-connection background daemon writes its structured runtime events and
197
+ // untrusted provider stderr to this file so `openyida agent logs` can surface
198
+ // them after the launcher has already returned the terminal.
199
+ function backgroundLogPath(config) {
200
+ return path.join(config.stateDir, 'logs', BACKGROUND_LOG_NAME);
201
+ }
202
+
203
+ // Launch the Go runtime as a detached background daemon. Unlike launchRuntime,
204
+ // this deliberately does NOT bind the runtime lifetime to the launcher: the
205
+ // daemon survives terminal/desktop close and is governed only by its own owner
206
+ // lock and the authenticated loopback control socket, so `disconnect` remains
207
+ // the way to stop it. No parent-lifetime pipe is attached. Output is redirected
208
+ // to a per-connection log file. Resolves only after a private, launch-specific
209
+ // readiness receipt; provider stderr and stale log entries cannot signal ready.
210
+ function launchBackgroundRuntime(runtime, config, options = {}) {
211
+ if (config.command !== 'run') {
212
+ throw new CliError(t('agent.input_invalid'), { code: 'AGENT_INPUT_INVALID' });
213
+ }
214
+ const daemonConfig = { ...config, background: true, startupId: randomUUID() };
215
+ delete daemonConfig.parentWatchFD;
216
+ delete daemonConfig.parentPID;
217
+ const payload = JSON.stringify(daemonConfig);
218
+ if (Buffer.byteLength(payload) > MAX_CONFIG_BYTES) {
219
+ throw new CliError(t('agent.input_invalid'), { code: 'AGENT_INPUT_INVALID' });
220
+ }
221
+ const diagnostic = typeof options.diagnostic === 'function' ? options.diagnostic : () => {};
222
+ const logPath = backgroundLogPath(daemonConfig);
223
+ const startupPath = path.join(daemonConfig.stateDir, `startup-${daemonConfig.startupId}.json`);
224
+ return new Promise((resolve, reject) => {
225
+ let logFd;
226
+ try {
227
+ fs.mkdirSync(path.dirname(logPath), { recursive: true, mode: 0o700 });
228
+ logFd = fs.openSync(logPath, 'a', 0o600);
229
+ } catch {
230
+ reject(new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_START_FAILED' }));
231
+ return;
232
+ }
233
+ let child;
234
+ try {
235
+ child = (options.spawn || spawn)(runtime.executable, [daemonConfig.command, '--stdio-config'], {
236
+ cwd: daemonConfig.node.packageRoot,
237
+ env: runtimeEnvironment(options.env),
238
+ // stdout and stderr are redirected to the daemon log; stdin carries the
239
+ // one launch-config JSON and then reaches EOF, which the daemon ignores.
240
+ stdio: ['pipe', logFd, logFd],
241
+ detached: true,
242
+ windowsHide: true,
243
+ shell: false,
244
+ });
245
+ } catch {
246
+ try {fs.closeSync(logFd);} catch { /* already closed */ }
247
+ diagnostic('error', 'runtime_spawn_failed', { command: daemonConfig.command, component: 'node', errorCode: 'AGENT_RUNTIME_START_FAILED' });
248
+ reject(new CliError(t('agent.runtime_failed'), { code: 'AGENT_RUNTIME_START_FAILED' }));
249
+ return;
250
+ }
251
+ // The child holds its own duplicated descriptor after spawn; releasing the
252
+ // launcher's copy keeps no handle that would tie the daemon to this process.
253
+ try {fs.closeSync(logFd);} catch { /* child owns its dup */ }
254
+ let settled = false;
255
+ let finished = false;
256
+ let stopTimer;
257
+ const removeReceipt = () => { try {fs.unlinkSync(startupPath);} catch { /* absent/failed startup */ } };
258
+ const fail = (code) => {
259
+ if (settled) {return;}
260
+ settled = true;
261
+ clearInterval(pollTimer);
262
+ clearTimeout(startupTimer);
263
+ diagnostic('error', 'runtime_spawn_failed', { command: daemonConfig.command, component: 'node', errorCode: code });
264
+ const error = new CliError(t('agent.runtime_failed'), { code, details: { logPath } });
265
+ // Stop only this newly spawned child. Keep its state/journals for recovery.
266
+ // Give the Go runtime its normal drain window before forcing termination.
267
+ if (!finished && child.pid) {
268
+ try {child.kill('SIGTERM');} catch { /* exit event may already be queued */ }
269
+ stopTimer = setTimeout(() => {
270
+ try {child.kill('SIGKILL');} catch { /* already exited */ }
271
+ removeReceipt();
272
+ reject(error);
273
+ }, options.stopTimeoutMs ?? 15000);
274
+ child.once('close', () => { clearTimeout(stopTimer); removeReceipt(); reject(error); });
275
+ } else {
276
+ removeReceipt();
277
+ reject(error);
278
+ }
279
+ };
280
+ child.once('error', () => { finished = true; fail('AGENT_RUNTIME_START_FAILED'); });
281
+ child.once('close', () => {
282
+ finished = true;
283
+ removeReceipt();
284
+ fail('AGENT_RUNTIME_START_FAILED');
285
+ });
286
+ const checkReady = () => {
287
+ if (settled) {return;}
288
+ let fd;
289
+ try {
290
+ fd = fs.openSync(startupPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
291
+ const info = fs.fstatSync(fd);
292
+ if (!info.isFile() || info.size > 4096 || (process.platform !== 'win32' && (info.mode & 0o077))) {
293
+ fail('AGENT_RUNTIME_START_FAILED'); return;
294
+ }
295
+ const raw = fs.readFileSync(fd, 'utf8');
296
+ fs.closeSync(fd); fd = undefined;
297
+ const receipt = JSON.parse(raw);
298
+ if (receipt.protocolVersion !== 1 || receipt.startupId !== daemonConfig.startupId || receipt.ready !== true) {
299
+ fail('AGENT_RUNTIME_START_FAILED'); return;
300
+ }
301
+ settled = true;
302
+ clearInterval(pollTimer);
303
+ clearTimeout(startupTimer);
304
+ removeReceipt();
305
+ if (typeof child.unref === 'function') {child.unref();}
306
+ diagnostic('info', 'runtime_backgrounded', { command: daemonConfig.command, component: 'node' });
307
+ resolve({ pid: child.pid, logPath });
308
+ } catch (error) {
309
+ if (error.code !== 'ENOENT') {fail('AGENT_RUNTIME_START_FAILED');}
310
+ } finally { if (fd !== undefined) {fs.closeSync(fd);} }
311
+ };
312
+ const pollTimer = setInterval(checkReady, 50);
313
+ const startupTimer = setTimeout(() => fail('AGENT_RUNTIME_START_TIMEOUT'), options.startupTimeoutMs ?? 60000);
314
+ if (child.stdin) {
315
+ child.stdin.on('error', () => fail('AGENT_RUNTIME_START_FAILED'));
316
+ child.stdin.end(`${payload}\n`);
317
+ } else {fail('AGENT_RUNTIME_START_FAILED');}
318
+ });
319
+ }
320
+
321
+ module.exports = { MAX_CONFIG_BYTES, BACKGROUND_LOG_NAME, backgroundLogPath, runtimeEnvironment, readStdinJson, launchRuntime, launchBackgroundRuntime };
@@ -9,8 +9,9 @@ const { auditAssetExecution } = require('../asset/asset-execution');
9
9
  const { fetchFormPageList } = require('./form-navigation');
10
10
 
11
11
  const CHECKABLE_RESOURCE_KINDS = new Set(['display-page', 'normal-form', 'process-form']);
12
+ const APP_TYPE_OPTIONS = Object.freeze(['--app-type', '--appType', '--app_type']);
12
13
 
13
- function parseArgs(args = []) {
14
+ function parseArgs(args = [], options = {}) {
14
15
  const parsed = {
15
16
  prdPath: '',
16
17
  appType: '',
@@ -19,20 +20,29 @@ function parseArgs(args = []) {
19
20
  help: false,
20
21
  };
21
22
 
23
+ const seen = new Set();
22
24
  for (let index = 0; index < args.length; index++) {
23
25
  const arg = args[index];
26
+ const key = APP_TYPE_OPTIONS.includes(arg) ? 'appType'
27
+ : ['--build-manifest', '--manifest'].includes(arg) ? 'buildManifestPath' : arg;
28
+ if (options.strict && arg.startsWith('-') && seen.has(key)) {
29
+ throwUsage(t('check_prd_completeness.usage'), t('check_prd_completeness.example'));
30
+ }
31
+ if (options.strict && arg.startsWith('-')) {seen.add(key);}
24
32
  if (arg === '--help' || arg === '-h') {
25
33
  parsed.help = true;
26
34
  } else if (arg === '--json') {
27
35
  parsed.json = true;
28
- } else if ((arg === '--app-type' || arg === '--appType' || arg === '--app_type') && args[index + 1]) {
36
+ } else if (APP_TYPE_OPTIONS.includes(arg) && args[index + 1] && (!options.strict || !args[index + 1].startsWith('-'))) {
29
37
  parsed.appType = args[index + 1];
30
38
  index++;
31
- } else if ((arg === '--build-manifest' || arg === '--manifest') && args[index + 1]) {
39
+ } else if ((arg === '--build-manifest' || arg === '--manifest') && args[index + 1] && (!options.strict || !args[index + 1].startsWith('-'))) {
32
40
  parsed.buildManifestPath = args[index + 1];
33
41
  index++;
34
- } else if (!arg.startsWith('--') && !parsed.prdPath) {
42
+ } else if (!arg.startsWith(options.strict ? '-' : '--') && !parsed.prdPath) {
35
43
  parsed.prdPath = arg;
44
+ } else if (options.strict) {
45
+ throwUsage(t('check_prd_completeness.usage'), t('check_prd_completeness.example'));
36
46
  }
37
47
  }
38
48
 
@@ -627,6 +637,7 @@ async function run(args = []) {
627
637
  }
628
638
 
629
639
  module.exports = {
640
+ APP_TYPE_OPTIONS,
630
641
  evaluatePrdCompleteness,
631
642
  extractResources,
632
643
  loadBuildManifest,