@nexart/mcp-server 0.0.0-stage → 0.2.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 (100) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/CONTRIBUTING.md +58 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +14 -0
  5. package/README.md +356 -2
  6. package/SECURITY.md +77 -0
  7. package/THIRD_PARTY_NOTICES.md +111 -0
  8. package/dist/adapters.d.ts +16 -0
  9. package/dist/adapters.js +48 -0
  10. package/dist/approve-public.d.ts +2 -0
  11. package/dist/approve-public.js +65 -0
  12. package/dist/contracts.d.ts +48 -0
  13. package/dist/contracts.js +35 -0
  14. package/dist/create-confidential.d.ts +2 -0
  15. package/dist/create-confidential.js +34 -0
  16. package/dist/instrumentation/openai-worker.d.ts +1 -0
  17. package/dist/instrumentation/openai-worker.js +26 -0
  18. package/dist/instrumentation/openai.d.ts +51 -0
  19. package/dist/instrumentation/openai.js +197 -0
  20. package/dist/json-schema.d.ts +9 -0
  21. package/dist/json-schema.js +20 -0
  22. package/dist/limits.d.ts +15 -0
  23. package/dist/limits.js +62 -0
  24. package/dist/lookup/contracts.d.ts +38 -0
  25. package/dist/lookup/contracts.js +23 -0
  26. package/dist/lookup/verify.d.ts +54 -0
  27. package/dist/lookup/verify.js +110 -0
  28. package/dist/network/client.d.ts +26 -0
  29. package/dist/network/client.js +188 -0
  30. package/dist/network/contracts.d.ts +104 -0
  31. package/dist/network/contracts.js +54 -0
  32. package/dist/network-tools.d.ts +5 -0
  33. package/dist/network-tools.js +32 -0
  34. package/dist/owner/create.d.ts +52 -0
  35. package/dist/owner/create.js +117 -0
  36. package/dist/owner/custody.d.ts +36 -0
  37. package/dist/owner/custody.js +210 -0
  38. package/dist/owner/host.d.ts +10 -0
  39. package/dist/owner/host.js +70 -0
  40. package/dist/owner/publisher.d.ts +21 -0
  41. package/dist/owner/publisher.js +27 -0
  42. package/dist/owner/reconcile.d.ts +16 -0
  43. package/dist/owner/reconcile.js +109 -0
  44. package/dist/protocol-safety.d.ts +3 -0
  45. package/dist/protocol-safety.js +16 -0
  46. package/dist/receipts/contracts.d.ts +72 -0
  47. package/dist/receipts/contracts.js +34 -0
  48. package/dist/receipts/verify.d.ts +4 -0
  49. package/dist/receipts/verify.js +104 -0
  50. package/dist/record/contracts.d.ts +323 -0
  51. package/dist/record/contracts.js +75 -0
  52. package/dist/record/customer.d.ts +40 -0
  53. package/dist/record/customer.js +99 -0
  54. package/dist/record/policy.d.ts +46 -0
  55. package/dist/record/policy.js +67 -0
  56. package/dist/record/publication.d.ts +23 -0
  57. package/dist/record/publication.js +148 -0
  58. package/dist/record/record.d.ts +15 -0
  59. package/dist/record/record.js +97 -0
  60. package/dist/record/state.d.ts +44 -0
  61. package/dist/record/state.js +84 -0
  62. package/dist/record-tools.d.ts +13 -0
  63. package/dist/record-tools.js +95 -0
  64. package/dist/recover-confidential.d.ts +2 -0
  65. package/dist/recover-confidential.js +13 -0
  66. package/dist/results.d.ts +8 -0
  67. package/dist/results.js +83 -0
  68. package/dist/server.d.ts +12 -0
  69. package/dist/server.js +39 -0
  70. package/dist/stdio.d.ts +2 -0
  71. package/dist/stdio.js +88 -0
  72. package/dist/trust/lifecycle.d.ts +13 -0
  73. package/dist/trust/lifecycle.js +42 -0
  74. package/dist/trust/policy.d.ts +14 -0
  75. package/dist/trust/policy.js +6 -0
  76. package/dist/verify.d.ts +3 -0
  77. package/dist/verify.js +56 -0
  78. package/dist/write/approval.d.ts +5 -0
  79. package/dist/write/approval.js +95 -0
  80. package/dist/write/attest.d.ts +17 -0
  81. package/dist/write/attest.js +141 -0
  82. package/dist/write/config.d.ts +11 -0
  83. package/dist/write/config.js +12 -0
  84. package/dist/write/contracts.d.ts +229 -0
  85. package/dist/write/contracts.js +61 -0
  86. package/dist/write/post.d.ts +11 -0
  87. package/dist/write/post.js +105 -0
  88. package/dist/write/profile.d.ts +19 -0
  89. package/dist/write/profile.js +114 -0
  90. package/dist/write/seal.d.ts +3 -0
  91. package/dist/write/seal.js +49 -0
  92. package/dist/write-tools.d.ts +4 -0
  93. package/dist/write-tools.js +36 -0
  94. package/docs/consumer-guide.md +133 -0
  95. package/docs/examples/customer-claude-desktop.json +14 -0
  96. package/docs/examples/customer-consent.json +15 -0
  97. package/docs/examples/customer-custody.json +8 -0
  98. package/docs/examples/customer-policy.json +43 -0
  99. package/package.json +58 -4
  100. package/server.json +20 -0
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ import { constants, openSync, fstatSync, readFileSync, closeSync } from 'node:fs';
3
+ import { createInterface } from 'node:readline/promises';
4
+ import { ReadStream, WriteStream } from 'node:tty';
5
+ import { attestInput } from './write/contracts.js';
6
+ import { writeConfig } from './write/config.js';
7
+ import { boundedInput, validV2, publicProfile, PUBLIC_PROFILE, WRITE_LIMITS } from './write/profile.js';
8
+ import { issueApproval } from './write/approval.js';
9
+ import { NODE_ORIGIN } from './network/client.js';
10
+ /** Owner-only command, deliberately not registered as an MCP tool.
11
+ * A trusted local terminal is required; piped/model-generated flags cannot consent.
12
+ */
13
+ async function main() {
14
+ if (process.argv.length !== 3)
15
+ throw Error('USAGE');
16
+ const fd = openSync(process.argv[2], constants.O_RDONLY | constants.O_NOFOLLOW);
17
+ let raw;
18
+ try {
19
+ const stat = fstatSync(fd);
20
+ if (!stat.isFile() || stat.size > WRITE_LIMITS.inputBytes)
21
+ throw Error('INPUT');
22
+ raw = JSON.parse(readFileSync(fd, 'utf8'));
23
+ }
24
+ finally {
25
+ closeSync(fd);
26
+ }
27
+ if (boundedInput(raw))
28
+ throw Error('INPUT');
29
+ const args = attestInput.parse(raw);
30
+ if (args.visibility !== 'public' || !validV2(args.bundle) ||
31
+ args.certificateHash !== args.bundle.certificateHash || !publicProfile(args.bundle))
32
+ throw Error('PROFILE');
33
+ const config = writeConfig(), key = config.apiKey();
34
+ if (!config.publicEnabled || !config.attestEnabled || !config.accountContext?.trim() || !key || /[\r\n]/.test(key))
35
+ throw Error('CONFIG');
36
+ // Open the controlling terminal directly. stdin and stdout are not approval channels.
37
+ const ttyFd = openSync('/dev/tty', constants.O_RDWR | constants.O_NOCTTY);
38
+ const input = new ReadStream(ttyFd);
39
+ const output = new WriteStream(openSync('/dev/tty', constants.O_RDWR | constants.O_NOCTTY));
40
+ if (!input.isTTY || !output.isTTY)
41
+ throw Error('TTY');
42
+ const rl = createInterface({ input, output, terminal: true });
43
+ try {
44
+ output.write(`PUBLIC CERTIFICATION APPROVAL\nDestination: ${NODE_ORIGIN}/api/attest\nProfile: ${PUBLIC_PROFILE}\n`);
45
+ output.write('The complete CER below, its canonical certificate/envelope payloads, input/output hashes, all identity fields, and Node receipt/timestamp metadata can become public and permanently cached.\n');
46
+ output.write('Commitment plaintext and openings are absent. Readable values and original hashes can still disclose or correlate information. Identity verified:true remains a producer assertion, not authentication by this server.\n');
47
+ output.write(JSON.stringify(args.bundle, null, 2) + '\n');
48
+ output.write('Node-generated public metadata includes execution/app/SDK descriptors when present, creation/attestation times, Node ID/runtime hash, attestation ID, public signing key information, signatures, and available timestamp/transparency evidence. See docs/milestone-3.md.\n');
49
+ const answer = await rl.question(`Type PUBLISH ${args.certificateHash} to authorize this exact payload once for five minutes: `);
50
+ if (answer !== `PUBLISH ${args.certificateHash}`)
51
+ throw Error('DECLINED');
52
+ issueApproval(config, JSON.stringify(args.bundle), key);
53
+ output.write('Single-use approval recorded. No evidence was submitted by this command.\n');
54
+ }
55
+ finally {
56
+ rl.close();
57
+ input.destroy();
58
+ output.destroy();
59
+ }
60
+ }
61
+ main().catch(() => {
62
+ process.stderr.write('PUBLIC_APPROVAL_NOT_CREATED: check the input/profile, host configuration, secure approval directory and controlling terminal. No submission was made.\n');
63
+ process.exitCode = 1;
64
+ });
65
+ //# sourceMappingURL=approve-public.js.map
@@ -0,0 +1,48 @@
1
+ import * as z from 'zod/v4';
2
+ export declare const TOOL_NAMES: readonly ["nexart_verify_ai_cer", "nexart_verify_consequential_cer", "nexart_verify_governed_execution", "nexart_verify_project_bundle"];
3
+ export type ToolName = (typeof TOOL_NAMES)[number];
4
+ export declare const inputSchema: z.ZodObject<{
5
+ bundle: z.ZodUnknown;
6
+ }, z.core.$strict>;
7
+ export declare const outputSchema: z.ZodObject<{
8
+ contractVersion: z.ZodLiteral<"1">;
9
+ tool: z.ZodEnum<{
10
+ nexart_verify_ai_cer: "nexart_verify_ai_cer";
11
+ nexart_verify_consequential_cer: "nexart_verify_consequential_cer";
12
+ nexart_verify_governed_execution: "nexart_verify_governed_execution";
13
+ nexart_verify_project_bundle: "nexart_verify_project_bundle";
14
+ }>;
15
+ family: z.ZodNullable<z.ZodEnum<{
16
+ "cer.ai.execution.v1": "cer.ai.execution.v1";
17
+ "cer.ai.execution.v2": "cer.ai.execution.v2";
18
+ "cer.consequential.execution.v1": "cer.consequential.execution.v1";
19
+ "cer.governed.execution.v1": "cer.governed.execution.v1";
20
+ "cer.project.bundle.v1": "cer.project.bundle.v1";
21
+ }>>;
22
+ recordVersion: z.ZodNullable<z.ZodEnum<{
23
+ 0.1: "0.1";
24
+ 0.2: "0.2";
25
+ }>>;
26
+ protocol: z.ZodNullable<z.ZodEnum<{
27
+ "1.2.0": "1.2.0";
28
+ "1.3.0": "1.3.0";
29
+ "1.3.1": "1.3.1";
30
+ "jcs-v1": "jcs-v1";
31
+ }>>;
32
+ artifactIntegrity: z.ZodEnum<{
33
+ valid: "valid";
34
+ invalid: "invalid";
35
+ not_performed: "not_performed";
36
+ }>;
37
+ reasonCode: z.ZodString;
38
+ sdk: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
39
+ checks: z.ZodObject<{
40
+ nodeSignature: z.ZodLiteral<"not_performed">;
41
+ signerTrust: z.ZodLiteral<"not_established">;
42
+ timestampCryptography: z.ZodLiteral<"not_performed">;
43
+ confidentialOpenings: z.ZodLiteral<"not_performed">;
44
+ completeness: z.ZodLiteral<"not_established">;
45
+ }, z.core.$strict>;
46
+ limitations: z.ZodArray<z.ZodString>;
47
+ }, z.core.$strict>;
48
+ export type VerificationOutput = z.infer<typeof outputSchema>;
@@ -0,0 +1,35 @@
1
+ import * as z from 'zod/v4';
2
+ import { anyJsonValue, sdkMetadata } from './json-schema.js';
3
+ export const TOOL_NAMES = [
4
+ 'nexart_verify_ai_cer',
5
+ 'nexart_verify_consequential_cer',
6
+ 'nexart_verify_governed_execution',
7
+ 'nexart_verify_project_bundle',
8
+ ];
9
+ export const inputSchema = z.strictObject({
10
+ bundle: anyJsonValue.describe('An inline NexArt artifact. No URLs, paths, credentials or openings.'),
11
+ });
12
+ const state = z.enum(['valid', 'invalid', 'not_performed']);
13
+ const safeSdkResult = sdkMetadata;
14
+ export const outputSchema = z.strictObject({
15
+ contractVersion: z.literal('1'),
16
+ tool: z.enum(TOOL_NAMES),
17
+ family: z.enum([
18
+ 'cer.ai.execution.v1', 'cer.ai.execution.v2', 'cer.consequential.execution.v1',
19
+ 'cer.governed.execution.v1', 'cer.project.bundle.v1',
20
+ ]).nullable(),
21
+ recordVersion: z.enum(['0.1', '0.2']).nullable(),
22
+ protocol: z.enum(['1.2.0', '1.3.0', '1.3.1', 'jcs-v1']).nullable(),
23
+ artifactIntegrity: state,
24
+ reasonCode: z.string().max(96),
25
+ sdk: safeSdkResult.nullable(),
26
+ checks: z.strictObject({
27
+ nodeSignature: z.literal('not_performed'),
28
+ signerTrust: z.literal('not_established'),
29
+ timestampCryptography: z.literal('not_performed'),
30
+ confidentialOpenings: z.literal('not_performed'),
31
+ completeness: z.literal('not_established'),
32
+ }),
33
+ limitations: z.array(z.string().max(256)).max(12),
34
+ });
35
+ //# sourceMappingURL=contracts.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ import { openSync, constants } from 'node:fs';
3
+ import { ReadStream, WriteStream } from 'node:tty';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { createOwnerConfidential, readOwnerInput, ownerDirectory } from './owner/create.js';
6
+ async function main() {
7
+ if (process.argv.length !== 4)
8
+ throw Error('USAGE');
9
+ const input = process.argv[2], custody = ownerDirectory(process.argv[3]);
10
+ const output = new WriteStream(openSync('/dev/tty', constants.O_RDWR | constants.O_NOCTTY));
11
+ const terminal = new ReadStream(openSync('/dev/tty', constants.O_RDWR | constants.O_NOCTTY));
12
+ const rl = createInterface({ input: terminal, output, terminal: true });
13
+ try {
14
+ if (!terminal.isTTY || !output.isTTY)
15
+ throw Error('OWNER_TTY');
16
+ output.write('OWNER-ONLY CONFIDENTIAL CREATION — no network or MCP.\nUse an isolated owner account/device, inaccessible to agents. A TTY is not isolation.\n');
17
+ output.write(`Custody directory: ${custody}\n`);
18
+ output.write('recovery.json will contain original confidential plaintext AND SDK salt openings, unencrypted with mode 0600 under 0700 directories. Use an owner-encrypted volume and offline backup; never share recovery.json or the input with an agent. Only cer.json may be exported after metadata review. Losing recovery material prevents later opening verification. No automatic deletion or backup is provided.\n');
19
+ if (await rl.question('Type RETAIN OWNER RECOVERY to approve this custody mechanism: ') !== 'RETAIN OWNER RECOVERY')
20
+ throw Error('DECLINED');
21
+ const result = createOwnerConfidential(readOwnerInput(input), custody);
22
+ process.stdout.write(`CONFIDENTIAL_CREATED ${result.certificateHash}\n`);
23
+ }
24
+ finally {
25
+ rl.close();
26
+ terminal.destroy();
27
+ output.destroy();
28
+ }
29
+ }
30
+ main().catch(() => {
31
+ process.stderr.write('CONFIDENTIAL_CREATION_STOPPED: no plaintext or openings logged. Unsaved openings cannot be recovered; no successful export is authorized. Keep any private partial custody files and inspect locally before exporting any CER.\n');
32
+ process.exitCode = 1;
33
+ });
34
+ //# sourceMappingURL=create-confidential.js.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { runOpenAIChatExecutionV2 } from '@nexart/ai-execution/providers/openaiV2';
3
+ // This worker bounds SDK lifetime and confines its fetch shim to this worker.
4
+ // It is NOT an OS/security boundary against an agent controlling the process.
5
+ globalThis.fetch = (async (url, init) => {
6
+ return new Promise((resolve, reject) => {
7
+ parentPort.once('message', message => {
8
+ if (message.type !== 'response')
9
+ return reject(Error('PROVIDER_TRANSPORT_FAILED'));
10
+ resolve(new Response(message.body, { status: message.status, headers: { 'content-type': 'application/json' } }));
11
+ });
12
+ parentPort.postMessage({ type: 'request', url, init });
13
+ });
14
+ });
15
+ try {
16
+ const result = await runOpenAIChatExecutionV2(workerData);
17
+ parentPort.postMessage({ type: 'result', result });
18
+ }
19
+ catch {
20
+ // The published SDK may put raw provider bodies into errors. Never forward.
21
+ parentPort.postMessage({ type: 'failed' });
22
+ }
23
+ finally {
24
+ parentPort.close();
25
+ }
26
+ //# sourceMappingURL=openai-worker.js.map
@@ -0,0 +1,51 @@
1
+ import * as z from 'zod/v4';
2
+ import { type RecordRuntime } from '../record/record.js';
3
+ import { type RecordResult } from '../record/contracts.js';
4
+ import { type EncryptedCustody } from '../owner/custody.js';
5
+ declare const inputSchema: z.ZodObject<{
6
+ params: z.ZodObject<{
7
+ instruction: z.ZodString;
8
+ input: z.ZodString;
9
+ model: z.ZodOptional<z.ZodString>;
10
+ parameters: z.ZodOptional<z.ZodObject<{
11
+ temperature: z.ZodOptional<z.ZodNumber>;
12
+ maxTokens: z.ZodOptional<z.ZodNumber>;
13
+ topP: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
14
+ seed: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
15
+ }, z.core.$strict>>;
16
+ executionRole: z.ZodOptional<z.ZodEnum<{
17
+ advisory: "advisory";
18
+ operative: "operative";
19
+ unspecified: "unspecified";
20
+ }>>;
21
+ decisionRefs: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
22
+ }, z.core.$strict>;
23
+ certification: z.ZodOptional<z.ZodObject<{
24
+ mode: z.ZodDefault<z.ZodEnum<{
25
+ local: "local";
26
+ node: "node";
27
+ }>>;
28
+ visibility: z.ZodOptional<z.ZodEnum<{
29
+ private: "private";
30
+ public: "public";
31
+ }>>;
32
+ }, z.core.$strict>>;
33
+ }, z.core.$strict>;
34
+ export type OpenAIRecordingInput = z.input<typeof inputSchema>;
35
+ export interface OpenAIRecordingRuntime {
36
+ custody: EncryptedCustody;
37
+ apiKey: () => string | undefined;
38
+ /** Trusted application transport injection, never input/env/MCP. Defaults to fixed-origin fetch. */
39
+ request?: typeof fetch;
40
+ /** Only an independently secured existing 4A owner publisher may be supplied. */
41
+ publish?: RecordRuntime['publish'];
42
+ }
43
+ export interface OpenAIRecordingResult {
44
+ providerCall: 'not_started' | 'completed' | 'failed_or_outcome_unknown';
45
+ output: string | null;
46
+ recording: RecordResult;
47
+ }
48
+ /** Real SDK wrapper, called once. No provider key from model arguments and no
49
+ * ambient Node credential discovery. Plaintext output goes only to its calling app. */
50
+ export declare function runOpenAIRecorded(raw: OpenAIRecordingInput, runtime: OpenAIRecordingRuntime): Promise<OpenAIRecordingResult>;
51
+ export {};
@@ -0,0 +1,197 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import * as z from 'zod/v4';
3
+ import { createSnapshotV2, sealCerV2, verifyCerV2 } from '@nexart/ai-execution';
4
+ import {} from '@nexart/ai-execution/providers/openaiV2';
5
+ import { recordExecution } from '../record/record.js';
6
+ import {} from '../record/contracts.js';
7
+ import { boundedInput, disclosureEligible, OPENAI_DISCLOSURE } from '../write/profile.js';
8
+ import { preflightEncryptedCustody, retainEncrypted, EncryptedCustodyError } from '../owner/custody.js';
9
+ import { mcpRecordInput } from '../record/contracts.js';
10
+ const paramsSchema = z.strictObject({
11
+ instruction: z.string(), input: z.string(), model: z.string().min(1).max(128).optional(),
12
+ parameters: z.strictObject({
13
+ temperature: z.number().optional(), maxTokens: z.number().int().positive().optional(),
14
+ topP: z.number().nullable().optional(), seed: z.number().nullable().optional(),
15
+ }).optional(),
16
+ executionRole: z.enum(['advisory', 'operative', 'unspecified']).optional(),
17
+ decisionRefs: z.array(z.unknown()).max(16).optional(),
18
+ });
19
+ const inputSchema = z.strictObject({
20
+ params: paramsSchema,
21
+ certification: mcpRecordInput.options[1].shape.certification,
22
+ });
23
+ const LIMIT = 65_536;
24
+ const TIMEOUT = 10_000;
25
+ async function runOnce(params, request) {
26
+ return new Promise((resolve, reject) => {
27
+ const controller = new AbortController();
28
+ const worker = new Worker(new URL('./openai-worker.js', import.meta.url), {
29
+ workerData: params, execArgv: [], stdout: true, stderr: true,
30
+ resourceLimits: { maxOldGenerationSizeMb: 128 },
31
+ });
32
+ // Deliberately discard any worker diagnostics; never copy raw SDK errors.
33
+ worker.stdout.resume();
34
+ worker.stderr.resume();
35
+ let finished = false, requests = 0;
36
+ const finish = (result) => {
37
+ if (finished)
38
+ return;
39
+ finished = true;
40
+ clearTimeout(timer);
41
+ controller.abort();
42
+ void worker.terminate();
43
+ if (result)
44
+ resolve(result);
45
+ else
46
+ reject(Error('PROVIDER_CALL_FAILED_OR_OUTCOME_UNKNOWN'));
47
+ };
48
+ const timer = setTimeout(() => finish(), TIMEOUT);
49
+ worker.on('error', () => finish());
50
+ worker.on('exit', () => { if (!finished)
51
+ finish(); });
52
+ worker.on('message', async (message) => {
53
+ if (finished)
54
+ return;
55
+ if (message.type === 'failed')
56
+ return finish();
57
+ if (message.type === 'result') {
58
+ if (Buffer.byteLength(JSON.stringify(message.result)) > LIMIT * 4)
59
+ return finish();
60
+ return finish(message.result);
61
+ }
62
+ if (message.type !== 'request' || ++requests !== 1 ||
63
+ message.url !== 'https://api.openai.com/v1/chat/completions' ||
64
+ message.init?.method !== 'POST')
65
+ return finish();
66
+ try {
67
+ if (Buffer.byteLength(message.init.body) > LIMIT)
68
+ return finish();
69
+ const response = await request(message.url, {
70
+ ...message.init, redirect: 'error', signal: controller.signal,
71
+ });
72
+ if (finished)
73
+ return;
74
+ if (!response.ok || response.status !== 200 || !response.body ||
75
+ !/^application\/json(?:;|$)/i.test(response.headers.get('content-type') ?? '') ||
76
+ Number(response.headers.get('content-length') ?? 0) > LIMIT) {
77
+ void response.body?.cancel().catch(() => { });
78
+ return finish();
79
+ }
80
+ const reader = response.body.getReader(), chunks = [];
81
+ let size = 0;
82
+ try {
83
+ while (true) {
84
+ const { done, value } = await reader.read();
85
+ if (done)
86
+ break;
87
+ size += value.byteLength;
88
+ if (size > LIMIT || finished) {
89
+ await reader.cancel();
90
+ return finish();
91
+ }
92
+ chunks.push(value);
93
+ }
94
+ }
95
+ finally {
96
+ reader.releaseLock();
97
+ }
98
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
99
+ // Reject malformed/deep JSON and unsupported text shapes before SDK parsing.
100
+ let depth = 0, quoted = false, escaped = false;
101
+ for (const c of text) {
102
+ if (quoted) {
103
+ if (escaped)
104
+ escaped = false;
105
+ else if (c === '\\')
106
+ escaped = true;
107
+ else if (c === '"')
108
+ quoted = false;
109
+ }
110
+ else if (c === '"')
111
+ quoted = true;
112
+ else if (c === '{' || c === '[') {
113
+ if (++depth > 32)
114
+ throw Error('DEPTH');
115
+ }
116
+ else if (c === '}' || c === ']')
117
+ depth--;
118
+ }
119
+ const data = JSON.parse(text);
120
+ if (!Array.isArray(data.choices) || data.choices.length !== 1 ||
121
+ typeof data.choices[0]?.message?.content !== 'string' ||
122
+ data.choices[0]?.message?.tool_calls !== undefined ||
123
+ data.choices[0]?.message?.function_call !== undefined ||
124
+ data.choices[0]?.message?.refusal)
125
+ return finish();
126
+ if (!finished)
127
+ worker.postMessage({ type: 'response', body: text, status: 200 });
128
+ }
129
+ catch {
130
+ finish();
131
+ }
132
+ });
133
+ });
134
+ }
135
+ /** Real SDK wrapper, called once. No provider key from model arguments and no
136
+ * ambient Node credential discovery. Plaintext output goes only to its calling app. */
137
+ export async function runOpenAIRecorded(raw, runtime) {
138
+ let state = 'not_started';
139
+ let output = null;
140
+ // Initialize with the same separately reported default intent as orchestration.
141
+ let recording = await recordExecution({ kind: 'cer', bundle: {},
142
+ ...(raw && typeof raw === 'object' && 'certification' in raw ? { certification: raw.certification } : {}),
143
+ }, { captureSource: 'instrumented_provider_call' });
144
+ try {
145
+ if (boundedInput(raw))
146
+ throw Error('INPUT');
147
+ const parsed = inputSchema.parse(raw), p = parsed.params;
148
+ recording = { ...recording, evidence: 'not_created', localIntegrity: 'not_performed', reasonCode: 'PROVIDER_SETUP_REQUIRED' };
149
+ preflightEncryptedCustody(runtime.custody);
150
+ const key = runtime.apiKey();
151
+ if (!key || key.length > 4096 || /[\r\n]/.test(key))
152
+ throw Error('KEY');
153
+ // Validate SDK decision refs before any provider request, without changing a returned CER.
154
+ const probe = createSnapshotV2({
155
+ executionId: 'recording-preflight', provider: 'openai', model: p.model ?? 'gpt-4o',
156
+ input: p.input, output: '', instruction: p.instruction, instructionKind: 'system',
157
+ parameters: { temperature: p.parameters?.temperature ?? 0.7, maxTokens: p.parameters?.maxTokens ?? 1024,
158
+ topP: p.parameters?.topP ?? null, seed: p.parameters?.seed ?? null },
159
+ executionRole: p.executionRole ?? 'unspecified',
160
+ ...(p.decisionRefs ? { decisionRefs: p.decisionRefs } : {}),
161
+ });
162
+ if (!verifyCerV2(sealCerV2(probe)).ok)
163
+ throw Error('SDK_INPUT');
164
+ const params = {
165
+ ...p, apiKey: key, confidentialFields: ['input', 'output', 'instruction'],
166
+ confidentialDecisionRefIndexes: (p.decisionRefs ?? []).map((_, i) => i),
167
+ };
168
+ state = 'failed_or_outcome_unknown';
169
+ const result = await runOnce(params, runtime.request ?? globalThis.fetch);
170
+ state = 'completed';
171
+ output = result.output;
172
+ const bundle = result.bundle;
173
+ const eligible = disclosureEligible(bundle, 'public', OPENAI_DISCLOSURE);
174
+ recording = { ...recording, evidence: 'custody_failed', reasonCode: 'ENCRYPTED_CUSTODY_FAILED' };
175
+ retainEncrypted(bundle, result.snapshot, result.openings, runtime.custody);
176
+ recording = await recordExecution({
177
+ kind: 'cer', bundle, ...(parsed.certification ? { certification: parsed.certification } : {}),
178
+ }, {
179
+ captureSource: 'instrumented_provider_call',
180
+ ...(runtime.publish && eligible ? { publish: runtime.publish } : {}),
181
+ });
182
+ recording = { ...recording, custody: 'encrypted_owner_recipient' };
183
+ if (!eligible && recording.certificationIntent === 'node')
184
+ recording = {
185
+ ...recording, policyAuthorization: 'authorization_denied', reasonCode: 'PROVIDER_DISCLOSURE_PROFILE_REJECTED',
186
+ };
187
+ }
188
+ catch (error) {
189
+ // No raw exception, response body, SDK diagnostics, input or key is returned.
190
+ if (state === 'failed_or_outcome_unknown')
191
+ recording = { ...recording, reasonCode: 'PROVIDER_CALL_FAILED_OR_OUTCOME_UNKNOWN' };
192
+ else if (error instanceof EncryptedCustodyError)
193
+ recording = { ...recording, evidence: 'custody_failed', reasonCode: error.reasonCode };
194
+ }
195
+ return { providerCall: state, output, recording };
196
+ }
197
+ //# sourceMappingURL=openai.js.map
@@ -0,0 +1,9 @@
1
+ import * as z from 'zod/v4';
2
+ /**
3
+ * Discovery-only spelling of the existing unknown/any-JSON wire contract.
4
+ * Keep runtime validation at the existing handler/SDK boundary. Branch
5
+ * annotations prevent Zod from collapsing anyOf into unportable type arrays.
6
+ */
7
+ export declare const anyJsonValue: z.ZodUnknown;
8
+ /** {} and true are equivalent in this keyword; keep the runtime record intact. */
9
+ export declare const sdkMetadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
@@ -0,0 +1,20 @@
1
+ import * as z from 'zod/v4';
2
+ /**
3
+ * Discovery-only spelling of the existing unknown/any-JSON wire contract.
4
+ * Keep runtime validation at the existing handler/SDK boundary. Branch
5
+ * annotations prevent Zod from collapsing anyOf into unportable type arrays.
6
+ */
7
+ export const anyJsonValue = z.unknown().meta({
8
+ anyOf: [
9
+ { type: 'object', additionalProperties: true },
10
+ { type: 'array', minItems: 0 },
11
+ { type: 'string', minLength: 0 },
12
+ { type: 'number', description: 'Any JSON number.' },
13
+ { type: 'boolean', description: 'Any JSON boolean.' },
14
+ { type: 'null', description: 'JSON null.' },
15
+ ],
16
+ });
17
+ /** {} and true are equivalent in this keyword; keep the runtime record intact. */
18
+ export const sdkMetadata = z.record(z.string(), z.unknown())
19
+ .meta({ additionalProperties: true });
20
+ //# sourceMappingURL=json-schema.js.map
@@ -0,0 +1,15 @@
1
+ /** Policy limits, not NexArt protocol limits. Never truncate input evidence. */
2
+ export declare const LIMITS: Readonly<{
3
+ inputBytes: 1048576;
4
+ frameBytes: 1081344;
5
+ depth: 64;
6
+ nodes: 25000;
7
+ objectKeys: 4096;
8
+ arrayItems: 4096;
9
+ projectSteps: 100;
10
+ outputBytes: 262144;
11
+ }>;
12
+ export type LimitCode = 'INPUT_TOO_LARGE' | 'JSON_TOO_DEEP' | 'JSON_TOO_COMPLEX' | 'PROJECT_STEP_LIMIT' | 'NON_JSON_INPUT';
13
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
14
+ /** Iterative traversal avoids recursion and rejects cycles/non-JSON library callers. */
15
+ export declare function checkInput(input: unknown): LimitCode | undefined;
package/dist/limits.js ADDED
@@ -0,0 +1,62 @@
1
+ /** Policy limits, not NexArt protocol limits. Never truncate input evidence. */
2
+ export const LIMITS = Object.freeze({
3
+ inputBytes: 1_048_576,
4
+ frameBytes: 1_081_344,
5
+ depth: 64,
6
+ nodes: 25_000,
7
+ objectKeys: 4_096,
8
+ arrayItems: 4_096,
9
+ projectSteps: 100,
10
+ outputBytes: 262_144,
11
+ });
12
+ export function isObject(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /** Iterative traversal avoids recursion and rejects cycles/non-JSON library callers. */
16
+ export function checkInput(input) {
17
+ const queue = [{ value: input, depth: 0 }];
18
+ const seen = new WeakSet();
19
+ let count = 0;
20
+ while (queue.length) {
21
+ const { value, depth } = queue.pop();
22
+ if (++count > LIMITS.nodes)
23
+ return 'JSON_TOO_COMPLEX';
24
+ if (depth > LIMITS.depth)
25
+ return 'JSON_TOO_DEEP';
26
+ if (typeof value === 'number' && !Number.isFinite(value))
27
+ return 'NON_JSON_INPUT';
28
+ if (value === null || ['string', 'boolean', 'number'].includes(typeof value))
29
+ continue;
30
+ if (typeof value !== 'object')
31
+ return 'NON_JSON_INPUT';
32
+ if (seen.has(value))
33
+ return 'NON_JSON_INPUT';
34
+ seen.add(value);
35
+ if (Array.isArray(value)) {
36
+ if (value.length > LIMITS.arrayItems)
37
+ return 'JSON_TOO_COMPLEX';
38
+ for (const child of value)
39
+ queue.push({ value: child, depth: depth + 1 });
40
+ }
41
+ else {
42
+ if (Object.getPrototypeOf(value) !== Object.prototype &&
43
+ Object.getPrototypeOf(value) !== null)
44
+ return 'NON_JSON_INPUT';
45
+ const keys = Object.keys(value);
46
+ if (keys.length > LIMITS.objectKeys)
47
+ return 'JSON_TOO_COMPLEX';
48
+ for (const key of keys) {
49
+ const property = Object.getOwnPropertyDescriptor(value, key);
50
+ if (!property || !('value' in property))
51
+ return 'NON_JSON_INPUT';
52
+ queue.push({ value: property.value, depth: depth + 1 });
53
+ }
54
+ }
55
+ if (queue.length + count > LIMITS.nodes)
56
+ return 'JSON_TOO_COMPLEX';
57
+ }
58
+ return Buffer.byteLength(JSON.stringify(input), 'utf8') > LIMITS.inputBytes
59
+ ? 'INPUT_TOO_LARGE'
60
+ : undefined;
61
+ }
62
+ //# sourceMappingURL=limits.js.map
@@ -0,0 +1,38 @@
1
+ import * as z from 'zod/v4';
2
+ export declare const LOOKUP_NAMES: readonly ["nexart_lookup_cer", "nexart_lookup_project_bundle"];
3
+ export declare const lookupCerInput: z.ZodObject<{
4
+ certificateHash: z.ZodString;
5
+ }, z.core.$strict>;
6
+ export declare const lookupProjectInput: z.ZodObject<{
7
+ projectHash: z.ZodString;
8
+ }, z.core.$strict>;
9
+ export declare const lookupOutput: z.ZodObject<{
10
+ contractVersion: z.ZodLiteral<"1">;
11
+ lookup: z.ZodEnum<{
12
+ unavailable: "unavailable";
13
+ rejected: "rejected";
14
+ found: "found";
15
+ not_found_or_not_public: "not_found_or_not_public";
16
+ }>;
17
+ reasonCode: z.ZodString;
18
+ family: z.ZodNullable<z.ZodEnum<{
19
+ "cer.ai.execution.v1": "cer.ai.execution.v1";
20
+ "cer.ai.execution.v2": "cer.ai.execution.v2";
21
+ "cer.consequential.execution.v1": "cer.consequential.execution.v1";
22
+ "cer.governed.execution.v1": "cer.governed.execution.v1";
23
+ "cer.project.bundle.v1": "cer.project.bundle.v1";
24
+ }>>;
25
+ integrity: z.ZodEnum<{
26
+ valid: "valid";
27
+ invalid: "invalid";
28
+ not_performed: "not_performed";
29
+ indeterminate: "indeterminate";
30
+ }>;
31
+ integrityScope: z.ZodLiteral<"returned_bundle">;
32
+ sdk: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
33
+ receiptPresent: z.ZodBoolean;
34
+ nodeSignature: z.ZodLiteral<"not_performed">;
35
+ signerTrust: z.ZodLiteral<"not_established">;
36
+ limitations: z.ZodArray<z.ZodString>;
37
+ }, z.core.$strict>;
38
+ export type LookupOutput = z.infer<typeof lookupOutput>;
@@ -0,0 +1,23 @@
1
+ import * as z from 'zod/v4';
2
+ import { sdkMetadata } from '../json-schema.js';
3
+ import { hashSchema } from '../network/contracts.js';
4
+ export const LOOKUP_NAMES = ['nexart_lookup_cer', 'nexart_lookup_project_bundle'];
5
+ export const lookupCerInput = z.strictObject({ certificateHash: hashSchema });
6
+ export const lookupProjectInput = z.strictObject({ projectHash: hashSchema });
7
+ export const lookupOutput = z.strictObject({
8
+ contractVersion: z.literal('1'),
9
+ lookup: z.enum(['found', 'not_found_or_not_public', 'unavailable', 'rejected']),
10
+ reasonCode: z.string().max(96),
11
+ family: z.enum([
12
+ 'cer.ai.execution.v1', 'cer.ai.execution.v2', 'cer.consequential.execution.v1',
13
+ 'cer.governed.execution.v1', 'cer.project.bundle.v1',
14
+ ]).nullable(),
15
+ integrity: z.enum(['valid', 'invalid', 'not_performed', 'indeterminate']),
16
+ integrityScope: z.literal('returned_bundle'),
17
+ sdk: sdkMetadata.nullable(),
18
+ receiptPresent: z.boolean(),
19
+ nodeSignature: z.literal('not_performed'),
20
+ signerTrust: z.literal('not_established'),
21
+ limitations: z.array(z.string().max(256)).max(12),
22
+ });
23
+ //# sourceMappingURL=contracts.js.map