@synopackageland/cli 0.49.0 → 0.50.0

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 (77) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +10 -0
  3. package/dist/ctl/ai-tools.d.ts +9 -1
  4. package/dist/ctl/ai-tools.js +4 -4
  5. package/dist/ctl/cli.d.ts +8 -1
  6. package/dist/ctl/cli.js +40 -5
  7. package/dist/ctl/descriptor.d.ts +15 -2
  8. package/dist/ctl/descriptor.js +9 -4
  9. package/dist/ctl/flows.js +2 -0
  10. package/dist/ctl/input.d.ts +5 -3
  11. package/dist/ctl/input.js +3 -3
  12. package/dist/ctl/native-auth-command.d.ts +9 -0
  13. package/dist/ctl/native-auth-command.js +98 -0
  14. package/dist/ctl/native-executor.d.ts +16 -0
  15. package/dist/ctl/native-executor.js +187 -0
  16. package/dist/ctl/native-file-types.d.ts +16 -0
  17. package/dist/ctl/native-file-types.js +57 -0
  18. package/dist/ctl/native-files.d.ts +13 -0
  19. package/dist/ctl/native-files.js +115 -0
  20. package/dist/ctl/native-metadata.d.ts +10 -0
  21. package/dist/ctl/native-metadata.js +50 -0
  22. package/dist/ctl/native-paths.d.ts +4 -0
  23. package/dist/ctl/native-paths.js +54 -0
  24. package/dist/ctl/native-protocol.d.ts +21 -0
  25. package/dist/ctl/native-protocol.js +150 -0
  26. package/dist/ctl/native-registry.d.ts +8 -0
  27. package/dist/ctl/native-registry.js +182 -0
  28. package/dist/ctl/native-schemas.d.ts +7 -0
  29. package/dist/ctl/native-schemas.js +25 -0
  30. package/dist/ctl/native-store.d.ts +61 -0
  31. package/dist/ctl/native-store.js +348 -0
  32. package/dist/ctl/native-transfers.d.ts +13 -0
  33. package/dist/ctl/native-transfers.js +331 -0
  34. package/dist/ctl/native-transport.d.ts +30 -0
  35. package/dist/ctl/native-transport.js +148 -0
  36. package/dist/ctl/native-types.d.ts +15 -0
  37. package/dist/ctl/native-types.js +1 -0
  38. package/dist/ctl/registry.d.ts +5 -4
  39. package/dist/ctl/registry.js +12 -1
  40. package/dist/ctl/service.d.ts +32 -1
  41. package/dist/ctl/service.js +122 -1
  42. package/dist/error-registry.js +15 -0
  43. package/dist/generated/native-http.d.ts +189 -0
  44. package/dist/generated/native-http.js +1 -0
  45. package/dist/nas/store.d.ts +3 -1
  46. package/dist/nas/store.js +6 -3
  47. package/dist/nas/transport.d.ts +1 -0
  48. package/dist/native-http-schema/descriptor.schema.json +242 -0
  49. package/dist/native-http-schema/inventory.schema.json +121 -0
  50. package/dist/native-http-schema/registry.schema.json +872 -0
  51. package/dist/native-http-schema/source.json +1 -0
  52. package/dist/runtime/sdk-source.d.ts +1 -1
  53. package/dist/runtime/sdk-source.js +1 -1
  54. package/dist/standalone/api-description.d.ts +2 -5
  55. package/dist/standalone/build.js +5 -1
  56. package/dist/standalone/compose-errors.js +5 -0
  57. package/dist/standalone/inspect-spk.js +2 -17
  58. package/dist/standalone/lifecycle.js +9 -2
  59. package/dist/standalone/manifest.d.ts +1 -0
  60. package/dist/standalone/manifest.js +22 -5
  61. package/dist/standalone/mobile.js +4 -4
  62. package/dist/standalone/native-http-inspect.d.ts +9 -0
  63. package/dist/standalone/native-http-inspect.js +43 -0
  64. package/dist/standalone/native-http.d.ts +31 -0
  65. package/dist/standalone/native-http.js +120 -0
  66. package/dist/standalone/operation-registry.d.ts +2 -7
  67. package/dist/standalone/operation-registry.js +3 -0
  68. package/dist/standalone/spk.d.ts +1 -0
  69. package/dist/standalone/spk.js +15 -1
  70. package/package.json +3 -3
  71. package/schema/dsm-api-contract.json +8 -7
  72. package/skills/SKILL.md +2 -2
  73. package/skills/reference/compose.md +21 -0
  74. package/skills/reference/ctl.md +198 -0
  75. package/skills/reference/daemon-mode.md +1 -1
  76. package/skills/reference/mobile.md +7 -3
  77. package/skills/reference/upstream-fork.md +5 -2
@@ -0,0 +1,331 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { Readable } from 'node:stream';
3
+ import { ajv } from './descriptor.js';
4
+ import { CtlError } from './errors.js';
5
+ import { nativeRequest, boundValue } from './native-executor.js';
6
+ import { decodeNative, mismatch, nativeActionToken, nativeMime } from './native-protocol.js';
7
+ import { nativeNetwork, nativeStatus } from './native-transport.js';
8
+ import { openUpload, openDownload, localFailure } from './native-files.js';
9
+ import { documentMime, fileError, transferLimit, OpmlGuard, OPML_MAX_BYTES, FILE_CHUNK_BYTES } from './native-file-types.js';
10
+ let active = false;
11
+ const xmlTypes = ['application/xml', 'text/xml', 'text/x-opml'];
12
+ function result(op, value) { if (op.resultSchema && !ajv.validate(op.resultSchema, value))
13
+ throw mismatch(); }
14
+ function length(response, max) {
15
+ const raw = response.headers['content-length'];
16
+ if (raw === undefined)
17
+ return undefined;
18
+ if (typeof raw !== 'string' || !/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)))
19
+ throw fileError('FILE_TRUNCATED', 'Invalid native content length.');
20
+ const n = Number(raw);
21
+ if (n > max)
22
+ throw fileError('FILE_BOUND', 'Native file exceeds its byte bound.');
23
+ return n;
24
+ }
25
+ function responseHeaders(response) {
26
+ let bytes = 0;
27
+ for (const [name, value] of Object.entries(response.headers)) {
28
+ bytes += Buffer.byteLength(name) + Buffer.byteLength(Array.isArray(value) ? value.join('\r\n') : String(value ?? ''));
29
+ if (bytes > 65536)
30
+ throw fileError('FILE_BOUND', 'Native response headers exceed their byte bound.');
31
+ }
32
+ }
33
+ function watch(signal, body) {
34
+ const abort = () => body.destroy(new CtlError('CTL_NATIVE_FILE_CANCELLED', 'Local transfer cancelled.', 'Check App state; upstream work was not cancelled.', 130));
35
+ body.on('error', () => { });
36
+ if (signal.aborted)
37
+ abort();
38
+ else
39
+ signal.addEventListener('abort', abort, { once: true });
40
+ return () => signal.removeEventListener('abort', abort);
41
+ }
42
+ function rejectHtml(prefix) {
43
+ const text = prefix.toString('utf8').trimStart();
44
+ if (/^(?:<!doctype\s+html|<html\b|<head\b|<body\b|[\[{])/i.test(text))
45
+ throw fileError('FILE_TYPE', 'Expected a file, received HTML or JSON.');
46
+ }
47
+ function uploadFields(op, params, action, boundary) {
48
+ const entries = Object.entries(op.http.body?.fields ?? {});
49
+ if (entries.length > 16)
50
+ throw fileError('FILE_BOUND', 'Too many multipart fields.');
51
+ const fields = [];
52
+ let total = 0;
53
+ for (const [name, binding] of entries) {
54
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
55
+ throw mismatch();
56
+ const value = boundValue(binding, params, action);
57
+ if (value === undefined)
58
+ continue;
59
+ for (const item of Array.isArray(value) ? value : [value]) {
60
+ const text = String(item);
61
+ if (Buffer.byteLength(text) > 65536 - total || fields.length >= 16)
62
+ throw fileError('FILE_BOUND', 'Multipart fields exceed their bound.');
63
+ const field = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${text}\r\n`);
64
+ total += field.length;
65
+ if (total > 65536 || fields.length >= 16)
66
+ throw fileError('FILE_BOUND', 'Multipart fields exceed their bound.');
67
+ fields.push(field);
68
+ }
69
+ }
70
+ return fields;
71
+ }
72
+ /** Install only on the human ctl entry. Uses the authenticated transport supplied by B. */
73
+ export function createNativeTransfer(options = {}) {
74
+ return async (op, params, context) => {
75
+ const flow = op.flow;
76
+ if (!op.http || !['upload-http', 'download-file'].includes(flow.type) || op.ai !== 'human-only')
77
+ throw fileError('FILE_HUMAN_ONLY', 'Native file transfers require a human-only operation.');
78
+ if (active)
79
+ throw fileError('FILE_BUSY', 'Only one native file transfer may run in this process.');
80
+ active = true;
81
+ const controller = new AbortController();
82
+ const cancel = () => controller.abort();
83
+ const signal = context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal;
84
+ const transport = request => context.transport({ ...request, signal, timeoutMs: options.timeoutMs });
85
+ if (options.handleSignals)
86
+ process.once('SIGINT', cancel);
87
+ let dispatched = false;
88
+ const check = () => { if (signal.aborted)
89
+ throw new CtlError('CTL_NATIVE_FILE_CANCELLED', 'Local transfer cancelled; no upstream task was cancelled.', 'Check App state before retrying.', 130); };
90
+ let lastProgress = 0;
91
+ const progress = (direction, bytes, total) => {
92
+ if (performance.now() - lastProgress >= 250) {
93
+ lastProgress = performance.now();
94
+ options.progress?.({ direction, bytes, total });
95
+ }
96
+ };
97
+ try {
98
+ check();
99
+ // Defence in depth: remove local-only parameters before any binding expansion.
100
+ const remote = { ...params };
101
+ if (flow.type === 'upload-http')
102
+ delete remote[flow.fileParam];
103
+ if (flow.type === 'download-file')
104
+ delete remote[flow.outputParam];
105
+ if (flow.type === 'upload-http') {
106
+ let source;
107
+ try {
108
+ source = await openUpload(params[flow.fileParam]);
109
+ }
110
+ catch (error) {
111
+ throw localFailure(error);
112
+ }
113
+ let body, response;
114
+ let sourceError;
115
+ const unwatch = [];
116
+ try {
117
+ const max = transferLimit(context.http.limits.maxTransferBytes, flow.maxBytes, ...(flow.encoding === 'raw' ? [OPML_MAX_BYTES] : []));
118
+ if (source.size > max)
119
+ throw fileError('FILE_BOUND', 'Upload file exceeds its byte bound.');
120
+ const prefix = Buffer.alloc(512);
121
+ const peek = await source.handle.read(prefix, 0, prefix.length, 0);
122
+ let mime;
123
+ if (flow.encoding === 'raw') {
124
+ mime = xmlTypes.find(type => flow.contentTypes.includes(type));
125
+ if (!mime)
126
+ throw fileError('FILE_TYPE', 'Raw uploads require declared OPML XML.');
127
+ const guard = new OpmlGuard();
128
+ const buffer = Buffer.alloc(FILE_CHUNK_BYTES);
129
+ for (let offset = 0; offset < source.size;) {
130
+ check();
131
+ const { bytesRead } = await source.handle.read(buffer, 0, Math.min(buffer.length, source.size - offset), offset);
132
+ if (!bytesRead)
133
+ throw fileError('FILE_CHANGED', 'Upload source was truncated.');
134
+ guard.push(buffer.subarray(0, bytesRead));
135
+ offset += bytesRead;
136
+ }
137
+ guard.push(Buffer.alloc(0), true);
138
+ await source.unchanged();
139
+ }
140
+ else
141
+ mime = documentMime(prefix.subarray(0, peek.bytesRead));
142
+ if (!mime || !flow.contentTypes.includes(mime))
143
+ throw fileError('FILE_TYPE', 'Upload signature does not match a declared MIME type.');
144
+ const needsAction = Object.values(op.http.body?.fields ?? {}).some(binding => 'actionToken' in binding);
145
+ const action = needsAction ? await nativeActionToken(context.http, transport) : undefined;
146
+ const request = nativeRequest({ ...op.http, body: undefined }, remote, action);
147
+ // Override negotiated upload headers case-insensitively.
148
+ const headers = Object.fromEntries(Object.entries(request.headers ?? {}).filter(([name]) => !['content-type', 'content-length'].includes(name.toLowerCase())));
149
+ const boundary = 'ctl-' + randomBytes(24).toString('hex');
150
+ const parts = flow.encoding === 'multipart' ? uploadFields(op, remote, action, boundary) : [];
151
+ if (flow.encoding === 'multipart') {
152
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(flow.part))
153
+ throw mismatch();
154
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${flow.part}"; filename="${source.name}"\r\nContent-Type: ${mime}\r\n\r\n`));
155
+ }
156
+ const ending = flow.encoding === 'multipart' ? Buffer.from(`\r\n--${boundary}--\r\n`) : Buffer.alloc(0);
157
+ const overhead = parts.reduce((n, part) => n + part.length, ending.length);
158
+ if (overhead > 131072)
159
+ throw fileError('FILE_BOUND', 'Multipart overhead exceeds its byte bound.');
160
+ headers['content-type'] = flow.encoding === 'multipart' ? `multipart/form-data; boundary=${boundary}` : mime;
161
+ headers['content-length'] = String(source.size + overhead);
162
+ let sent = 0, complete = false;
163
+ body = Readable.from((async function* () {
164
+ try {
165
+ for (const part of parts) {
166
+ check();
167
+ yield part;
168
+ }
169
+ while (sent < source.size) {
170
+ check();
171
+ const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, source.size - sent));
172
+ const { bytesRead } = await source.handle.read(buffer, 0, buffer.length, sent);
173
+ if (!bytesRead)
174
+ throw fileError('FILE_CHANGED', 'Upload source was truncated; outcome_unknown.');
175
+ sent += bytesRead;
176
+ if (sent > max)
177
+ throw fileError('FILE_BOUND', 'Upload exceeds its byte bound; outcome_unknown.');
178
+ yield buffer.subarray(0, bytesRead);
179
+ progress('upload', sent, source.size);
180
+ }
181
+ await source.unchanged();
182
+ check();
183
+ if (ending.length)
184
+ yield ending;
185
+ complete = true;
186
+ }
187
+ catch (error) {
188
+ sourceError = error;
189
+ throw error;
190
+ }
191
+ })(), { objectMode: false, highWaterMark: FILE_CHUNK_BYTES });
192
+ unwatch.push(watch(signal, body));
193
+ check();
194
+ dispatched = true;
195
+ response = await transport({ ...request, headers, body, effect: op.effect });
196
+ unwatch.push(watch(signal, response.body));
197
+ responseHeaders(response);
198
+ nativeStatus(response.status);
199
+ const expected = length(response, Math.min(context.http.limits.maxResponseBytes, op.http.response.maxBytes, 65536));
200
+ const decoded = await decodeNative(response, { ...op.http.response, contentTypes: op.http.response.contentTypes.filter(type => type !== 'text/html') }, Math.min(context.http.limits.maxResponseBytes, 65536), true);
201
+ if (op.http.response.decode === 'text' && decoded.bytes)
202
+ rejectHtml(Buffer.from(decoded.raw));
203
+ if (expected !== undefined && decoded.bytes !== expected)
204
+ throw fileError('FILE_TRUNCATED', 'Native receipt was truncated; outcome_unknown.');
205
+ // An early HTTP receipt must not hide an interrupted or unconsumed upload.
206
+ if (sourceError)
207
+ throw sourceError;
208
+ if (!complete || sent !== source.size)
209
+ throw fileError('FILE_INCOMPLETE', 'Upload body was not completed; outcome_unknown.');
210
+ await source.unchanged();
211
+ check();
212
+ result(op, decoded.value);
213
+ return decoded.value; // Preserve the native receipt/task ID, without fabricating OCR completion.
214
+ }
215
+ catch (error) {
216
+ if (sourceError)
217
+ throw localFailure(sourceError);
218
+ if (error?.code?.startsWith('CTL_'))
219
+ throw error;
220
+ throw nativeNetwork(error, dispatched);
221
+ }
222
+ finally {
223
+ unwatch.forEach(stop => stop());
224
+ response?.body.destroy();
225
+ body?.destroy();
226
+ await source.handle.close().catch(error => { throw localFailure(error); });
227
+ }
228
+ }
229
+ if (flow.type === 'download-file') {
230
+ const max = transferLimit(context.http.limits.maxTransferBytes, flow.maxBytes, op.http.response.maxBytes);
231
+ let file;
232
+ try {
233
+ file = await openDownload(params[flow.outputParam]);
234
+ }
235
+ catch (error) {
236
+ throw localFailure(error);
237
+ }
238
+ let response, unwatch;
239
+ try {
240
+ response = await transport({ ...nativeRequest(op.http, remote), effect: op.effect });
241
+ unwatch = watch(signal, response.body);
242
+ responseHeaders(response);
243
+ nativeStatus(response.status);
244
+ if (!op.http.response.statuses.includes(response.status))
245
+ throw mismatch();
246
+ nativeMime(response, op.http.response.contentTypes.filter(type => flow.contentTypes.includes(type) && type !== 'text/html' && type !== 'application/json'));
247
+ const expected = length(response, max), mime = String(response.headers['content-type']).split(';')[0].trim().toLowerCase();
248
+ const xml = xmlTypes.includes(mime) ? new OpmlGuard() : undefined;
249
+ const hash = createHash('sha256');
250
+ let bytes = 0, prefix = Buffer.alloc(0), checked = false;
251
+ const inspect = () => {
252
+ rejectHtml(prefix);
253
+ if (['application/pdf', 'image/png', 'image/jpeg'].includes(mime) && documentMime(prefix) !== mime)
254
+ throw fileError('FILE_TYPE', 'Download signature does not match its MIME type.');
255
+ checked = true;
256
+ };
257
+ try {
258
+ for await (const data of response.body) {
259
+ check();
260
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
261
+ bytes += chunk.length;
262
+ if (bytes > max)
263
+ throw fileError('FILE_BOUND', 'Download exceeds its byte bound.');
264
+ if (!checked) {
265
+ prefix = Buffer.concat([prefix, chunk.subarray(0, 512 - prefix.length)]);
266
+ if (prefix.length === 512)
267
+ inspect();
268
+ }
269
+ xml?.push(chunk);
270
+ hash.update(chunk);
271
+ // FileHandle writes can be short; await every write for backpressure.
272
+ for (let offset = 0; offset < chunk.length;) {
273
+ check();
274
+ let written;
275
+ try {
276
+ written = (await file.handle.write(chunk, offset, chunk.length - offset)).bytesWritten;
277
+ }
278
+ catch (error) {
279
+ throw localFailure(error);
280
+ }
281
+ if (!written)
282
+ throw fileError('FILE_DISK_FULL', 'Local write made no progress.');
283
+ offset += written;
284
+ }
285
+ progress('download', bytes, expected);
286
+ }
287
+ }
288
+ catch (error) {
289
+ if (error instanceof CtlError)
290
+ throw error;
291
+ throw nativeNetwork(error, false);
292
+ }
293
+ if (!checked)
294
+ inspect();
295
+ xml?.push(Buffer.alloc(0), true);
296
+ if (expected !== undefined && bytes !== expected)
297
+ throw fileError('FILE_TRUNCATED', 'Download ended before the declared content length.');
298
+ check();
299
+ const receipt = { bytes, sha256: hash.digest('hex') };
300
+ result(op, receipt);
301
+ try {
302
+ await file.publish(check);
303
+ check();
304
+ }
305
+ catch (error) {
306
+ throw localFailure(error);
307
+ }
308
+ return receipt;
309
+ }
310
+ finally {
311
+ unwatch?.();
312
+ response?.body.destroy();
313
+ await file.close().catch(error => { throw localFailure(error); });
314
+ }
315
+ }
316
+ throw mismatch();
317
+ }
318
+ catch (error) {
319
+ if (signal.aborted && dispatched && op.effect !== 'read')
320
+ throw nativeNetwork(error, true);
321
+ if (signal.aborted)
322
+ check();
323
+ throw error;
324
+ }
325
+ finally {
326
+ if (options.handleSignals)
327
+ process.removeListener('SIGINT', cancel);
328
+ active = false;
329
+ }
330
+ };
331
+ }
@@ -0,0 +1,30 @@
1
+ import type { Readable } from 'node:stream';
2
+ import { type NasHttpResponseHeaders } from '../nas/transport.js';
3
+ import { type HostTls } from '../nas/tls.js';
4
+ import { CtlError } from './errors.js';
5
+ export interface NativeRequest {
6
+ /** Already encoded, App-relative path; never a URL. */
7
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
8
+ path: string;
9
+ query?: URLSearchParams;
10
+ effect?: 'read' | 'write' | 'destructive';
11
+ headers?: Record<string, string>;
12
+ body?: Uint8Array | Readable;
13
+ signal?: AbortSignal;
14
+ /** Header/connection/idle budget. Productive streams have no total timer. */
15
+ timeoutMs?: number;
16
+ }
17
+ export interface NativeResponse {
18
+ status: number;
19
+ headers: NasHttpResponseHeaders;
20
+ body: Readable;
21
+ }
22
+ /** Tokens are held by the implementation closure, never exposed to transfer modules. */
23
+ export type NativeTransport = (request: NativeRequest) => Promise<NativeResponse>;
24
+ export declare function nativePath(path: string, encoded?: boolean): void;
25
+ export declare function nativeWithin(path: string, prefixes: readonly string[]): boolean;
26
+ export declare function nativeStatus(status: number): void;
27
+ export declare function nativeNetwork(error: unknown, mutation: boolean): CtlError;
28
+ /** A cookie-free branch of the shared NAS connection. Every request gets a fresh socket. */
29
+ export declare function createNativeTransport(origin: string, basePath: string, upstreamAuthPaths: readonly string[], trust?: HostTls, authorization?: () => string, templates?: readonly string[]): NativeTransport;
30
+ export declare function nativeBytes(response: NativeResponse, maxBytes: number, mutation?: boolean): Promise<Buffer>;
@@ -0,0 +1,148 @@
1
+ import { nasHttpRequest, canonicalOrigin } from '../nas/transport.js';
2
+ import { networkError } from '../nas/tls.js';
3
+ import { CtlError } from './errors.js';
4
+ const negotiation = new Set(['accept', 'content-type', 'content-length', 'accept-encoding']);
5
+ export function nativePath(path, encoded = false) {
6
+ const fail = () => { throw new CtlError('CTL_NATIVE_PATH_INVALID', 'Unsafe native API path.', 'Refresh the App metadata.', 5); };
7
+ if (!path.startsWith('/') || path.includes('//') || /[?#\\\x00-\x20\x7f]/.test(path) || path.length > 4096)
8
+ return fail();
9
+ for (const segment of path.split('/')) {
10
+ let decoded;
11
+ try {
12
+ decoded = decodeURIComponent(segment);
13
+ }
14
+ catch {
15
+ return fail();
16
+ }
17
+ if (!encoded && segment.includes('%') || /[\/\\%\x00-\x20\x7f]/.test(decoded) || decoded === '.' || decoded === '..')
18
+ return fail();
19
+ }
20
+ if (/^\/(?:_sso|_spl|webapi|webman)(?:\/|$)/.test(path))
21
+ return fail();
22
+ }
23
+ export function nativeWithin(path, prefixes) {
24
+ return prefixes.some(raw => { const prefix = raw.replace(/\/$/, ''); return path === prefix || path.startsWith(prefix + '/'); });
25
+ }
26
+ export function nativeStatus(status) {
27
+ if (status >= 300 && status < 400)
28
+ throw new CtlError('CTL_NATIVE_REDIRECT', 'Native redirects are refused.', 'Check App ingress and API configuration.', 5);
29
+ if (status === 401)
30
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'The App rejected the native credential.', 'Run ctl auth --app <package> in your own terminal.', 2);
31
+ if (status === 403)
32
+ throw new CtlError('CTL_NATIVE_ACCESS_DENIED', 'Native role or resource access was denied.', 'Check the native App role and resource permissions.', 4);
33
+ if (status === 503)
34
+ throw new CtlError('CTL_NATIVE_UNAVAILABLE', 'Native API is unavailable or disabled.', 'Check the App configuration and enable its native API.', 5);
35
+ if (status < 200 || status >= 300)
36
+ throw new CtlError('CTL_NATIVE_HTTP_ERROR', `Native API returned HTTP ${status}.`, 'Check App state; the request was not replayed.', 5);
37
+ }
38
+ export function nativeNetwork(error, mutation) {
39
+ const safe = networkError(error);
40
+ if (safe.code === 'HOST_TLS_UNTRUSTED' || safe.code === 'HOST_CERT_CHANGED')
41
+ return safe;
42
+ return mutation ? new CtlError('CTL_NATIVE_OUTCOME_UNKNOWN', 'Native request interrupted; outcome_unknown.', 'Check the original resource or task in the App before retrying.', 6) : safe;
43
+ }
44
+ /** A cookie-free branch of the shared NAS connection. Every request gets a fresh socket. */
45
+ export function createNativeTransport(origin, basePath, upstreamAuthPaths, trust = {}, authorization, templates) {
46
+ canonicalOrigin(origin, new URL(origin).protocol === 'http:');
47
+ nativePath(basePath);
48
+ if (!basePath.endsWith('/') || basePath === '/')
49
+ throw new CtlError('CTL_NATIVE_PATH_INVALID', 'A package ingress prefix is required.', 'Refresh the App metadata.', 5);
50
+ for (const prefix of upstreamAuthPaths)
51
+ nativePath(prefix);
52
+ return async (input) => {
53
+ nativePath(input.path, true);
54
+ if (templates && !templates.some(template => { const a = template.split('/'), b = input.path.split('/'); return a.length === b.length && a.every((part, i) => /^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(part) ? !!b[i] : part === b[i]); }))
55
+ throw new CtlError('CTL_NATIVE_PATH_INVALID', 'Request has no declared native binding.', 'Refresh the App metadata.', 5);
56
+ if (!nativeWithin(input.path, upstreamAuthPaths))
57
+ throw new CtlError('CTL_NATIVE_PATH_INVALID', 'Request is outside declared upstream auth paths.', 'Refresh the App metadata.', 5);
58
+ const url = new URL(origin);
59
+ url.pathname = basePath.slice(0, -1) + input.path;
60
+ url.search = input.query?.toString() ?? '';
61
+ if (url.origin !== origin || !url.pathname.startsWith(basePath))
62
+ throw new CtlError('CTL_ORIGIN_MISMATCH', 'Native request left the package origin.', 'Refresh the App metadata.', 4);
63
+ const headers = { 'accept-encoding': 'identity' };
64
+ for (const [name, value] of Object.entries(input.headers ?? {})) {
65
+ if (!negotiation.has(name.toLowerCase()) || /[\r\n\0]/.test(value))
66
+ throw new CtlError('CTL_NATIVE_HEADER_INVALID', 'Reserved or invalid native header.', 'Use declared negotiation headers only.', 5);
67
+ headers[name.toLowerCase()] = value;
68
+ }
69
+ if (headers['accept-encoding'] !== 'identity')
70
+ throw new CtlError('CTL_NATIVE_HEADER_INVALID', 'Native responses require identity encoding.', 'Use identity encoding.', 5);
71
+ if (authorization) {
72
+ const value = authorization();
73
+ if (/[\r\n\0]/.test(value))
74
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Invalid stored credential.', 'Run ctl auth --app <package>.', 2);
75
+ headers.authorization = value;
76
+ }
77
+ const mutation = input.effect ? input.effect !== 'read' : input.method !== 'GET';
78
+ return new Promise((resolve, reject) => {
79
+ let received = false;
80
+ const req = nasHttpRequest(url, { method: input.method, headers, signal: input.signal }, input.timeoutMs ?? 60000, trust, res => {
81
+ received = true;
82
+ clearTimeout(connectTimer);
83
+ clearTimeout(headerTimer);
84
+ try {
85
+ nativeStatus(res.statusCode ?? 0);
86
+ }
87
+ catch (error) {
88
+ res.destroy();
89
+ reject(error);
90
+ return;
91
+ }
92
+ // IncomingMessage preserves backpressure and never saves Set-Cookie.
93
+ resolve({ status: res.statusCode, headers: res.headers, body: res });
94
+ });
95
+ let headerTimer;
96
+ const connectTimer = setTimeout(() => req.destroy(new Error('Native connection timed out')), input.timeoutMs ?? 60000);
97
+ req.once('socket', socket => { const connected = () => clearTimeout(connectTimer); if (socket.connecting)
98
+ socket.once(url.protocol === 'https:' ? 'secureConnect' : 'connect', connected);
99
+ else
100
+ connected(); });
101
+ // Upload progress is governed by socket idle timeout. Start the response-header
102
+ // budget only after the request body has finished, never as an upload total timer.
103
+ req.once('finish', () => { clearTimeout(connectTimer); if (!received)
104
+ headerTimer = setTimeout(() => req.destroy(new Error('Native response headers timed out')), input.timeoutMs ?? 60000); });
105
+ req.once('close', () => { clearTimeout(connectTimer); clearTimeout(headerTimer); });
106
+ req.on('timeout', () => req.destroy(new Error('Native idle timeout')));
107
+ req.on('error', error => { if (!received)
108
+ reject(nativeNetwork(error, mutation)); });
109
+ if (input.body && 'pipe' in input.body) {
110
+ const body = input.body;
111
+ body.once('error', () => req.destroy(new Error('Native upload interrupted')));
112
+ req.once('close', () => { if (!body.destroyed)
113
+ body.destroy(); });
114
+ body.pipe(req);
115
+ }
116
+ else
117
+ req.end(input.body);
118
+ });
119
+ };
120
+ }
121
+ export async function nativeBytes(response, maxBytes, mutation = false) {
122
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 16 * 1024 * 1024)
123
+ throw new CtlError('CTL_NATIVE_RESPONSE_INVALID', 'Invalid response byte bound.', 'Use a compatible App declaration.', 5);
124
+ const length = response.headers['content-length'];
125
+ if (length !== undefined && (!/^\d+$/.test(String(length)) || Number(length) > maxBytes)) {
126
+ response.body.destroy();
127
+ throw new CtlError('CTL_NATIVE_RESPONSE_TOO_LARGE', 'Native response exceeds its byte bound.', 'Narrow the request.', 5);
128
+ }
129
+ const chunks = [];
130
+ let total = 0;
131
+ try {
132
+ for await (const data of response.body) {
133
+ const chunk = Buffer.from(data);
134
+ total += chunk.length;
135
+ if (total > maxBytes) {
136
+ response.body.destroy();
137
+ throw new CtlError('CTL_NATIVE_RESPONSE_TOO_LARGE', 'Native response exceeds its byte bound.', 'Narrow the request.', 5);
138
+ }
139
+ chunks.push(chunk);
140
+ }
141
+ }
142
+ catch (error) {
143
+ if (error instanceof CtlError)
144
+ throw error;
145
+ throw nativeNetwork(error, mutation);
146
+ }
147
+ return Buffer.concat(chunks, total);
148
+ }
@@ -0,0 +1,15 @@
1
+ /** SDK-owned pure metadata types, generated from matching SDK sources at build. */
2
+ export type { NativeHttp, NativeAuth, NativeRegistry, NativeDescriptor, NativeInventory, NativeOperation, NativeInventoryBinding, NativeFeature } from '../generated/native-http.js';
3
+ export type { NativeBinding as HttpBinding, NativeResponse as HttpResponse, NativeHttpBinding as HttpOperation, NativePagination as HttpPagination } from '../generated/native-http.js';
4
+ export type NativeFlow = Exclude<import('../generated/native-http.js').NativeFlow, {
5
+ type: 'invoke' | 'ndjson';
6
+ }>;
7
+ /** Client storage record; never part of the SDK metadata. */
8
+ export interface NativeCredential {
9
+ version: 1;
10
+ kind: import('../generated/native-http.js').NativeAuth['type'];
11
+ token: string;
12
+ username?: string;
13
+ verifiedAt: string;
14
+ identity?: Record<string, string>;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -15,7 +15,8 @@ export type RegisteredOperation = Operation & {
15
15
  /** Unbound source of the synopkgland.api v2 build artifact. Keys are real route names. */
16
16
  export interface OperationRegistry {
17
17
  format: 'synopkgland.api';
18
- version: 2;
18
+ version: 2 | 3;
19
+ nativeHttp?: import('./native-types.js').NativeHttp;
19
20
  operations: Record<string, RegisteredOperation>;
20
21
  }
21
22
  export declare const INFRASTRUCTURE_METHODS: Set<string>;
@@ -27,7 +28,7 @@ export declare function checkRouteEquality(registry: OperationRegistry, routes:
27
28
  permission: string;
28
29
  }[]): void;
29
30
  export declare function registryPermissions(registry: OperationRegistry): string;
30
- export declare function registryTools(registry: OperationRegistry): {
31
+ export declare function registryTools(registry: Pick<OperationRegistry, 'operations'>): {
31
32
  execution: string;
32
33
  preview?: string | undefined;
33
34
  name: string;
@@ -39,7 +40,7 @@ export declare function registryTools(registry: OperationRegistry): {
39
40
  destructiveHint: boolean;
40
41
  openWorldHint: boolean;
41
42
  };
42
- ai: "hidden" | "read" | "preview" | "draft" | "human-only";
43
+ ai: "read" | "preview" | "draft" | "human-only" | "hidden";
43
44
  flow: import("./descriptor.js").Flow;
44
45
  }[];
45
46
  export declare function registryReference(registry: OperationRegistry): string;
@@ -52,7 +53,7 @@ export declare function registrySessionRetry(registry: OperationRegistry, routes
52
53
  }[]): {
53
54
  [k: string]: {
54
55
  effect: "read" | "write" | "destructive";
55
- kind: "unknown" | "rpc" | "ai" | "stream";
56
+ kind: "rpc" | "stream" | "unknown" | "ai";
56
57
  };
57
58
  };
58
59
  export declare function registryArtifacts(root: string, registry: OperationRegistry, check: boolean, routes?: readonly {
@@ -2,6 +2,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
2
2
  import { dirname, join, resolve, relative, isAbsolute } from 'node:path';
3
3
  import { strictJson } from './json.js';
4
4
  import { ajv, safeSchema, validateFlow } from './descriptor.js';
5
+ import { validateNativeRegistry } from './native-registry.js';
5
6
  export const AI_CLASSES = ['read', 'preview', 'draft', 'human-only', 'hidden'];
6
7
  export const INFRASTRUCTURE_METHODS = new Set(['synopkgland.describe', 'identity.status', 'identity.login', 'identity.session', 'identity.logout']);
7
8
  const METHOD = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/;
@@ -18,6 +19,10 @@ export function readRegistry(path) {
18
19
  return value;
19
20
  }
20
21
  export function validateRegistry(value) {
22
+ if (value?.version === 3) {
23
+ validateNativeRegistry(value);
24
+ return;
25
+ }
21
26
  const fail = (why) => { throw Error('CTL_REGISTRY_INVALID: ' + why); };
22
27
  if (!value || value.format !== 'synopkgland.api' || value.version !== 2 || !value.operations || Array.isArray(value.operations) || typeof value.operations !== 'object' || Object.keys(value.operations).length > 1024 || Object.keys(value).some(k => !['format', 'version', 'operations'].includes(k)))
23
28
  fail('expected synopkgland.api v2 operations.');
@@ -98,8 +103,14 @@ export function checkRouteEquality(registry, routes) {
98
103
  export function registryPermissions(registry) {
99
104
  return JSON.stringify({ schema: 1, default: 'administrators', methods: Object.fromEntries(Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => [name, op.permission])) }, null, 2) + '\n';
100
105
  }
106
+ function toolResultSchema(op) {
107
+ if (!op.http || !['paginate-http', 'ndjson'].includes(op.flow.type))
108
+ return op.resultSchema;
109
+ const items = op.resultSchema.type === 'array' ? op.resultSchema : { type: 'array', items: op.resultSchema };
110
+ return { type: 'object', required: op.flow.type === 'paginate-http' ? ['items', 'incomplete'] : ['items'], properties: { items, ...(op.flow.type === 'paginate-http' ? { incomplete: { type: 'boolean' }, reason: { type: 'string' }, continuation: { type: 'object' } } : {}) }, additionalProperties: false };
111
+ }
101
112
  export function registryTools(registry) {
102
- return Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).filter(([, op]) => ['read', 'preview', 'draft'].includes(op.ai)).map(([name, op]) => ({ name, description: op.summary, inputSchema: op.paramsSchema, outputSchema: op.resultSchema, annotations: { readOnlyHint: op.effect === 'read', destructiveHint: op.effect === 'destructive', openWorldHint: false }, ai: op.ai, flow: op.flow, ...(op.preview ? { preview: op.preview } : {}), execution: op.ai === 'draft' ? 'preview-and-human-confirmation' : 'flow' }));
113
+ return Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).filter(([, op]) => ['read', 'preview', 'draft'].includes(op.ai)).map(([name, op]) => ({ name, description: op.summary, inputSchema: op.paramsSchema, outputSchema: toolResultSchema(op), annotations: { readOnlyHint: op.effect === 'read', destructiveHint: op.effect === 'destructive', openWorldHint: false }, ai: op.ai, flow: op.flow, ...(op.preview ? { preview: op.preview } : {}), execution: op.ai === 'draft' ? 'preview-and-human-confirmation' : 'flow' }));
103
114
  }
104
115
  export function registryReference(registry) {
105
116
  return '<!-- Generated by synopkgland ctl generate; edit the operation registry. -->\n# App operations\n\n' + Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => `## ${name}\n\n${op.summary.replaceAll('<', '&lt;')}\n\nAI: ${op.ai}; effect: ${op.effect}; permission: ${op.permission}; flow: ${op.flow.type}\n\n${op.ai === 'hidden' ? 'No ctl or AI exposure.' : `ctl: \`${op.cli.join(' ')}\``}\n${op.preview ? `\nPreview: \`${op.preview}\`; obtain human confirmation before execution.\n` : ''}`).join('\n');
@@ -2,6 +2,10 @@ import { CtlError } from './errors.js';
2
2
  import { type DsmSession, type JsonRequest } from './transport.js';
3
3
  import { CtlStore, type Host } from './store.js';
4
4
  import { type Descriptor } from './descriptor.js';
5
+ import { type NativeStoreKind } from './native-store.js';
6
+ import { type NativeTransport } from './native-transport.js';
7
+ import { type EnrollmentInput } from './native-protocol.js';
8
+ import { type NativeTransfer } from './native-executor.js';
5
9
  export declare function boundedMap<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>;
6
10
  export interface DiscoverOptions {
7
11
  refresh?: boolean;
@@ -27,8 +31,35 @@ interface Discovery {
27
31
  export declare class CtlClient {
28
32
  store: CtlStore;
29
33
  host: Host;
34
+ private timeoutMs;
35
+ private nativeOptions;
30
36
  request: JsonRequest;
31
- constructor(store: CtlStore, host: Host, request?: JsonRequest, timeoutMs?: number);
37
+ constructor(store: CtlStore, host: Host, request?: JsonRequest, timeoutMs?: number, nativeOptions?: {
38
+ transportFor?: (app: Descriptor, authorization?: string) => NativeTransport;
39
+ transfer?: NativeTransfer;
40
+ });
41
+ private nativeApproved;
42
+ nativeTransport(app: Descriptor, auth?: string): NativeTransport;
43
+ private nativePaths;
44
+ nativeGuidance(app: Descriptor): {
45
+ scheme: "header" | "greader-client-login";
46
+ credentialUrl: string;
47
+ instructions: string;
48
+ command: string;
49
+ };
50
+ nativeStoreKind(app: Descriptor): Promise<NativeStoreKind | undefined>;
51
+ nativeState(app: Descriptor): Promise<{
52
+ state: import("./native-store.js").NativeStoreState;
53
+ scheme: "header" | "greader-client-login";
54
+ credentialUrl: string;
55
+ instructions: string;
56
+ command: string;
57
+ }>;
58
+ private nativeRequired;
59
+ freshNative(app: Descriptor): Promise<Descriptor>;
60
+ authApp(name: string, options?: DiscoverOptions): Promise<Descriptor>;
61
+ resetNative(app: Descriptor): Promise<void>;
62
+ enroll(app: Descriptor, input: EnrollmentInput, store?: NativeStoreKind, confirm?: (identity: Record<string, string>) => Promise<boolean>): Promise<void>;
32
63
  private until?;
33
64
  private jobRequestBudget?;
34
65
  private remaining;