@histoire/devframe 0.0.0-stage → 1.0.0-beta.2

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/dist/client/attach.d.ts +15 -0
  4. package/dist/client/attach.d.ts.map +1 -0
  5. package/dist/client/attach.js +238 -0
  6. package/dist/client/diagnostics.d.ts +14 -0
  7. package/dist/client/diagnostics.d.ts.map +1 -0
  8. package/dist/client/diagnostics.js +31 -0
  9. package/dist/client/events.d.ts +11 -0
  10. package/dist/client/events.d.ts.map +1 -0
  11. package/dist/client/events.js +52 -0
  12. package/dist/client/highlight-operations.d.ts +14 -0
  13. package/dist/client/highlight-operations.d.ts.map +1 -0
  14. package/dist/client/highlight-operations.js +74 -0
  15. package/dist/client/index.d.ts +3 -0
  16. package/dist/client/index.d.ts.map +1 -0
  17. package/dist/client/index.js +2 -0
  18. package/dist/client/inspection.d.ts +9 -0
  19. package/dist/client/inspection.d.ts.map +1 -0
  20. package/dist/client/inspection.js +32 -0
  21. package/dist/client/pairing-budget.d.ts +3 -0
  22. package/dist/client/pairing-budget.d.ts.map +1 -0
  23. package/dist/client/pairing-budget.js +36 -0
  24. package/dist/host/index.d.ts +35 -0
  25. package/dist/host/index.d.ts.map +1 -0
  26. package/dist/host/index.js +86 -0
  27. package/dist/node/broker.d.ts +37 -0
  28. package/dist/node/broker.d.ts.map +1 -0
  29. package/dist/node/broker.js +349 -0
  30. package/dist/node/devframe.d.ts +64 -0
  31. package/dist/node/devframe.d.ts.map +1 -0
  32. package/dist/node/devframe.js +193 -0
  33. package/dist/node/grants.d.ts +24 -0
  34. package/dist/node/grants.d.ts.map +1 -0
  35. package/dist/node/grants.js +58 -0
  36. package/dist/node/index.d.ts +8 -0
  37. package/dist/node/index.d.ts.map +1 -0
  38. package/dist/node/index.js +4 -0
  39. package/dist/node/mcp.d.ts +10 -0
  40. package/dist/node/mcp.d.ts.map +1 -0
  41. package/dist/node/mcp.js +150 -0
  42. package/dist/node/retirements.d.ts +8 -0
  43. package/dist/node/retirements.d.ts.map +1 -0
  44. package/dist/node/retirements.js +34 -0
  45. package/dist/node/rpc-budget.d.ts +6 -0
  46. package/dist/node/rpc-budget.d.ts.map +1 -0
  47. package/dist/node/rpc-budget.js +26 -0
  48. package/dist/node/types.d.ts +65 -0
  49. package/dist/node/types.d.ts.map +1 -0
  50. package/dist/node/types.js +1 -0
  51. package/dist/node/validation.d.ts +10 -0
  52. package/dist/node/validation.d.ts.map +1 -0
  53. package/dist/node/validation.js +50 -0
  54. package/dist/report/content.d.ts +33 -0
  55. package/dist/report/content.d.ts.map +1 -0
  56. package/dist/report/content.js +64 -0
  57. package/dist/report/index.d.ts +60 -0
  58. package/dist/report/index.d.ts.map +1 -0
  59. package/dist/report/index.js +78 -0
  60. package/dist/shared/diagnostics.d.ts +9 -0
  61. package/dist/shared/diagnostics.d.ts.map +1 -0
  62. package/dist/shared/diagnostics.js +20 -0
  63. package/dist/shared/events.d.ts +27 -0
  64. package/dist/shared/events.d.ts.map +1 -0
  65. package/dist/shared/events.js +49 -0
  66. package/dist/shared/services.d.ts +413 -0
  67. package/dist/shared/services.d.ts.map +1 -0
  68. package/dist/shared/services.js +113 -0
  69. package/package.json +53 -3
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { defineDevframe } from 'devframe';
3
+ import { createLiveBroker } from './broker.js';
4
+ import { createRpcBudget } from './rpc-budget.js';
5
+ /** Create an inert Devframe definition; host owns installation and disconnect hooks. */
6
+ export function createDevframeBridge(options) {
7
+ const id = options.id ?? 'histoire';
8
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(id))
9
+ throw new Error('Invalid adapter namespace');
10
+ const peers = new Map();
11
+ const owned = new Set();
12
+ const calls = createRpcBudget(64);
13
+ const retirements = createRpcBudget(64);
14
+ let closed = false;
15
+ let closing;
16
+ const broker = createLiveBroker({
17
+ leaseMs: options.leaseMs,
18
+ timeoutMs: options.timeoutMs,
19
+ identifyPeer: peer => options.identifyPeer(peer.session),
20
+ verifyAttachment: (peer, identity, url) => options.verifyAttachment(peer.session, identity, url),
21
+ isCurrent: (peer, identity) => options.isCurrent(peer.session, identity),
22
+ authorityVersion: options.authorityVersion,
23
+ onRetire(peer, attachmentId) {
24
+ const group = peers.get(peer.session.meta.id);
25
+ if (group?.get(attachmentId) === peer)
26
+ group.delete(attachmentId);
27
+ if (group && !group.size && peers.get(peer.session.meta.id) === group)
28
+ peers.delete(peer.session.meta.id);
29
+ },
30
+ allowSource: options.allowSource,
31
+ authorize: options.authorize,
32
+ });
33
+ const definition = defineDevframe({
34
+ id,
35
+ name: 'Histoire',
36
+ version: '1',
37
+ packageName: '@histoire/devframe',
38
+ homepage: 'https://histoire.dev',
39
+ description: 'Explicitly paired mounted story inspection',
40
+ setup(ctx) {
41
+ if (closed)
42
+ throw new Error('Adapter disposed');
43
+ /** Capture transport session synchronously before any asynchronous work. */
44
+ function current() {
45
+ const session = ctx.rpc.getCurrentRpcSession();
46
+ if (!session)
47
+ throw new Error('Session unavailable');
48
+ return session;
49
+ }
50
+ /** Invoke exactly this connection; abort sends matching operation cancellation. */
51
+ function createPeer(session, method) {
52
+ return { session, method, retire() {
53
+ const invoke = session.rpc.$call;
54
+ return retirements.call(() => invoke(method, { action: 'retire', operationId: randomUUID() }));
55
+ }, async callHighlight(name, input, signal) {
56
+ const operationId = randomUUID();
57
+ const invoke = session.rpc.$call;
58
+ const send = session.rpc.$callEvent;
59
+ const cancel = () => {
60
+ void send(method, { action: 'cancel', operationId }).catch(() => { });
61
+ };
62
+ signal.addEventListener('abort', cancel, { once: true });
63
+ try {
64
+ signal.throwIfAborted();
65
+ const value = await calls.call(() => invoke(method, { action: 'call', operationId, name, input }));
66
+ return { value, async finish(accepted) {
67
+ signal.removeEventListener('abort', cancel);
68
+ if (accepted) {
69
+ void send(method, { action: 'commit', operationId }).catch(() => { });
70
+ return;
71
+ }
72
+ await retirements.call(() => invoke(method, { action: 'cancel', operationId }));
73
+ } };
74
+ }
75
+ catch (error) {
76
+ signal.removeEventListener('abort', cancel);
77
+ throw error;
78
+ }
79
+ }, async call(name, input, signal) {
80
+ const operationId = randomUUID();
81
+ const invoke = session.rpc.$call;
82
+ const cancel = () => {
83
+ const send = session.rpc.$callEvent;
84
+ void send(method, { action: 'cancel', operationId }).catch(() => { });
85
+ };
86
+ signal.addEventListener('abort', cancel, { once: true });
87
+ try {
88
+ signal.throwIfAborted();
89
+ return await calls.call(() => invoke(method, { action: 'call', operationId, name, input }));
90
+ }
91
+ finally {
92
+ signal.removeEventListener('abort', cancel);
93
+ }
94
+ } };
95
+ }
96
+ /** Only delete definitions installed by this adapter instance. */
97
+ function register(name, handler) {
98
+ if (ctx.rpc.definitions.has(name))
99
+ throw new Error('Adapter RPC already registered');
100
+ ctx.rpc.register({ name, type: 'action', jsonSerializable: true, setup: () => ({ handler }) });
101
+ const definition = ctx.rpc.definitions.get(name);
102
+ owned.add(() => {
103
+ if (ctx.rpc.definitions.get(name) === definition) {
104
+ ctx.rpc.definitions.delete(name);
105
+ }
106
+ });
107
+ }
108
+ register(`${id}:pair`, async (input) => {
109
+ const session = current();
110
+ if (!input || typeof input.method !== 'string' || !new RegExp(`^${id}:attachment:[a-f0-9-]{36}$`).test(input.method))
111
+ throw new Error('Pairing unavailable');
112
+ const peer = createPeer(session, input.method);
113
+ const key = `pending:${randomUUID()}`;
114
+ const group = peers.get(session.meta.id) ?? new Map();
115
+ group.set(key, peer);
116
+ peers.set(session.meta.id, group);
117
+ try {
118
+ const attachment = await broker.attach(peer, { grant: input.grant, sourceUrl: input.sourceUrl, identity: input.identity, scopes: input.scopes });
119
+ if (closed || peers.get(session.meta.id) !== group || group.get(key) !== peer) {
120
+ broker.disconnect(peer);
121
+ throw new Error('Pairing unavailable');
122
+ }
123
+ group.set(attachment.attachmentId, peer);
124
+ return attachment;
125
+ }
126
+ finally {
127
+ group.delete(key);
128
+ if (!group.size && peers.get(session.meta.id) === group) {
129
+ peers.delete(session.meta.id);
130
+ }
131
+ }
132
+ });
133
+ register(`${id}:heartbeat`, async (attachmentId) => {
134
+ const session = current();
135
+ const peer = peers.get(session.meta.id)?.get(attachmentId);
136
+ if (!peer || peer.session.meta !== session.meta)
137
+ throw new Error('Session unavailable');
138
+ await broker.heartbeat(peer, attachmentId);
139
+ return null;
140
+ });
141
+ register(`${id}:detach`, (attachmentId) => {
142
+ const session = current();
143
+ const group = peers.get(session.meta.id);
144
+ const peer = group?.get(attachmentId);
145
+ if (peer?.session.meta === session.meta) {
146
+ broker.detach(peer, attachmentId);
147
+ group.delete(attachmentId);
148
+ if (!group.size) {
149
+ peers.delete(session.meta.id);
150
+ }
151
+ }
152
+ return null;
153
+ });
154
+ },
155
+ });
156
+ return {
157
+ definition,
158
+ broker,
159
+ /** Host-visible count of currently owned and pending transport attachments. */
160
+ getStatus() { return { attachments: [...peers.values()].reduce((count, group) => count + group.size, 0) }; },
161
+ /** Call synchronously after host authority changes; omit ID for global changes. */
162
+ invalidate(attachmentId) { broker.invalidate(attachmentId); },
163
+ /** Wire this hook to the caller-owned Devframe instance. */
164
+ onPeerDisconnect(meta) {
165
+ const group = peers.get(meta.id);
166
+ if (!group)
167
+ return;
168
+ for (const [attachmentId, peer] of group) {
169
+ if (peer.session.meta === meta) {
170
+ broker.disconnect(peer);
171
+ group.delete(attachmentId);
172
+ }
173
+ }
174
+ if (!group.size)
175
+ peers.delete(meta.id);
176
+ },
177
+ /** Release only adapter registrations and never close the host connection. */
178
+ dispose() {
179
+ if (closing)
180
+ return closing;
181
+ const completion = Promise.withResolvers();
182
+ closing = completion.promise;
183
+ closed = true;
184
+ const draining = broker.dispose();
185
+ for (const cleanup of owned)
186
+ cleanup();
187
+ owned.clear();
188
+ peers.clear();
189
+ void draining.then(completion.resolve, completion.reject);
190
+ return closing;
191
+ },
192
+ };
193
+ }
@@ -0,0 +1,24 @@
1
+ import type { Exposure } from './types.js';
2
+ /** Canonical HTTP source without credentials, query or fragment. */
3
+ export declare function canonicalSource(input: string): string;
4
+ /** Bounded single-use grants retain secret hashes only. */
5
+ export declare function createGrants(): {
6
+ create(input: {
7
+ principal: string;
8
+ sourceUrl: string;
9
+ scopes: readonly Exposure[];
10
+ authorityVersion: number;
11
+ }): {
12
+ token: string;
13
+ expiresAt: number;
14
+ };
15
+ redeem(token: unknown, principal: string, sourceUrl: string, authorityVersion: number): {
16
+ principal: string;
17
+ sourceUrl: string;
18
+ scopes: Exposure[];
19
+ expiresAt: number;
20
+ authorityVersion: number;
21
+ };
22
+ clear(): void;
23
+ };
24
+ //# sourceMappingURL=grants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../../src/node/grants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAG1C,oEAAoE;AACpE,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAUrD;AAED,2DAA2D;AAC3D,wBAAgB,YAAY;kBAaV;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,SAAS,QAAQ,EAAE,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAA;KAAE;;;;kBAS/F,OAAO,aAAa,MAAM,aAAa,MAAM,oBAAoB,MAAM;mBArB1C,MAAM;mBAAa,MAAM;gBAAU,QAAQ,EAAE;mBAAa,MAAM;0BAAoB,MAAM;;;EAgCxI"}
@@ -0,0 +1,58 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ /** Canonical HTTP source without credentials, query or fragment. */
3
+ export function canonicalSource(input) {
4
+ if (typeof input !== 'string' || !input || input.length > 2048)
5
+ throw new Error('Invalid source');
6
+ let url;
7
+ try {
8
+ url = new URL(input);
9
+ }
10
+ catch {
11
+ throw new Error('Invalid source');
12
+ }
13
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
14
+ throw new Error('Invalid source');
15
+ if (!url.pathname.endsWith('/'))
16
+ url.pathname += '/';
17
+ return url.href;
18
+ }
19
+ /** Bounded single-use grants retain secret hashes only. */
20
+ export function createGrants() {
21
+ const entries = new Map();
22
+ /** Secrets never enter stored metadata or error messages. */
23
+ function hash(token) {
24
+ return createHash('sha256').update(token).digest('hex');
25
+ }
26
+ /** Expire abandoned grants before capacity checks or redemption. */
27
+ function prune() {
28
+ for (const [key, grant] of entries) {
29
+ if (grant.expiresAt <= Date.now())
30
+ entries.delete(key);
31
+ }
32
+ }
33
+ return {
34
+ create(input) {
35
+ prune();
36
+ if (entries.size >= 128)
37
+ throw new Error('Pairing capacity reached');
38
+ if (!input.principal || input.principal.length > 1024 || !Array.isArray(input.scopes) || input.scopes.length > 6 || new Set(input.scopes).size !== input.scopes.length || input.scopes.some(scope => !['inspection', 'events', 'diagnostics', 'components', 'accessibility', 'highlight'].includes(scope)))
39
+ throw new Error('Invalid grant');
40
+ const token = randomBytes(32).toString('base64url');
41
+ const expiresAt = Date.now() + 60_000;
42
+ entries.set(hash(token), { principal: input.principal, sourceUrl: canonicalSource(input.sourceUrl), scopes: [...input.scopes], expiresAt, authorityVersion: input.authorityVersion });
43
+ return { token, expiresAt };
44
+ },
45
+ redeem(token, principal, sourceUrl, authorityVersion) {
46
+ prune();
47
+ if (typeof token !== 'string' || token.length > 128)
48
+ throw new Error('Pairing unavailable');
49
+ const key = hash(token);
50
+ const grant = entries.get(key);
51
+ if (!grant || grant.principal !== principal || grant.sourceUrl !== sourceUrl || grant.authorityVersion !== authorityVersion)
52
+ throw new Error('Pairing unavailable');
53
+ entries.delete(key);
54
+ return grant;
55
+ },
56
+ clear() { entries.clear(); },
57
+ };
58
+ }
@@ -0,0 +1,8 @@
1
+ export { mountDevframeHost } from '../host/index.js';
2
+ export type { DevframeHost, DevframeHostOptions } from '../host/index.js';
3
+ /** Node entry defines optional factories; importing starts no listeners. */
4
+ export { createDevframeBridge } from './devframe.js';
5
+ export type { DevframeBridgeOptions } from './devframe.js';
6
+ export { createMcpEndpoint } from './mcp.js';
7
+ export type { Authorization, Exposure, LiveAttachment, LiveIdentity, LivePeer } from './types.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AACpD,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAA;AACzE,4EAA4E;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,YAAY,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAE1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAC5C,YAAY,EAAE,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA"}
@@ -0,0 +1,4 @@
1
+ export { mountDevframeHost } from '../host/index.js';
2
+ /** Node entry defines optional factories; importing starts no listeners. */
3
+ export { createDevframeBridge } from './devframe.js';
4
+ export { createMcpEndpoint } from './mcp.js';
@@ -0,0 +1,10 @@
1
+ import type { createLiveBroker } from './broker.js';
2
+ import type { LivePeer } from './types.js';
3
+ /** Optional fetch endpoint; host authenticates each request and owns its server. */
4
+ export declare function createMcpEndpoint<P extends LivePeer>(broker: ReturnType<typeof createLiveBroker<P>>, authenticate: (request: Request) => string | undefined | Promise<string | undefined>): {
5
+ /** Authentication precedes MCP parsing and cannot be supplied through tool arguments. */
6
+ fetch(request: Request): Promise<Response>;
7
+ /** Close this endpoint, preserving caller-owned broker and HTTP listener. */
8
+ close(): Promise<void>;
9
+ };
10
+ //# sourceMappingURL=mcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/node/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AACnD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAO1C,oFAAoF;AACpF,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IA+EtL,yFAAyF;IACnF,KAAK,UAAU,OAAO;IAkC5B,6EAA6E;IAC7E,KAAK;EAQR"}
@@ -0,0 +1,150 @@
1
+ import { measureWireValue, sameInspectionOwner, validateBridgeResult, validateInspectionInput, validateInspectionOwner, validateInspectionResult } from '@histoire/protocol';
2
+ import { createMcpHandler, Server } from '@modelcontextprotocol/server';
3
+ import { parseDiagnosticRequest } from '../shared/diagnostics.js';
4
+ import { parseEventRequest, validateEventPage } from '../shared/events.js';
5
+ import { componentKind, LIVE_SERVICES, LIVE_TOOLS } from '../shared/services.js';
6
+ /** Optional fetch endpoint; host authenticates each request and owns its server. */
7
+ export function createMcpEndpoint(broker, authenticate) {
8
+ let closed = false;
9
+ let active = 0;
10
+ let closing;
11
+ const authenticating = new Set();
12
+ const handler = createMcpHandler((context) => {
13
+ const principal = context.authInfo.clientId;
14
+ const server = new Server({ name: 'histoire-live', version: '1' }, { capabilities: { tools: {}, resources: {} } });
15
+ const { tool, eventTool, diagnosticTool, componentTool, accessibilityTool, highlightTool } = LIVE_TOOLS;
16
+ server.setRequestHandler('tools/list', async (_request, extra) => {
17
+ const attachments = await broker.list(principal, extra.mcpReq.signal, true);
18
+ extra.mcpReq.signal.throwIfAborted();
19
+ const scopes = new Set(attachments.flatMap(attachment => attachment.scopes));
20
+ return { tools: [tool, eventTool, diagnosticTool, componentTool, accessibilityTool, highlightTool].filter(item => scopes.has(LIVE_SERVICES[item.name].scope)) };
21
+ });
22
+ server.setRequestHandler('resources/list', async (_request, extra) => {
23
+ const resources = (await broker.list(principal, extra.mcpReq.signal)).map(record => ({ uri: `histoire://live/${record.attachmentId}`, name: 'Histoire live session', mimeType: 'application/json' }));
24
+ measureWireValue(resources, { maxBytes: 60 * 1024, maxDepth: 16 });
25
+ return { resources };
26
+ });
27
+ server.setRequestHandler('resources/read', async (request, extra) => {
28
+ const records = await broker.list(principal, extra.mcpReq.signal);
29
+ extra.mcpReq.signal.throwIfAborted();
30
+ const record = records.find(item => `histoire://live/${item.attachmentId}` === request.params.uri);
31
+ if (!record)
32
+ throw new Error('Session unavailable');
33
+ return { contents: [{ uri: request.params.uri, mimeType: 'application/json', text: JSON.stringify(record) }] };
34
+ });
35
+ server.setRequestHandler('tools/call', async (request, context) => {
36
+ try {
37
+ if (!Object.hasOwn(LIVE_SERVICES, request.params.name))
38
+ throw new Error('Invalid request');
39
+ const value = request.params.arguments;
40
+ measureWireValue(value, { maxBytes: 16 * 1024, maxDepth: 32 });
41
+ if (!value || typeof value !== 'object' || Array.isArray(value))
42
+ throw new Error('Invalid request');
43
+ const { attachmentId, ...input } = value;
44
+ if (typeof attachmentId !== 'string' || !attachmentId)
45
+ throw new Error('Invalid request');
46
+ if ((request.params.name === componentTool.name || request.params.name === accessibilityTool.name || request.params.name === highlightTool.name) && Object.hasOwn(input, 'kind'))
47
+ throw new Error('Invalid request');
48
+ const event = request.params.name === eventTool.name;
49
+ const diagnostic = request.params.name === diagnosticTool.name;
50
+ const kind = request.params.name === componentTool.name ? componentKind(input) : request.params.name === accessibilityTool.name ? 'accessibility' : request.params.name === highlightTool.name ? 'highlight' : input.kind;
51
+ if (request.params.name === tool.name && kind !== 'variant' && kind !== 'dom')
52
+ throw new Error('Invalid request');
53
+ let owner;
54
+ const eventRequest = event ? parseEventRequest(input) : undefined;
55
+ if (eventRequest) {
56
+ owner = eventRequest.expectedOwner;
57
+ }
58
+ else if (diagnostic) {
59
+ owner = parseDiagnosticRequest(input).expectedOwner;
60
+ }
61
+ else {
62
+ const { kind: _kind, ...options } = input;
63
+ if (typeof kind !== 'string')
64
+ throw new Error('Invalid request');
65
+ validateInspectionInput(kind, options);
66
+ owner = validateInspectionOwner(options.expectedOwner);
67
+ if (!options.target || options.target.storyId !== owner.target.storyId || options.target.variantId !== owner.target.variantId)
68
+ throw new Error('Invalid request');
69
+ }
70
+ const attachment = (await broker.list(principal, context.mcpReq.signal)).find(item => item.attachmentId === attachmentId);
71
+ context.mcpReq.signal.throwIfAborted();
72
+ if (!attachment || !sameInspectionOwner(owner, attachment.owner))
73
+ throw new Error('Session unavailable');
74
+ const payload = event || diagnostic ? input : { ...input, kind };
75
+ const raw = await broker.call(principal, attachmentId, request.params.name, payload, context.mcpReq.signal);
76
+ if (kind === 'highlight') {
77
+ validateBridgeResult('inspection.highlight', raw);
78
+ const result = raw;
79
+ if (!sameInspectionOwner(result.owner, owner))
80
+ throw new Error('Session unavailable');
81
+ return { structuredContent: result, content: [{ type: 'text', text: JSON.stringify(result) }] };
82
+ }
83
+ const result = event ? validateEventPage(raw, owner, eventRequest) : validateInspectionResult(raw);
84
+ if (result.mode !== 'live' || !sameInspectionOwner(result.owner, owner) || (diagnostic && (!('inspection' in result) || result.inspection !== 'debug')) || (!event && !diagnostic && 'inspection' in result && result.inspection !== kind))
85
+ throw new Error('Session unavailable');
86
+ return { structuredContent: result, content: [{ type: 'text', text: JSON.stringify(result) }] };
87
+ }
88
+ catch (error) {
89
+ const unavailable = error instanceof Error && error.message.includes('Event lifetime unavailable');
90
+ const result = { ok: false, error: unavailable ? { code: 'STALE_REVISION', message: 'Event history lifetime unavailable' } : { code: 'SESSION_UNAVAILABLE', message: 'Live session unavailable' } };
91
+ return { isError: true, structuredContent: result, content: [{ type: 'text', text: JSON.stringify(result) }] };
92
+ }
93
+ });
94
+ return server;
95
+ }, { legacy: 'stateless', responseMode: 'json', maxRequestBodySize: 32 * 1024 });
96
+ return {
97
+ /** Authentication precedes MCP parsing and cannot be supplied through tool arguments. */
98
+ async fetch(request) {
99
+ if (closed)
100
+ return new Response('Unavailable', { status: 503 });
101
+ if (active >= 64)
102
+ return new Response('Busy', { status: 429 });
103
+ active++;
104
+ const controller = new AbortController();
105
+ const timer = setTimeout(() => controller.abort(), 5000);
106
+ const abort = () => controller.abort();
107
+ request.signal.addEventListener('abort', abort, { once: true });
108
+ authenticating.add(controller);
109
+ let off = () => { };
110
+ try {
111
+ if (request.signal.aborted)
112
+ abort();
113
+ const cancelled = new Promise((_resolve, reject) => {
114
+ const stop = () => reject(new Error('Authentication unavailable'));
115
+ off = () => controller.signal.removeEventListener('abort', stop);
116
+ controller.signal.addEventListener('abort', stop, { once: true });
117
+ if (controller.signal.aborted)
118
+ stop();
119
+ });
120
+ let principal;
121
+ try {
122
+ principal = await Promise.race([authenticate(request.clone()), cancelled]);
123
+ }
124
+ catch {
125
+ return new Response(closed ? 'Unavailable' : 'Unauthorized', { status: closed ? 503 : 401 });
126
+ }
127
+ if (closed || controller.signal.aborted || !principal || principal.length > 1024)
128
+ return new Response('Unauthorized', { status: 401 });
129
+ return await handler.fetch(new Request(request, { signal: controller.signal }), { authInfo: { token: 'verified', clientId: principal, scopes: [] } });
130
+ }
131
+ finally {
132
+ off();
133
+ clearTimeout(timer);
134
+ request.signal.removeEventListener('abort', abort);
135
+ authenticating.delete(controller);
136
+ active--;
137
+ }
138
+ },
139
+ /** Close this endpoint, preserving caller-owned broker and HTTP listener. */
140
+ close() {
141
+ if (closing)
142
+ return closing;
143
+ closed = true;
144
+ for (const controller of authenticating)
145
+ controller.abort();
146
+ closing = handler.close();
147
+ return closing;
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,8 @@
1
+ /** Track bounded, adapter-owned remote cleanup without closing caller connections. */
2
+ export declare function createRetirementTracker(timeoutMs: number): {
3
+ /** Reserve tracking before invoking a reentrant transport callback. */
4
+ start(operation: () => void | Promise<unknown>): void;
5
+ /** Join every retirement already reserved, reporting failed or stalled cleanup. */
6
+ drain(): Promise<void>;
7
+ };
8
+ //# sourceMappingURL=retirements.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retirements.d.ts","sourceRoot":"","sources":["../../src/node/retirements.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM;IAGrD,uEAAuE;IACvE,KAAK,YAAY,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;IAkB9C,mFAAmF;IAC7E,KAAK;EAKd"}
@@ -0,0 +1,34 @@
1
+ /** Track bounded, adapter-owned remote cleanup without closing caller connections. */
2
+ export function createRetirementTracker(timeoutMs) {
3
+ const pending = new Set();
4
+ return {
5
+ /** Reserve tracking before invoking a reentrant transport callback. */
6
+ start(operation) {
7
+ const completion = Promise.withResolvers();
8
+ pending.add(completion.promise);
9
+ let finished = false;
10
+ const timer = setTimeout(() => finish(false), timeoutMs);
11
+ /** Settle exactly once even when the remote reply arrives after timeout. */
12
+ function finish(success) {
13
+ if (finished)
14
+ return;
15
+ finished = true;
16
+ clearTimeout(timer);
17
+ completion.resolve(success);
18
+ }
19
+ try {
20
+ Promise.resolve(operation()).then(() => finish(true), () => finish(false));
21
+ }
22
+ catch {
23
+ finish(false);
24
+ }
25
+ void completion.promise.then(() => pending.delete(completion.promise));
26
+ },
27
+ /** Join every retirement already reserved, reporting failed or stalled cleanup. */
28
+ async drain() {
29
+ const results = await Promise.all([...pending]);
30
+ if (results.some(result => !result))
31
+ throw new Error('Attachment retirement incomplete');
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,6 @@
1
+ /** Bound Devframe calls until birpc itself settles, including after local abort. */
2
+ export declare function createRpcBudget(limit: number): {
3
+ /** Reserve before invoking upstream, then release only on actual settlement. */
4
+ call<T>(operation: () => Promise<T>): Promise<T>;
5
+ };
6
+ //# sourceMappingURL=rpc-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-budget.d.ts","sourceRoot":"","sources":["../../src/node/rpc-budget.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM;IAGzC,gFAAgF;IAChF,IAAI,CAAC,CAAC,aAAa,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;EAmBnD"}
@@ -0,0 +1,26 @@
1
+ /** Bound Devframe calls until birpc itself settles, including after local abort. */
2
+ export function createRpcBudget(limit) {
3
+ let pending = 0;
4
+ return {
5
+ /** Reserve before invoking upstream, then release only on actual settlement. */
6
+ call(operation) {
7
+ if (pending >= limit)
8
+ throw new Error('Transport capacity reached');
9
+ pending++;
10
+ let result;
11
+ try {
12
+ result = Promise.resolve(operation());
13
+ }
14
+ catch (error) {
15
+ pending--;
16
+ throw error;
17
+ }
18
+ void result.then(() => {
19
+ pending--;
20
+ }, () => {
21
+ pending--;
22
+ });
23
+ return result;
24
+ },
25
+ };
26
+ }
@@ -0,0 +1,65 @@
1
+ import type { Exposure } from '../shared/services.js';
2
+ export type { Exposure } from '../shared/services.js';
3
+ /** Host-verified document metadata; SDK retains its own bridge identity. */
4
+ export interface LiveIdentity {
5
+ projectId: string;
6
+ sourceId: string;
7
+ epoch: string;
8
+ revision: string;
9
+ mountId: string;
10
+ runtimeId: string;
11
+ target: {
12
+ storyId: string;
13
+ variantId: string;
14
+ };
15
+ }
16
+ /** Trusted host wrapper for exactly one authenticated transport connection. */
17
+ export interface LivePeer {
18
+ /** Dispatch one finite operation to this connection, propagating abort. */
19
+ call: (name: string, input: unknown, signal: AbortSignal) => Promise<unknown>;
20
+ /** Dispatch a reversible highlight and retain its exact cleanup until authorization finishes. */
21
+ callHighlight?: (name: string, input: unknown, signal: AbortSignal) => Promise<{
22
+ value: unknown;
23
+ finish: (accepted: boolean) => Promise<void>;
24
+ }>;
25
+ /** Notify the remote attachment that its authority has ended. */
26
+ retire?: () => void | Promise<unknown>;
27
+ }
28
+ /** Credential-free attachment exposed to authorized callers. */
29
+ export interface LiveAttachment {
30
+ attachmentId: string;
31
+ sourceUrl: string;
32
+ owner: Pick<LiveIdentity, 'sourceId' | 'epoch' | 'revision' | 'runtimeId' | 'target'>;
33
+ scopes: Exposure[];
34
+ }
35
+ /** Host policy resolves transport identity and verifies document authority. */
36
+ export interface BrokerOptions<P extends LivePeer> {
37
+ identifyPeer: (peer: P) => string | undefined | Promise<string | undefined>;
38
+ verifyAttachment: (peer: P, identity: LiveIdentity, sourceUrl: string) => {
39
+ identity: LiveIdentity;
40
+ scopes: readonly Exposure[];
41
+ } | Promise<{
42
+ identity: LiveIdentity;
43
+ scopes: readonly Exposure[];
44
+ }>;
45
+ /** Revalidate host ownership before and after asynchronous work. */
46
+ isCurrent: (peer: P, identity: LiveIdentity) => boolean | Promise<boolean>;
47
+ /** Increment synchronously for every policy or document ownership change. */
48
+ authorityVersion: () => number;
49
+ /** Observe retirement to release transport-owned bookkeeping. */
50
+ onRetire?: (peer: P, attachmentId: string) => void;
51
+ allowSource: (url: string) => boolean;
52
+ authorize: Authorization;
53
+ leaseMs?: number;
54
+ timeoutMs?: number;
55
+ }
56
+ /** Host policy runs for every discovery and operation. */
57
+ export type Authorization = (input: {
58
+ principal: string;
59
+ attachment: LiveAttachment & {
60
+ principal: string;
61
+ };
62
+ identity: LiveIdentity;
63
+ capability: 'discover' | Exposure;
64
+ }) => boolean | Promise<boolean>;
65
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/node/types.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { LiveIdentity } from './types.js';
2
+ /** Bound JSON payloads before they cross a trust or transport boundary. */
3
+ export declare function bounded<T>(value: T, maxBytes: number): T;
4
+ /** Verify the private owner tuple returned by the trusted host. */
5
+ export declare function verifiedIdentity(value: unknown): LiveIdentity;
6
+ /** Read a finite host revision without leaking host callback errors. */
7
+ export declare function readAuthorityVersion(callback: () => number): number;
8
+ /** Treat host source-policy errors as denial. */
9
+ export declare function isSourceAllowed(callback: (url: string) => boolean, url: string): boolean;
10
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/node/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAG9C,2EAA2E;AAC3E,wBAAgB,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,CAOxD;AAED,mEAAmE;AACnE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CAU7D;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,MAAM,GAAG,MAAM,CAQnE;AAED,iDAAiD;AACjD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAKxF"}