@harnesys/sdk 0.0.0-stage → 1.1.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 (147) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -2
  3. package/dist/addon-context-factory.d.ts +6 -0
  4. package/dist/addon-context-factory.js +160 -0
  5. package/dist/addon-context.d.ts +346 -0
  6. package/dist/addon-context.js +0 -0
  7. package/dist/define-addon.d.ts +57 -0
  8. package/dist/define-addon.js +53 -0
  9. package/dist/families/config.d.ts +14 -0
  10. package/dist/families/config.js +16 -0
  11. package/dist/families/content.d.ts +28 -0
  12. package/dist/families/content.js +19 -0
  13. package/dist/families/field-spec.d.ts +100 -0
  14. package/dist/families/field-spec.js +85 -0
  15. package/dist/families/hook.d.ts +37 -0
  16. package/dist/families/hook.js +25 -0
  17. package/dist/families/job.d.ts +45 -0
  18. package/dist/families/job.js +26 -0
  19. package/dist/families/json-schema-value.d.ts +12 -0
  20. package/dist/families/json-schema-value.js +243 -0
  21. package/dist/families/json-schema.d.ts +36 -0
  22. package/dist/families/json-schema.js +101 -0
  23. package/dist/families/lsp.d.ts +18 -0
  24. package/dist/families/lsp.js +18 -0
  25. package/dist/families/mcp.d.ts +18 -0
  26. package/dist/families/mcp.js +18 -0
  27. package/dist/families/registry.d.ts +9 -0
  28. package/dist/families/registry.js +34 -0
  29. package/dist/families/route.d.ts +38 -0
  30. package/dist/families/route.js +37 -0
  31. package/dist/families/source-kind.d.ts +24 -0
  32. package/dist/families/source-kind.js +21 -0
  33. package/dist/families/tool-pack.d.ts +68 -0
  34. package/dist/families/tool-pack.js +57 -0
  35. package/dist/families/transport.d.ts +52 -0
  36. package/dist/families/transport.js +29 -0
  37. package/dist/families/trigger.d.ts +97 -0
  38. package/dist/families/trigger.js +46 -0
  39. package/dist/families/view.d.ts +255 -0
  40. package/dist/families/view.js +87 -0
  41. package/dist/families/viewer.d.ts +31 -0
  42. package/dist/families/viewer.js +26 -0
  43. package/dist/families/worker.d.ts +23 -0
  44. package/dist/families/worker.js +19 -0
  45. package/dist/host-client.d.ts +11 -0
  46. package/dist/host-client.js +30 -0
  47. package/dist/index.d.ts +36 -0
  48. package/dist/index.js +36 -0
  49. package/dist/manifest/branding.d.ts +14 -0
  50. package/dist/manifest/branding.js +18 -0
  51. package/dist/manifest/connections.d.ts +21 -0
  52. package/dist/manifest/connections.js +10 -0
  53. package/dist/manifest/json-schema.d.ts +2 -0
  54. package/dist/manifest/json-schema.js +13 -0
  55. package/dist/manifest/l10n.d.ts +9 -0
  56. package/dist/manifest/l10n.js +28 -0
  57. package/dist/manifest/manifest.d.ts +112 -0
  58. package/dist/manifest/manifest.js +45 -0
  59. package/dist/manifest/validate.d.ts +14 -0
  60. package/dist/manifest/validate.js +144 -0
  61. package/dist/permissions/permissions.d.ts +31 -0
  62. package/dist/permissions/permissions.js +53 -0
  63. package/dist/process-entry.d.ts +26 -0
  64. package/dist/process-entry.js +146 -0
  65. package/dist/protocol/envelope.d.ts +115 -0
  66. package/dist/protocol/envelope.js +72 -0
  67. package/dist/protocol/error.d.ts +67 -0
  68. package/dist/protocol/error.js +61 -0
  69. package/dist/protocol/handshake.d.ts +55 -0
  70. package/dist/protocol/handshake.js +26 -0
  71. package/dist/protocol/map.d.ts +1090 -0
  72. package/dist/protocol/map.js +127 -0
  73. package/dist/protocol/meta.d.ts +31 -0
  74. package/dist/protocol/meta.js +14 -0
  75. package/dist/protocol/method-spec.d.ts +13 -0
  76. package/dist/protocol/method-spec.js +9 -0
  77. package/dist/protocol/org-service-methods.d.ts +135 -0
  78. package/dist/protocol/org-service-methods.js +106 -0
  79. package/dist/protocol/shared.d.ts +389 -0
  80. package/dist/protocol/shared.js +231 -0
  81. package/dist/protocol/source-methods.d.ts +218 -0
  82. package/dist/protocol/source-methods.js +18 -0
  83. package/dist/protocol/thread-service-methods.d.ts +50 -0
  84. package/dist/protocol/thread-service-methods.js +32 -0
  85. package/dist/runtime.d.ts +25 -0
  86. package/dist/runtime.js +229 -0
  87. package/dist/testing/fake-db.d.ts +15 -0
  88. package/dist/testing/fake-db.js +120 -0
  89. package/dist/testing/fake-files.d.ts +9 -0
  90. package/dist/testing/fake-files.js +87 -0
  91. package/dist/testing/fake-host.d.ts +115 -0
  92. package/dist/testing/fake-host.js +217 -0
  93. package/dist/testing/fake-services.d.ts +63 -0
  94. package/dist/testing/fake-services.js +277 -0
  95. package/dist/testing/fixtures.d.ts +5 -0
  96. package/dist/testing/fixtures.js +101 -0
  97. package/dist/testing/index.d.ts +4 -0
  98. package/dist/testing/index.js +2 -0
  99. package/package.json +66 -4
  100. package/src/addon-context-factory.ts +236 -0
  101. package/src/addon-context.ts +313 -0
  102. package/src/define-addon.ts +178 -0
  103. package/src/families/config.ts +24 -0
  104. package/src/families/content.ts +35 -0
  105. package/src/families/field-spec.ts +175 -0
  106. package/src/families/hook.ts +34 -0
  107. package/src/families/job.ts +41 -0
  108. package/src/families/json-schema-value.ts +322 -0
  109. package/src/families/json-schema.ts +167 -0
  110. package/src/families/lsp.ts +28 -0
  111. package/src/families/mcp.ts +28 -0
  112. package/src/families/registry.ts +44 -0
  113. package/src/families/route.ts +52 -0
  114. package/src/families/source-kind.ts +34 -0
  115. package/src/families/tool-pack.ts +92 -0
  116. package/src/families/transport.ts +52 -0
  117. package/src/families/trigger.ts +92 -0
  118. package/src/families/view.ts +144 -0
  119. package/src/families/viewer.ts +43 -0
  120. package/src/families/worker.ts +30 -0
  121. package/src/host-client.ts +52 -0
  122. package/src/index.ts +345 -0
  123. package/src/manifest/branding.ts +24 -0
  124. package/src/manifest/connections.ts +21 -0
  125. package/src/manifest/json-schema.ts +24 -0
  126. package/src/manifest/l10n.ts +39 -0
  127. package/src/manifest/manifest.ts +94 -0
  128. package/src/manifest/validate.ts +200 -0
  129. package/src/permissions/permissions.ts +79 -0
  130. package/src/process-entry.ts +205 -0
  131. package/src/protocol/envelope.ts +126 -0
  132. package/src/protocol/error.ts +81 -0
  133. package/src/protocol/handshake.ts +43 -0
  134. package/src/protocol/map.ts +339 -0
  135. package/src/protocol/meta.ts +26 -0
  136. package/src/protocol/method-spec.ts +40 -0
  137. package/src/protocol/org-service-methods.ts +148 -0
  138. package/src/protocol/shared.ts +345 -0
  139. package/src/protocol/source-methods.ts +61 -0
  140. package/src/protocol/thread-service-methods.ts +50 -0
  141. package/src/runtime.ts +332 -0
  142. package/src/testing/fake-db.ts +140 -0
  143. package/src/testing/fake-files.ts +114 -0
  144. package/src/testing/fake-host.ts +350 -0
  145. package/src/testing/fake-services.ts +345 -0
  146. package/src/testing/fixtures.ts +106 -0
  147. package/src/testing/index.ts +12 -0
@@ -0,0 +1,144 @@
1
+ import { familyRegistry } from "../families/registry.js";
2
+ import { isKnownPermissionId } from "../permissions/permissions.js";
3
+ import { l10nKeys } from "./l10n.js";
4
+ import { AddonManifestSchema } from "./manifest.js";
5
+ export function validateManifest(raw, options) {
6
+ const violations = [];
7
+ const parsed = AddonManifestSchema.safeParse(raw);
8
+ if (!parsed.success) {
9
+ for (const issue of parsed.error.issues) {
10
+ violations.push({
11
+ path: issue.path.map(String).join('.') || '(root)',
12
+ code: 'schema',
13
+ message: issue.message,
14
+ severity: 'error',
15
+ });
16
+ }
17
+ return { manifest: null, violations };
18
+ }
19
+ const context = {
20
+ manifest: parsed.data,
21
+ violations,
22
+ connectionIds: new Set(parsed.data.connections.map((c) => c.id)),
23
+ idsByKind: { route: new Set(), job: new Set(), worker: new Set() },
24
+ contributionIds: new Set(),
25
+ };
26
+ checkPermissions(context);
27
+ checkContributions(context);
28
+ checkL10nKeys(parsed.data, violations, options);
29
+ return { manifest: parsed.data, violations };
30
+ }
31
+ function checkPermissions(context) {
32
+ const { manifest, violations } = context;
33
+ for (const permission of manifest.permissions) {
34
+ if (!isKnownPermissionId(permission.id)) {
35
+ violations.push({
36
+ path: `permissions[${permission.id}]`,
37
+ code: 'unknown_permission',
38
+ message: `unknown permission id '${permission.id}'`,
39
+ severity: 'error',
40
+ });
41
+ }
42
+ }
43
+ if (manifest.activation === 'resident' &&
44
+ !manifest.permissions.some((p) => p.id === 'lifecycle.resident')) {
45
+ violations.push({
46
+ path: 'activation',
47
+ code: 'resident_without_permission',
48
+ message: `activation 'resident' requires the 'lifecycle.resident' permission`,
49
+ severity: 'error',
50
+ });
51
+ }
52
+ }
53
+ function checkContributions(context) {
54
+ const { manifest, violations } = context;
55
+ for (const [index, contribution] of manifest.contributions.entries()) {
56
+ const path = `contributions[${contribution.id || index}]`;
57
+ checkContributionId(context, contribution.id, path);
58
+ const schema = familyRegistry[contribution.family]?.schema(contribution.v ?? 1);
59
+ if (!schema) {
60
+ violations.push({
61
+ path,
62
+ code: 'unknown_family',
63
+ message: `unknown family '${contribution.family}'`,
64
+ severity: contribution.optional === true ? 'warning' : 'error',
65
+ });
66
+ continue;
67
+ }
68
+ checkDescriptorSchema(path, contribution.descriptor, schema, violations);
69
+ checkDescriptorRefs(context, path, contribution.family, contribution.descriptor);
70
+ }
71
+ }
72
+ function checkContributionId(context, id, path) {
73
+ if (context.contributionIds.has(id)) {
74
+ context.violations.push({
75
+ path,
76
+ code: 'duplicate_contribution_id',
77
+ message: `duplicate contribution id '${id}'`,
78
+ severity: 'error',
79
+ });
80
+ }
81
+ context.contributionIds.add(id);
82
+ }
83
+ function checkDescriptorSchema(path, descriptor, schema, violations) {
84
+ const parsed = schema.safeParse(descriptor);
85
+ if (parsed.success) {
86
+ return;
87
+ }
88
+ for (const issue of parsed.error.issues) {
89
+ violations.push({
90
+ path: `${path}.descriptor.${issue.path.map(String).join('.')}`,
91
+ code: 'descriptor_schema',
92
+ message: issue.message,
93
+ severity: 'error',
94
+ });
95
+ }
96
+ }
97
+ function checkDescriptorRefs(context, path, family, descriptor) {
98
+ const connection = descriptor.connection;
99
+ if (typeof connection === 'string' && !context.connectionIds.has(connection)) {
100
+ context.violations.push({
101
+ path,
102
+ code: 'unknown_connection',
103
+ message: `descriptor references undeclared connection '${connection}'`,
104
+ severity: 'error',
105
+ });
106
+ }
107
+ checkUniqueEntityId(context, family, descriptor, path);
108
+ }
109
+ function checkUniqueEntityId(context, family, descriptor, path) {
110
+ const ids = context.idsByKind[family];
111
+ if (!ids) {
112
+ return;
113
+ }
114
+ const id = descriptor.id ?? descriptor.name ?? descriptor.kind ?? descriptor.provider;
115
+ if (typeof id !== 'string') {
116
+ return;
117
+ }
118
+ if (ids.has(id)) {
119
+ context.violations.push({
120
+ path,
121
+ code: 'duplicate_id',
122
+ message: `duplicate ${family} id '${id}'`,
123
+ severity: 'error',
124
+ });
125
+ }
126
+ ids.add(id);
127
+ }
128
+ function checkL10nKeys(manifest, violations, options) {
129
+ if (!options?.l10nKeys) {
130
+ return;
131
+ }
132
+ const available = new Set(options.l10nKeys);
133
+ const used = [...l10nKeys(manifest.title), ...l10nKeys(manifest.description)];
134
+ for (const key of used) {
135
+ if (!available.has(key)) {
136
+ violations.push({
137
+ path: 'title',
138
+ code: 'missing_l10n_key',
139
+ message: `l10n key '%${key}%' is not present in l10n/en.json`,
140
+ severity: 'error',
141
+ });
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,31 @@
1
+ import { z } from 'zod';
2
+ export declare const JsonObjectSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3
+ export type JsonObject = Record<string, unknown>;
4
+ export declare const PermissionScopeSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
5
+ export type PermissionScope = JsonObject;
6
+ export interface PermissionRequest {
7
+ id: string;
8
+ scope?: JsonObject;
9
+ reason: string;
10
+ optional?: boolean;
11
+ }
12
+ export declare const PermissionRequestSchema: z.ZodObject<{
13
+ id: z.ZodString;
14
+ scope: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
15
+ reason: z.ZodString;
16
+ optional: z.ZodOptional<z.ZodBoolean>;
17
+ }, z.core.$strip>;
18
+ export interface EffectivePermission {
19
+ id: string;
20
+ scope?: JsonObject;
21
+ }
22
+ export declare const EffectivePermissionSchema: z.ZodObject<{
23
+ id: z.ZodString;
24
+ scope: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
25
+ }, z.core.$strip>;
26
+ export declare const BASELINE_PERMISSION_IDS: readonly ["config.read", "log", "db", "secrets.own", "events.emit.own", "org.read"];
27
+ export type BaselinePermissionId = (typeof BASELINE_PERMISSION_IDS)[number];
28
+ export declare const KNOWN_PERMISSION_IDS: readonly ["config.read", "log", "db", "secrets.own", "events.emit.own", "org.read", "http.fetch", "accounts.use", "accounts.credentials", "runs.dispatch", "runs.read", "threads.create", "threads.compact", "threads.read", "threads.write", "agents.read", "bindings.write", "usage.read", "skills.read", "events.subscribe", "files.read", "files.write", "bridge.inbound", "routes.public", "lifecycle.resident", "trigger", "approvals.request", "worker", "source"];
29
+ export type KnownPermissionId = (typeof KNOWN_PERMISSION_IDS)[number];
30
+ export declare function isKnownPermissionId(id: string): boolean;
31
+ export declare function isBaselinePermissionId(id: string): boolean;
@@ -0,0 +1,53 @@
1
+ import { z } from 'zod';
2
+ export const JsonObjectSchema = z.record(z.string(), z.unknown());
3
+ export const PermissionScopeSchema = JsonObjectSchema;
4
+ export const PermissionRequestSchema = z.object({
5
+ id: z.string().min(1),
6
+ scope: PermissionScopeSchema.optional(),
7
+ reason: z.string().min(1),
8
+ optional: z.boolean().optional(),
9
+ });
10
+ export const EffectivePermissionSchema = z.object({
11
+ id: z.string().min(1),
12
+ scope: PermissionScopeSchema.optional(),
13
+ });
14
+ export const BASELINE_PERMISSION_IDS = [
15
+ 'config.read',
16
+ 'log',
17
+ 'db',
18
+ 'secrets.own',
19
+ 'events.emit.own',
20
+ 'org.read',
21
+ ];
22
+ export const KNOWN_PERMISSION_IDS = [
23
+ ...BASELINE_PERMISSION_IDS,
24
+ 'http.fetch',
25
+ 'accounts.use',
26
+ 'accounts.credentials',
27
+ 'runs.dispatch',
28
+ 'runs.read',
29
+ 'threads.create',
30
+ 'threads.compact',
31
+ 'threads.read',
32
+ 'threads.write',
33
+ 'agents.read',
34
+ 'bindings.write',
35
+ 'usage.read',
36
+ 'skills.read',
37
+ 'events.subscribe',
38
+ 'files.read',
39
+ 'files.write',
40
+ 'bridge.inbound',
41
+ 'routes.public',
42
+ 'lifecycle.resident',
43
+ 'trigger',
44
+ 'approvals.request',
45
+ 'worker',
46
+ 'source',
47
+ ];
48
+ export function isKnownPermissionId(id) {
49
+ return KNOWN_PERMISSION_IDS.includes(id);
50
+ }
51
+ export function isBaselinePermissionId(id) {
52
+ return BASELINE_PERMISSION_IDS.includes(id);
53
+ }
@@ -0,0 +1,26 @@
1
+ import type { ResolvedAddonDefinition } from './define-addon.ts';
2
+ import type { HostChannel } from './host-client.ts';
3
+ import type { JsonRpcResponse } from './protocol/envelope.ts';
4
+ export declare const PROTOCOL_PLATFORM = 1;
5
+ export type StdioWiringStdin = AsyncIterable<Uint8Array> | ReadableStream<Uint8Array>;
6
+ export interface StdioWiring {
7
+ stdin: StdioWiringStdin;
8
+ stdout: {
9
+ write(chunk: string): unknown;
10
+ };
11
+ stderr: {
12
+ write(chunk: string): unknown;
13
+ };
14
+ }
15
+ export interface StartAddonProcessOptions {
16
+ definition: ResolvedAddonDefinition;
17
+ addon: {
18
+ id: string;
19
+ version: string;
20
+ };
21
+ wiring?: StdioWiring;
22
+ }
23
+ export declare function createStdioChannel(wiring: StdioWiring): HostChannel & {
24
+ resolveResponse(message: JsonRpcResponse): void;
25
+ };
26
+ export declare function startAddonProcess(options: StartAddonProcessOptions): Promise<void>;
@@ -0,0 +1,146 @@
1
+ import { decodeMessage, encodeMessage, errorResponse, request, response, } from "./protocol/envelope.js";
2
+ import { AddonError, isAddonError } from "./protocol/error.js";
3
+ import { createAddonRuntime } from "./runtime.js";
4
+ export const PROTOCOL_PLATFORM = 1;
5
+ const ERROR_CODES = {
6
+ invalid_params: -32602,
7
+ unsupported: -32601,
8
+ not_found: -32601,
9
+ };
10
+ function stdinSource(stdin) {
11
+ if ('values' in stdin && typeof stdin.values === 'function') {
12
+ return stdin.values();
13
+ }
14
+ return stdin;
15
+ }
16
+ export function createStdioChannel(wiring) {
17
+ let nextId = 0;
18
+ const pending = new Map();
19
+ function write(line) {
20
+ wiring.stdout.write(line);
21
+ }
22
+ return {
23
+ request(method, params, signal) {
24
+ nextId += 1;
25
+ const id = nextId;
26
+ return new Promise((resolve, reject) => {
27
+ pending.set(id, { resolve, reject });
28
+ signal?.addEventListener('abort', () => {
29
+ if (pending.has(id)) {
30
+ pending.delete(id);
31
+ reject(new AddonError('cancelled'));
32
+ }
33
+ }, { once: true });
34
+ write(encodeMessage(request(method, id, params)));
35
+ });
36
+ },
37
+ notify(method, params) {
38
+ write(encodeMessage({ jsonrpc: '2.0', method, params }));
39
+ },
40
+ resolveResponse(message) {
41
+ const call = pending.get(message.id);
42
+ if (!call) {
43
+ return;
44
+ }
45
+ pending.delete(message.id);
46
+ if (message.error) {
47
+ const data = message.error.data;
48
+ call.reject(data === undefined
49
+ ? new Error(message.error.message)
50
+ : new AddonError(data.reason, {
51
+ retryable: data.retryable,
52
+ detail: data.detail,
53
+ accountCode: data.accountCode,
54
+ }));
55
+ }
56
+ else {
57
+ call.resolve(message.result);
58
+ }
59
+ },
60
+ };
61
+ }
62
+ export async function startAddonProcess(options) {
63
+ const wiring = options.wiring ?? {
64
+ stdin: Bun.stdin.stream(),
65
+ stdout: process.stdout,
66
+ stderr: process.stderr,
67
+ };
68
+ const channel = createStdioChannel(wiring);
69
+ const runtime = createAddonRuntime({
70
+ definition: options.definition,
71
+ addon: options.addon,
72
+ channel,
73
+ });
74
+ const controllers = new Map();
75
+ function reply(id, result) {
76
+ wiring.stdout.write(encodeMessage(response(id, result)));
77
+ }
78
+ function replyError(id, error) {
79
+ const data = isAddonError(error)
80
+ ? error.toData()
81
+ : { reason: 'internal', retryable: false };
82
+ if (!isAddonError(error)) {
83
+ wiring.stderr.write(`addon request failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
84
+ }
85
+ const reason = data.reason;
86
+ wiring.stdout.write(encodeMessage(errorResponse(id, { code: ERROR_CODES[reason] ?? -32000, message: reason, data })));
87
+ }
88
+ function logFailure(scope, error) {
89
+ wiring.stderr.write(`addon ${scope} failed: ${error instanceof Error ? error.message : String(error)}\n`);
90
+ }
91
+ async function handleLine(line) {
92
+ const message = decodeMessage(line);
93
+ if ('method' in message && 'id' in message) {
94
+ await handleHostRequest(message.method, message.id, message.params);
95
+ return;
96
+ }
97
+ if ('method' in message) {
98
+ await handleHostNotification(message.method, message.params);
99
+ return;
100
+ }
101
+ channel.resolveResponse(message);
102
+ }
103
+ async function handleHostRequest(method, id, params) {
104
+ const controller = new AbortController();
105
+ controllers.set(id, controller);
106
+ try {
107
+ const result = method === 'initialize'
108
+ ? runtime.initialize(params)
109
+ : await runtime.handleRequest(method, params, controller.signal);
110
+ reply(id, result);
111
+ }
112
+ catch (error) {
113
+ replyError(id, error);
114
+ }
115
+ finally {
116
+ controllers.delete(id);
117
+ }
118
+ }
119
+ async function handleHostNotification(method, params) {
120
+ if (method === '$/cancel') {
121
+ const cancelParams = (params ?? {});
122
+ if (cancelParams.id !== undefined) {
123
+ controllers.get(cancelParams.id)?.abort();
124
+ }
125
+ return;
126
+ }
127
+ try {
128
+ await runtime.handleNotification(method, params, new AbortController().signal);
129
+ }
130
+ catch (error) {
131
+ logFailure(`notification ${method}`, error);
132
+ }
133
+ }
134
+ for await (const chunk of stdinSource(wiring.stdin)) {
135
+ const text = new TextDecoder().decode(chunk);
136
+ for (const line of text.split('\n')) {
137
+ const trimmed = line.trim();
138
+ if (trimmed.length === 0) {
139
+ continue;
140
+ }
141
+ void handleLine(trimmed).catch((error) => {
142
+ replyError(null, error);
143
+ });
144
+ }
145
+ }
146
+ }
@@ -0,0 +1,115 @@
1
+ import { z } from 'zod';
2
+ export declare const JSONRPC_VERSION = "2.0";
3
+ export declare const MAX_MESSAGE_BYTES: number;
4
+ export declare const JsonRpcIdSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
5
+ export declare const JsonRpcRequestSchema: z.ZodObject<{
6
+ jsonrpc: z.ZodLiteral<"2.0">;
7
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
8
+ method: z.ZodString;
9
+ params: z.ZodOptional<z.ZodUnknown>;
10
+ }, z.core.$strip>;
11
+ export declare const JsonRpcNotificationSchema: z.ZodObject<{
12
+ jsonrpc: z.ZodLiteral<"2.0">;
13
+ method: z.ZodString;
14
+ params: z.ZodOptional<z.ZodUnknown>;
15
+ }, z.core.$strip>;
16
+ export declare const JsonRpcErrorSchema: z.ZodObject<{
17
+ code: z.ZodNumber;
18
+ message: z.ZodString;
19
+ data: z.ZodOptional<z.ZodObject<{
20
+ reason: z.ZodEnum<{
21
+ invalid_params: "invalid_params";
22
+ invalid_response: "invalid_response";
23
+ permission_denied: "permission_denied";
24
+ not_found: "not_found";
25
+ conflict: "conflict";
26
+ quota_exceeded: "quota_exceeded";
27
+ rate_limited: "rate_limited";
28
+ timeout: "timeout";
29
+ cancelled: "cancelled";
30
+ unavailable: "unavailable";
31
+ unsupported: "unsupported";
32
+ account_failed: "account_failed";
33
+ incompatible_handlers: "incompatible_handlers";
34
+ migration_failed: "migration_failed";
35
+ permission_revoked: "permission_revoked";
36
+ internal: "internal";
37
+ }>;
38
+ retryable: z.ZodBoolean;
39
+ detail: z.ZodOptional<z.ZodString>;
40
+ accountCode: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strip>>;
42
+ }, z.core.$strip>;
43
+ export declare const JsonRpcResponseSchema: z.ZodObject<{
44
+ jsonrpc: z.ZodLiteral<"2.0">;
45
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
46
+ result: z.ZodOptional<z.ZodUnknown>;
47
+ error: z.ZodOptional<z.ZodObject<{
48
+ code: z.ZodNumber;
49
+ message: z.ZodString;
50
+ data: z.ZodOptional<z.ZodObject<{
51
+ reason: z.ZodEnum<{
52
+ invalid_params: "invalid_params";
53
+ invalid_response: "invalid_response";
54
+ permission_denied: "permission_denied";
55
+ not_found: "not_found";
56
+ conflict: "conflict";
57
+ quota_exceeded: "quota_exceeded";
58
+ rate_limited: "rate_limited";
59
+ timeout: "timeout";
60
+ cancelled: "cancelled";
61
+ unavailable: "unavailable";
62
+ unsupported: "unsupported";
63
+ account_failed: "account_failed";
64
+ incompatible_handlers: "incompatible_handlers";
65
+ migration_failed: "migration_failed";
66
+ permission_revoked: "permission_revoked";
67
+ internal: "internal";
68
+ }>;
69
+ retryable: z.ZodBoolean;
70
+ detail: z.ZodOptional<z.ZodString>;
71
+ accountCode: z.ZodOptional<z.ZodString>;
72
+ }, z.core.$strip>>;
73
+ }, z.core.$strip>>;
74
+ }, z.core.$strip>;
75
+ export type JsonRpcRequest = z.infer<typeof JsonRpcRequestSchema>;
76
+ export type JsonRpcNotification = z.infer<typeof JsonRpcNotificationSchema>;
77
+ export type JsonRpcResponse = z.infer<typeof JsonRpcResponseSchema>;
78
+ export type JsonRpcError = z.infer<typeof JsonRpcErrorSchema>;
79
+ export declare const CancelNotificationSchema: z.ZodObject<{
80
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
81
+ }, z.core.$strip>;
82
+ export type CancelNotification = z.infer<typeof CancelNotificationSchema>;
83
+ export declare const ProgressNotificationSchema: z.ZodObject<{
84
+ token: z.ZodString;
85
+ value: z.ZodUnknown;
86
+ }, z.core.$strip>;
87
+ export type ProgressNotification = z.infer<typeof ProgressNotificationSchema>;
88
+ export interface OutgoingRequest {
89
+ jsonrpc: typeof JSONRPC_VERSION;
90
+ id: string | number;
91
+ method: string;
92
+ params?: unknown;
93
+ }
94
+ export interface OutgoingNotification {
95
+ jsonrpc: typeof JSONRPC_VERSION;
96
+ method: string;
97
+ params?: unknown;
98
+ }
99
+ export interface OutgoingResponse {
100
+ jsonrpc: typeof JSONRPC_VERSION;
101
+ id: string | number;
102
+ result?: unknown;
103
+ error?: JsonRpcError;
104
+ }
105
+ export declare function request(method: string, id: string | number, params?: unknown): OutgoingRequest;
106
+ export declare function notification(method: string, params?: unknown): OutgoingNotification;
107
+ export declare function response(id: string | number, result: unknown): OutgoingResponse;
108
+ export declare function errorResponse(id: string | number | null, error: JsonRpcError): OutgoingErrorResponse;
109
+ export interface OutgoingErrorResponse {
110
+ jsonrpc: typeof JSONRPC_VERSION;
111
+ id: string | number | null;
112
+ error: JsonRpcError;
113
+ }
114
+ export declare function encodeMessage(message: OutgoingRequest | OutgoingNotification | OutgoingResponse | OutgoingErrorResponse): string;
115
+ export declare function decodeMessage(line: string): JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ import { AddonErrorDataSchema } from "./error.js";
3
+ export const JSONRPC_VERSION = '2.0';
4
+ export const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
5
+ export const JsonRpcIdSchema = z.union([z.string(), z.number()]);
6
+ export const JsonRpcRequestSchema = z.object({
7
+ jsonrpc: z.literal(JSONRPC_VERSION),
8
+ id: JsonRpcIdSchema,
9
+ method: z.string().min(1),
10
+ params: z.unknown().optional(),
11
+ });
12
+ export const JsonRpcNotificationSchema = z.object({
13
+ jsonrpc: z.literal(JSONRPC_VERSION),
14
+ method: z.string().min(1),
15
+ params: z.unknown().optional(),
16
+ });
17
+ export const JsonRpcErrorSchema = z.object({
18
+ code: z.number().int(),
19
+ message: z.string().min(1),
20
+ data: AddonErrorDataSchema.optional(),
21
+ });
22
+ export const JsonRpcResponseSchema = z.object({
23
+ jsonrpc: z.literal(JSONRPC_VERSION),
24
+ id: JsonRpcIdSchema,
25
+ result: z.unknown().optional(),
26
+ error: JsonRpcErrorSchema.optional(),
27
+ });
28
+ export const CancelNotificationSchema = z.object({ id: JsonRpcIdSchema });
29
+ export const ProgressNotificationSchema = z.object({
30
+ token: z.string().min(1),
31
+ value: z.unknown(),
32
+ });
33
+ export function request(method, id, params) {
34
+ return { jsonrpc: JSONRPC_VERSION, id, method, params };
35
+ }
36
+ export function notification(method, params) {
37
+ return { jsonrpc: JSONRPC_VERSION, method, params };
38
+ }
39
+ export function response(id, result) {
40
+ return { jsonrpc: JSONRPC_VERSION, id, result };
41
+ }
42
+ export function errorResponse(id, error) {
43
+ return { jsonrpc: JSONRPC_VERSION, id, error };
44
+ }
45
+ export function encodeMessage(message) {
46
+ const line = `${JSON.stringify(message)}\n`;
47
+ const bytes = new TextEncoder().encode(line);
48
+ if (bytes.length > MAX_MESSAGE_BYTES) {
49
+ throw new Error(`message exceeds the ${MAX_MESSAGE_BYTES} byte protocol cap`);
50
+ }
51
+ return line;
52
+ }
53
+ export function decodeMessage(line) {
54
+ const bytes = new TextEncoder().encode(line);
55
+ if (bytes.length > MAX_MESSAGE_BYTES) {
56
+ throw new Error(`message exceeds the ${MAX_MESSAGE_BYTES} byte protocol cap`);
57
+ }
58
+ const parsed = JSON.parse(line);
59
+ const asRequest = JsonRpcRequestSchema.safeParse(parsed);
60
+ if (asRequest.success) {
61
+ return asRequest.data;
62
+ }
63
+ const asNotification = JsonRpcNotificationSchema.safeParse(parsed);
64
+ if (asNotification.success) {
65
+ return asNotification.data;
66
+ }
67
+ const asResponse = JsonRpcResponseSchema.safeParse(parsed);
68
+ if (asResponse.success) {
69
+ return asResponse.data;
70
+ }
71
+ throw new Error('message is not a JSON-RPC 2.0 request, notification or response');
72
+ }
@@ -0,0 +1,67 @@
1
+ import { z } from 'zod';
2
+ export declare const AddonErrorReasonSchema: z.ZodEnum<{
3
+ invalid_params: "invalid_params";
4
+ invalid_response: "invalid_response";
5
+ permission_denied: "permission_denied";
6
+ not_found: "not_found";
7
+ conflict: "conflict";
8
+ quota_exceeded: "quota_exceeded";
9
+ rate_limited: "rate_limited";
10
+ timeout: "timeout";
11
+ cancelled: "cancelled";
12
+ unavailable: "unavailable";
13
+ unsupported: "unsupported";
14
+ account_failed: "account_failed";
15
+ incompatible_handlers: "incompatible_handlers";
16
+ migration_failed: "migration_failed";
17
+ permission_revoked: "permission_revoked";
18
+ internal: "internal";
19
+ }>;
20
+ export type AddonErrorReason = z.infer<typeof AddonErrorReasonSchema>;
21
+ export interface AddonErrorData {
22
+ reason: AddonErrorReason;
23
+ retryable: boolean;
24
+ detail?: string;
25
+ accountCode?: string;
26
+ }
27
+ export declare const AddonErrorDataSchema: z.ZodObject<{
28
+ reason: z.ZodEnum<{
29
+ invalid_params: "invalid_params";
30
+ invalid_response: "invalid_response";
31
+ permission_denied: "permission_denied";
32
+ not_found: "not_found";
33
+ conflict: "conflict";
34
+ quota_exceeded: "quota_exceeded";
35
+ rate_limited: "rate_limited";
36
+ timeout: "timeout";
37
+ cancelled: "cancelled";
38
+ unavailable: "unavailable";
39
+ unsupported: "unsupported";
40
+ account_failed: "account_failed";
41
+ incompatible_handlers: "incompatible_handlers";
42
+ migration_failed: "migration_failed";
43
+ permission_revoked: "permission_revoked";
44
+ internal: "internal";
45
+ }>;
46
+ retryable: z.ZodBoolean;
47
+ detail: z.ZodOptional<z.ZodString>;
48
+ accountCode: z.ZodOptional<z.ZodString>;
49
+ }, z.core.$strip>;
50
+ export declare class AddonError extends Error {
51
+ readonly reason: AddonErrorReason;
52
+ readonly retryable: boolean;
53
+ readonly detail?: string;
54
+ readonly accountCode?: string;
55
+ constructor(reason: AddonErrorReason, options?: {
56
+ retryable?: boolean;
57
+ detail?: string;
58
+ accountCode?: string;
59
+ });
60
+ toData(): AddonErrorData;
61
+ }
62
+ /**
63
+ * Copy-safe detection: the addon dist bundles its own copy of this module, so
64
+ * in-process hosts see errors whose class identity differs from the host's
65
+ * `AddonError`. Detect structurally instead of by `instanceof` alone.
66
+ */
67
+ export declare function isAddonError(error: unknown): error is AddonError;