@harnesys/sdk 0.0.0-stage → 1.0.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 (144) 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.d.ts +36 -0
  20. package/dist/families/json-schema.js +101 -0
  21. package/dist/families/lsp.d.ts +18 -0
  22. package/dist/families/lsp.js +18 -0
  23. package/dist/families/mcp.d.ts +18 -0
  24. package/dist/families/mcp.js +18 -0
  25. package/dist/families/registry.d.ts +9 -0
  26. package/dist/families/registry.js +34 -0
  27. package/dist/families/route.d.ts +38 -0
  28. package/dist/families/route.js +37 -0
  29. package/dist/families/source-kind.d.ts +24 -0
  30. package/dist/families/source-kind.js +21 -0
  31. package/dist/families/tool-pack.d.ts +68 -0
  32. package/dist/families/tool-pack.js +57 -0
  33. package/dist/families/transport.d.ts +52 -0
  34. package/dist/families/transport.js +29 -0
  35. package/dist/families/trigger.d.ts +97 -0
  36. package/dist/families/trigger.js +46 -0
  37. package/dist/families/view.d.ts +255 -0
  38. package/dist/families/view.js +87 -0
  39. package/dist/families/viewer.d.ts +31 -0
  40. package/dist/families/viewer.js +26 -0
  41. package/dist/families/worker.d.ts +23 -0
  42. package/dist/families/worker.js +19 -0
  43. package/dist/host-client.d.ts +11 -0
  44. package/dist/host-client.js +30 -0
  45. package/dist/index.d.ts +35 -0
  46. package/dist/index.js +35 -0
  47. package/dist/manifest/branding.d.ts +14 -0
  48. package/dist/manifest/branding.js +18 -0
  49. package/dist/manifest/connections.d.ts +21 -0
  50. package/dist/manifest/connections.js +10 -0
  51. package/dist/manifest/json-schema.d.ts +2 -0
  52. package/dist/manifest/json-schema.js +13 -0
  53. package/dist/manifest/l10n.d.ts +9 -0
  54. package/dist/manifest/l10n.js +28 -0
  55. package/dist/manifest/manifest.d.ts +112 -0
  56. package/dist/manifest/manifest.js +45 -0
  57. package/dist/manifest/validate.d.ts +14 -0
  58. package/dist/manifest/validate.js +144 -0
  59. package/dist/permissions/permissions.d.ts +31 -0
  60. package/dist/permissions/permissions.js +53 -0
  61. package/dist/process-entry.d.ts +26 -0
  62. package/dist/process-entry.js +146 -0
  63. package/dist/protocol/envelope.d.ts +115 -0
  64. package/dist/protocol/envelope.js +72 -0
  65. package/dist/protocol/error.d.ts +67 -0
  66. package/dist/protocol/error.js +61 -0
  67. package/dist/protocol/handshake.d.ts +55 -0
  68. package/dist/protocol/handshake.js +26 -0
  69. package/dist/protocol/map.d.ts +1090 -0
  70. package/dist/protocol/map.js +127 -0
  71. package/dist/protocol/meta.d.ts +31 -0
  72. package/dist/protocol/meta.js +14 -0
  73. package/dist/protocol/method-spec.d.ts +13 -0
  74. package/dist/protocol/method-spec.js +9 -0
  75. package/dist/protocol/org-service-methods.d.ts +135 -0
  76. package/dist/protocol/org-service-methods.js +106 -0
  77. package/dist/protocol/shared.d.ts +389 -0
  78. package/dist/protocol/shared.js +231 -0
  79. package/dist/protocol/source-methods.d.ts +218 -0
  80. package/dist/protocol/source-methods.js +18 -0
  81. package/dist/protocol/thread-service-methods.d.ts +50 -0
  82. package/dist/protocol/thread-service-methods.js +32 -0
  83. package/dist/runtime.d.ts +25 -0
  84. package/dist/runtime.js +229 -0
  85. package/dist/testing/fake-db.d.ts +15 -0
  86. package/dist/testing/fake-db.js +120 -0
  87. package/dist/testing/fake-files.d.ts +9 -0
  88. package/dist/testing/fake-files.js +87 -0
  89. package/dist/testing/fake-host.d.ts +115 -0
  90. package/dist/testing/fake-host.js +152 -0
  91. package/dist/testing/fake-services.d.ts +63 -0
  92. package/dist/testing/fake-services.js +277 -0
  93. package/dist/testing/fixtures.d.ts +4 -0
  94. package/dist/testing/fixtures.js +84 -0
  95. package/dist/testing/index.d.ts +4 -0
  96. package/dist/testing/index.js +2 -0
  97. package/package.json +66 -4
  98. package/src/addon-context-factory.ts +236 -0
  99. package/src/addon-context.ts +313 -0
  100. package/src/define-addon.ts +178 -0
  101. package/src/families/config.ts +24 -0
  102. package/src/families/content.ts +35 -0
  103. package/src/families/field-spec.ts +175 -0
  104. package/src/families/hook.ts +34 -0
  105. package/src/families/job.ts +41 -0
  106. package/src/families/json-schema.ts +167 -0
  107. package/src/families/lsp.ts +28 -0
  108. package/src/families/mcp.ts +28 -0
  109. package/src/families/registry.ts +44 -0
  110. package/src/families/route.ts +52 -0
  111. package/src/families/source-kind.ts +34 -0
  112. package/src/families/tool-pack.ts +92 -0
  113. package/src/families/transport.ts +52 -0
  114. package/src/families/trigger.ts +92 -0
  115. package/src/families/view.ts +144 -0
  116. package/src/families/viewer.ts +43 -0
  117. package/src/families/worker.ts +30 -0
  118. package/src/host-client.ts +52 -0
  119. package/src/index.ts +341 -0
  120. package/src/manifest/branding.ts +24 -0
  121. package/src/manifest/connections.ts +21 -0
  122. package/src/manifest/json-schema.ts +24 -0
  123. package/src/manifest/l10n.ts +39 -0
  124. package/src/manifest/manifest.ts +94 -0
  125. package/src/manifest/validate.ts +200 -0
  126. package/src/permissions/permissions.ts +79 -0
  127. package/src/process-entry.ts +205 -0
  128. package/src/protocol/envelope.ts +126 -0
  129. package/src/protocol/error.ts +81 -0
  130. package/src/protocol/handshake.ts +43 -0
  131. package/src/protocol/map.ts +339 -0
  132. package/src/protocol/meta.ts +26 -0
  133. package/src/protocol/method-spec.ts +40 -0
  134. package/src/protocol/org-service-methods.ts +148 -0
  135. package/src/protocol/shared.ts +345 -0
  136. package/src/protocol/source-methods.ts +61 -0
  137. package/src/protocol/thread-service-methods.ts +50 -0
  138. package/src/runtime.ts +332 -0
  139. package/src/testing/fake-db.ts +140 -0
  140. package/src/testing/fake-files.ts +114 -0
  141. package/src/testing/fake-host.ts +261 -0
  142. package/src/testing/fake-services.ts +345 -0
  143. package/src/testing/fixtures.ts +88 -0
  144. package/src/testing/index.ts +12 -0
@@ -0,0 +1,120 @@
1
+ const loadDatabase = () => {
2
+ // bun:sqlite must not be evaluated in browser bundles — resolved lazily.
3
+ const mod = require('bun:sqlite');
4
+ return mod.Database;
5
+ };
6
+ const FORBIDDEN_SQL = [/\battach\b/i, /\bdetach\b/i, /\bload_extension\s*\(/i];
7
+ const ALLOWED_PRAGMAS = ['user_version', 'foreign_keys'];
8
+ export class SqlAuthorizerError extends Error {
9
+ reason = 'permission_denied';
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'SqlAuthorizerError';
13
+ }
14
+ }
15
+ export function guardSql(sql) {
16
+ for (const pattern of FORBIDDEN_SQL) {
17
+ if (pattern.test(sql)) {
18
+ throw new SqlAuthorizerError(`sql statement is not allowed: ${pattern.source}`);
19
+ }
20
+ }
21
+ for (const statement of splitStatements(sql)) {
22
+ assertStatementAllowed(statement);
23
+ }
24
+ }
25
+ // Mirrors apps/server/src/app/infra/addons/storage/sql-guard.ts: the fake and the
26
+ // real host must accept and reject identical statements.
27
+ function assertStatementAllowed(statement) {
28
+ const match = /^\s*pragma\s+([a-zA-Z_]+)\s*(=\s*(.+))?$/i.exec(statement);
29
+ if (!match) {
30
+ return;
31
+ }
32
+ const name = (match[1] ?? '').toLowerCase();
33
+ if ((match[3] ?? null) !== null) {
34
+ throw new SqlAuthorizerError(`pragma writes are not allowed: ${statement.trim()}`);
35
+ }
36
+ if (!ALLOWED_PRAGMAS.includes(name)) {
37
+ throw new SqlAuthorizerError(`pragma is not allowed: ${statement.trim()}`);
38
+ }
39
+ }
40
+ function splitStatements(sql) {
41
+ const statements = [];
42
+ let current = '';
43
+ let index = 0;
44
+ while (index < sql.length) {
45
+ const char = sql[index] ?? '';
46
+ if (char === "'" || char === '"' || char === '`') {
47
+ const end = quotedEnd(sql, index);
48
+ current += sql.slice(index, end);
49
+ index = end;
50
+ continue;
51
+ }
52
+ if (char === ';') {
53
+ statements.push(current);
54
+ current = '';
55
+ }
56
+ else {
57
+ current += char;
58
+ }
59
+ index += 1;
60
+ }
61
+ if (current.trim().length > 0) {
62
+ statements.push(current);
63
+ }
64
+ return statements.length > 0 ? statements : [sql];
65
+ }
66
+ // Returns the index just past the closing quote of a quoted run starting at `start`.
67
+ function quotedEnd(sql, start) {
68
+ const quote = sql[start];
69
+ let index = start + 1;
70
+ while (index < sql.length) {
71
+ const char = sql[index];
72
+ if (char !== quote) {
73
+ index += 1;
74
+ continue;
75
+ }
76
+ if (sql[index + 1] === quote) {
77
+ index += 2;
78
+ continue;
79
+ }
80
+ return index + 1;
81
+ }
82
+ return sql.length;
83
+ }
84
+ export function createFakeDb() {
85
+ const db = new (loadDatabase())(':memory:');
86
+ db.run('pragma foreign_keys = on');
87
+ return {
88
+ exec(sql) {
89
+ guardSql(sql);
90
+ db.run(sql);
91
+ },
92
+ all(sql, params) {
93
+ guardSql(sql);
94
+ return db.prepare(sql).all(...(params ?? []));
95
+ },
96
+ get(sql, params) {
97
+ guardSql(sql);
98
+ return (db.prepare(sql).get(...(params ?? [])) ?? null);
99
+ },
100
+ run(sql, params) {
101
+ guardSql(sql);
102
+ const result = db.run(sql, params ?? []);
103
+ return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
104
+ },
105
+ batch(statements) {
106
+ const apply = () => statements.map((statement) => {
107
+ guardSql(statement.sql);
108
+ const result = db.run(statement.sql, statement.params ?? []);
109
+ return {
110
+ changes: Number(result.changes),
111
+ lastInsertRowid: Number(result.lastInsertRowid),
112
+ };
113
+ });
114
+ return db.transaction(apply)();
115
+ },
116
+ close() {
117
+ db.close();
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,9 @@
1
+ import type { FakeHostOptions } from './fake-host.ts';
2
+ export interface FakeFilesContext {
3
+ options: FakeHostOptions;
4
+ writes: Array<{
5
+ path: string;
6
+ size: number;
7
+ }>;
8
+ }
9
+ export declare function executeFilesService(method: string, params: Record<string, unknown>, context: FakeFilesContext): unknown;
@@ -0,0 +1,87 @@
1
+ import { AddonError } from "../protocol/error.js";
2
+ const MAX_CHUNK_BYTES = 4 * 1024 * 1024;
3
+ const MEDIA_TYPES = {
4
+ png: 'image/png',
5
+ jpg: 'image/jpeg',
6
+ jpeg: 'image/jpeg',
7
+ gif: 'image/gif',
8
+ webp: 'image/webp',
9
+ pdf: 'application/pdf',
10
+ json: 'application/json',
11
+ txt: 'text/plain',
12
+ md: 'text/markdown',
13
+ csv: 'text/csv',
14
+ mp4: 'video/mp4',
15
+ mov: 'video/quicktime',
16
+ webm: 'video/webm',
17
+ };
18
+ export function executeFilesService(method, params, context) {
19
+ const store = context.options.files ?? {};
20
+ const path = normalizePath(String(params.path));
21
+ if (method === 'files.write') {
22
+ return writeFile(store, path, params, context.writes);
23
+ }
24
+ const stored = store[path];
25
+ if (stored === undefined) {
26
+ throw new AddonError('not_found', { detail: `no such file: ${path}` });
27
+ }
28
+ if (method === 'files.stat') {
29
+ return statOf(path, stored, context);
30
+ }
31
+ return readChunk(path, stored, params);
32
+ }
33
+ function writeFile(store, path, params, writes) {
34
+ const data = decode(String(params.data));
35
+ if (data.byteLength > MAX_CHUNK_BYTES) {
36
+ throw new AddonError('invalid_params', {
37
+ detail: `write chunk exceeds ${MAX_CHUNK_BYTES} bytes`,
38
+ });
39
+ }
40
+ const previous = params.append === true && store[path] !== undefined ? decode(store[path]) : Buffer.alloc(0);
41
+ const next = Buffer.concat([previous, data]);
42
+ store[path] = next.toString('base64');
43
+ writes.push({ path, size: next.byteLength });
44
+ return { path, size: next.byteLength };
45
+ }
46
+ function statOf(path, stored, context) {
47
+ const bytes = decode(stored);
48
+ return {
49
+ path,
50
+ name: path.split('/').at(-1) ?? path,
51
+ size: bytes.byteLength,
52
+ mediaType: mediaTypeOf(path),
53
+ modifiedAt: new Date(context.options.now?.() ?? 0).toISOString(),
54
+ };
55
+ }
56
+ function readChunk(path, stored, params) {
57
+ const bytes = decode(stored);
58
+ const offset = Number(params.offset ?? 0);
59
+ const requested = Math.min(Number(params.length ?? MAX_CHUNK_BYTES), MAX_CHUNK_BYTES);
60
+ const length = Math.max(0, Math.min(requested, bytes.byteLength - offset));
61
+ const chunk = bytes.subarray(offset, offset + length);
62
+ return {
63
+ data: chunk.toString('base64'),
64
+ eof: offset + length >= bytes.byteLength,
65
+ size: bytes.byteLength,
66
+ mediaType: mediaTypeOf(path),
67
+ };
68
+ }
69
+ function normalizePath(raw) {
70
+ const normalized = raw.replace(/\\/g, '/').replace(/^\.\//, '');
71
+ const segments = normalized.split('/');
72
+ if (normalized.startsWith('/') ||
73
+ segments.some((segment) => segment === '..' || segment === '')) {
74
+ throw new AddonError('invalid_params', { detail: `invalid file path: ${raw}` });
75
+ }
76
+ return normalized;
77
+ }
78
+ function mediaTypeOf(path) {
79
+ const extension = path.includes('.') ? path.split('.').at(-1)?.toLowerCase() : undefined;
80
+ if (extension === undefined) {
81
+ return 'application/octet-stream';
82
+ }
83
+ return MEDIA_TYPES[extension] ?? 'application/octet-stream';
84
+ }
85
+ function decode(base64) {
86
+ return base64 === '' ? Buffer.alloc(0) : Buffer.from(base64, 'base64');
87
+ }
@@ -0,0 +1,115 @@
1
+ import type { ResolvedAddonDefinition } from '../define-addon.ts';
2
+ import type { AddonManifest } from '../manifest/manifest.ts';
3
+ export interface FakeAccount {
4
+ connection: string;
5
+ accountId: string;
6
+ label?: string;
7
+ externalAccountId?: string;
8
+ status?: string;
9
+ credentials?: unknown;
10
+ expiresAt?: string;
11
+ }
12
+ export interface FakeHttpRequest {
13
+ url: string;
14
+ method: string;
15
+ headers: Record<string, string>;
16
+ body?: string;
17
+ auth?: unknown;
18
+ }
19
+ export interface FakeHttpResponse {
20
+ status: number;
21
+ headers?: Record<string, string>;
22
+ body?: string;
23
+ }
24
+ export type FakeHttpHandler = (request: FakeHttpRequest) => FakeHttpResponse | Promise<FakeHttpResponse>;
25
+ export interface FakeGrant {
26
+ id: string;
27
+ scope?: Record<string, unknown>;
28
+ }
29
+ export interface FakeHostOptions {
30
+ definition: ResolvedAddonDefinition;
31
+ manifest: AddonManifest;
32
+ config?: Record<string, unknown>;
33
+ secrets?: Record<string, string>;
34
+ accounts?: FakeAccount[];
35
+ http?: FakeHttpHandler;
36
+ files?: Record<string, string>;
37
+ grants?: FakeGrant[];
38
+ now?(): number;
39
+ }
40
+ export interface FakeHost {
41
+ readonly manifest: AddonManifest;
42
+ logs: Array<{
43
+ level: string;
44
+ message: string;
45
+ fields?: Record<string, unknown>;
46
+ }>;
47
+ emitted: Array<{
48
+ name: string;
49
+ payload: unknown;
50
+ }>;
51
+ dispatchedRuns: Array<{
52
+ threadId?: string;
53
+ agentId?: string;
54
+ input: string;
55
+ }>;
56
+ cancelledRuns: Array<{
57
+ threadId: string;
58
+ runId: string;
59
+ }>;
60
+ createdThreads: string[];
61
+ patchedThreads: Array<{
62
+ threadId: string;
63
+ responderMode?: 'auto' | 'mention';
64
+ }>;
65
+ accountReports: Array<{
66
+ connection: string;
67
+ accountId?: string;
68
+ code: string;
69
+ }>;
70
+ workerReports: Array<{
71
+ workerId: string;
72
+ state: string;
73
+ code?: string;
74
+ }>;
75
+ inboundMessages: Array<{
76
+ channel: string;
77
+ from?: string;
78
+ text: string;
79
+ payload?: unknown;
80
+ }>;
81
+ fileWrites: Array<{
82
+ path: string;
83
+ size: number;
84
+ }>;
85
+ createdTriggerInstances: Array<Record<string, unknown>>;
86
+ files: Record<string, string>;
87
+ progress: Array<{
88
+ token: string;
89
+ value: unknown;
90
+ }>;
91
+ now(): number;
92
+ advanceTime(ms: number): void;
93
+ callTool(pack: string, tool: string, input?: Record<string, unknown>): Promise<{
94
+ output: unknown;
95
+ }>;
96
+ callRoute(routeId: string, request: {
97
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
98
+ path?: string;
99
+ query?: Record<string, string>;
100
+ body?: unknown;
101
+ }): Promise<{
102
+ status: number;
103
+ body?: unknown;
104
+ }>;
105
+ runJob(jobId: string): Promise<void>;
106
+ startTrigger(instanceId: string, kind: string, config?: Record<string, unknown>, target?: unknown): Promise<void>;
107
+ stopTrigger(instanceId: string): Promise<void>;
108
+ startWorker(workerId: string): Promise<void>;
109
+ emit(event: Record<string, unknown>, hookId: string): Promise<void>;
110
+ notify(method: string, params: unknown): Promise<void>;
111
+ deliver(method: string, params: unknown): Promise<unknown>;
112
+ service(method: string, params: unknown): Promise<unknown>;
113
+ close(): void;
114
+ }
115
+ export declare function createFakeHost(options: FakeHostOptions): FakeHost;
@@ -0,0 +1,152 @@
1
+ import { AddonError } from "../protocol/error.js";
2
+ import { methodSpec } from "../protocol/map.js";
3
+ import { createAddonRuntime } from "../runtime.js";
4
+ import { createFakeDb } from "./fake-db.js";
5
+ import { createFakeServices } from "./fake-services.js";
6
+ export function createFakeHost(options) {
7
+ const { definition, manifest } = options;
8
+ let clockOffset = 0;
9
+ let correlation = 0;
10
+ const base = options.now ?? (() => Date.now());
11
+ const now = () => base() + clockOffset;
12
+ const db = createFakeDb();
13
+ const startedTriggers = new Set();
14
+ const firedKeys = new Set();
15
+ const progress = [];
16
+ const sinks = {
17
+ logs: [],
18
+ emitted: [],
19
+ dispatchedRuns: [],
20
+ cancelledRuns: [],
21
+ createdThreads: [],
22
+ patchedThreads: [],
23
+ accountReports: [],
24
+ workerReports: [],
25
+ inboundMessages: [],
26
+ fileWrites: [],
27
+ createdTriggerInstances: [],
28
+ };
29
+ const files = options.files ?? {};
30
+ const services = createFakeServices({
31
+ manifest,
32
+ options: { ...options, files },
33
+ db,
34
+ sinks,
35
+ startedTriggers,
36
+ firedKeys,
37
+ });
38
+ const fakeChannel = {
39
+ request(method, params) {
40
+ return dispatchAddonToHost(method, params);
41
+ },
42
+ notify(method, params) {
43
+ if (method === '$/progress') {
44
+ progress.push(params);
45
+ }
46
+ },
47
+ };
48
+ const runtime = createAddonRuntime({
49
+ definition,
50
+ addon: { id: manifest.id, version: manifest.version },
51
+ channel: fakeChannel,
52
+ });
53
+ const host = {
54
+ manifest,
55
+ logs: sinks.logs,
56
+ emitted: sinks.emitted,
57
+ dispatchedRuns: sinks.dispatchedRuns,
58
+ cancelledRuns: sinks.cancelledRuns,
59
+ createdThreads: sinks.createdThreads,
60
+ patchedThreads: sinks.patchedThreads,
61
+ accountReports: sinks.accountReports,
62
+ workerReports: sinks.workerReports,
63
+ inboundMessages: sinks.inboundMessages,
64
+ fileWrites: sinks.fileWrites,
65
+ createdTriggerInstances: sinks.createdTriggerInstances,
66
+ files,
67
+ progress,
68
+ now,
69
+ advanceTime(ms) {
70
+ clockOffset += ms;
71
+ },
72
+ async callTool(pack, tool, input = {}) {
73
+ const result = (await deliver('tools.call', { pack, tool, input }));
74
+ return { output: result.output };
75
+ },
76
+ async callRoute(routeId, request) {
77
+ const result = (await deliver('route.handle', {
78
+ routeId,
79
+ request: {
80
+ method: request.method ?? 'GET',
81
+ path: request.path ?? '/',
82
+ query: request.query ?? {},
83
+ headers: {},
84
+ body: request.body,
85
+ },
86
+ }));
87
+ return { status: result.status, body: result.body };
88
+ },
89
+ async runJob(jobId) {
90
+ await deliver('job.run', { jobId });
91
+ },
92
+ async startTrigger(instanceId, kind, config = {}, target) {
93
+ await deliver('trigger.start', { instanceId, kind, config, target });
94
+ startedTriggers.add(instanceId);
95
+ },
96
+ async stopTrigger(instanceId) {
97
+ startedTriggers.delete(instanceId);
98
+ await deliver('trigger.stop', { instanceId });
99
+ },
100
+ async startWorker(workerId) {
101
+ await deliver('worker.start', { workerId });
102
+ },
103
+ async emit(event, hookId) {
104
+ await deliver('hook.deliver', { hookId, event });
105
+ },
106
+ async notify(method, params) {
107
+ await runtime.handleNotification(method, params, new AbortController().signal);
108
+ },
109
+ async deliver(method, params) {
110
+ return deliver(method, params);
111
+ },
112
+ async service(method, params) {
113
+ return dispatchAddonToHost(method, params);
114
+ },
115
+ close() {
116
+ db.close();
117
+ },
118
+ };
119
+ function deliver(method, params) {
120
+ correlation += 1;
121
+ const meta = {
122
+ correlationId: `fake-${correlation}`,
123
+ deadline: base() + 5000,
124
+ principal: { type: 'system' },
125
+ locale: 'en',
126
+ };
127
+ const controller = new AbortController();
128
+ const withMeta = method === 'initialize' ? params : { ...params, _meta: meta };
129
+ return runtime.handleRequest(method, withMeta, controller.signal);
130
+ }
131
+ async function dispatchAddonToHost(method, rawParams) {
132
+ const spec = methodSpec(method);
133
+ if (spec?.direction !== 'addon-to-host') {
134
+ throw new AddonError('unsupported', {
135
+ detail: `method '${method}' is not an addon-to-host service`,
136
+ });
137
+ }
138
+ await checkPermission(spec.permission);
139
+ const params = spec.params.parse(rawParams);
140
+ const result = await services.execute(method, params);
141
+ return spec.result ? spec.result.parse(result) : result;
142
+ }
143
+ function checkPermission(permission) {
144
+ if (permission === null || services.hasGrant(permission)) {
145
+ return;
146
+ }
147
+ throw new AddonError('permission_denied', {
148
+ detail: `permission '${permission}' was not granted`,
149
+ });
150
+ }
151
+ return host;
152
+ }
@@ -0,0 +1,63 @@
1
+ import type { AddonManifest } from '../manifest/manifest.ts';
2
+ import type { FakeDb } from './fake-db.ts';
3
+ import type { FakeHostOptions } from './fake-host.ts';
4
+ export interface FakeServiceSinks {
5
+ logs: Array<{
6
+ level: string;
7
+ message: string;
8
+ fields?: Record<string, unknown>;
9
+ }>;
10
+ emitted: Array<{
11
+ name: string;
12
+ payload: unknown;
13
+ }>;
14
+ dispatchedRuns: Array<{
15
+ threadId?: string;
16
+ agentId?: string;
17
+ input: string;
18
+ }>;
19
+ cancelledRuns: Array<{
20
+ threadId: string;
21
+ runId: string;
22
+ }>;
23
+ createdThreads: string[];
24
+ patchedThreads: Array<{
25
+ threadId: string;
26
+ responderMode?: 'auto' | 'mention';
27
+ }>;
28
+ accountReports: Array<{
29
+ connection: string;
30
+ accountId?: string;
31
+ code: string;
32
+ }>;
33
+ fileWrites: Array<{
34
+ path: string;
35
+ size: number;
36
+ }>;
37
+ workerReports: Array<{
38
+ workerId: string;
39
+ state: string;
40
+ code?: string;
41
+ }>;
42
+ inboundMessages: Array<{
43
+ channel: string;
44
+ from?: string;
45
+ text: string;
46
+ payload?: unknown;
47
+ }>;
48
+ createdTriggerInstances: Array<Record<string, unknown>>;
49
+ }
50
+ export interface FakeServiceContext {
51
+ manifest: AddonManifest;
52
+ options: FakeHostOptions;
53
+ db: FakeDb;
54
+ sinks: FakeServiceSinks;
55
+ startedTriggers: Set<string>;
56
+ firedKeys: Set<string>;
57
+ }
58
+ type ServiceParams = Record<string, unknown>;
59
+ export declare function createFakeServices(context: FakeServiceContext): {
60
+ execute(method: string, params: ServiceParams): Promise<unknown>;
61
+ hasGrant(permission: string): boolean;
62
+ };
63
+ export {};