@agentapps/station 0.0.0-stage → 0.2.1

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -2
  3. package/dist/api-key-store.d.ts +46 -0
  4. package/dist/api-key-store.d.ts.map +1 -0
  5. package/dist/api-key-store.js +84 -0
  6. package/dist/api-key-store.js.map +1 -0
  7. package/dist/app-station.d.ts +129 -0
  8. package/dist/app-station.d.ts.map +1 -0
  9. package/dist/app-station.js +706 -0
  10. package/dist/app-station.js.map +1 -0
  11. package/dist/approval-manager.d.ts +75 -0
  12. package/dist/approval-manager.d.ts.map +1 -0
  13. package/dist/approval-manager.js +96 -0
  14. package/dist/approval-manager.js.map +1 -0
  15. package/dist/document-store.d.ts +86 -0
  16. package/dist/document-store.d.ts.map +1 -0
  17. package/dist/document-store.js +230 -0
  18. package/dist/document-store.js.map +1 -0
  19. package/dist/file-handlers/object-store.d.ts +113 -0
  20. package/dist/file-handlers/object-store.d.ts.map +1 -0
  21. package/dist/file-handlers/object-store.js +273 -0
  22. package/dist/file-handlers/object-store.js.map +1 -0
  23. package/dist/file-handlers/signed-url.d.ts +44 -0
  24. package/dist/file-handlers/signed-url.d.ts.map +1 -0
  25. package/dist/file-handlers/signed-url.js +68 -0
  26. package/dist/file-handlers/signed-url.js.map +1 -0
  27. package/dist/file-handlers/volume-handlers.d.ts +136 -0
  28. package/dist/file-handlers/volume-handlers.d.ts.map +1 -0
  29. package/dist/file-handlers/volume-handlers.js +426 -0
  30. package/dist/file-handlers/volume-handlers.js.map +1 -0
  31. package/dist/in-process-runtime.d.ts +49 -0
  32. package/dist/in-process-runtime.d.ts.map +1 -0
  33. package/dist/in-process-runtime.js +50 -0
  34. package/dist/in-process-runtime.js.map +1 -0
  35. package/dist/index.d.ts +27 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +34 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/local-process-runtime.d.ts +28 -0
  40. package/dist/local-process-runtime.d.ts.map +1 -0
  41. package/dist/local-process-runtime.js +134 -0
  42. package/dist/local-process-runtime.js.map +1 -0
  43. package/dist/oauth-manager.d.ts +90 -0
  44. package/dist/oauth-manager.d.ts.map +1 -0
  45. package/dist/oauth-manager.js +148 -0
  46. package/dist/oauth-manager.js.map +1 -0
  47. package/dist/oauth-pages.d.ts +9 -0
  48. package/dist/oauth-pages.d.ts.map +1 -0
  49. package/dist/oauth-pages.js +59 -0
  50. package/dist/oauth-pages.js.map +1 -0
  51. package/dist/permission-enforcer.d.ts +52 -0
  52. package/dist/permission-enforcer.d.ts.map +1 -0
  53. package/dist/permission-enforcer.js +144 -0
  54. package/dist/permission-enforcer.js.map +1 -0
  55. package/dist/policy-store.d.ts +34 -0
  56. package/dist/policy-store.d.ts.map +1 -0
  57. package/dist/policy-store.js +35 -0
  58. package/dist/policy-store.js.map +1 -0
  59. package/dist/secrets-manager.d.ts +32 -0
  60. package/dist/secrets-manager.d.ts.map +1 -0
  61. package/dist/secrets-manager.js +12 -0
  62. package/dist/secrets-manager.js.map +1 -0
  63. package/dist/server.d.ts +383 -0
  64. package/dist/server.d.ts.map +1 -0
  65. package/dist/server.js +1974 -0
  66. package/dist/server.js.map +1 -0
  67. package/dist/telemetry.d.ts +9 -0
  68. package/dist/telemetry.d.ts.map +1 -0
  69. package/dist/telemetry.js +9 -0
  70. package/dist/telemetry.js.map +1 -0
  71. package/dist/types.d.ts +47 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +9 -0
  74. package/dist/types.js.map +1 -0
  75. package/package.json +40 -3
@@ -0,0 +1,706 @@
1
+ /**
2
+ * Agent App AppStation — core logic.
3
+ *
4
+ * The per-app-family component that owns instance lifecycle and proxies
5
+ * all traffic between host and instances. Handles:
6
+ * - Control plane: initialize, session_open/close, controller_health
7
+ * - Session plane: proxy to/from the correct instance
8
+ * - Requests: proxy instance→host secret/auth requests (with security)
9
+ * - Lifecycle: spawn timeout, idle teardown, session_status notifications
10
+ * - Backpressure: max in-flight per session, max instances
11
+ *
12
+ * Spec: docs/specs/agent-apps/controller-protocol.md
13
+ */
14
+ import { createEnvelope, ErrorCode, PROTOCOL_VERSION, } from '@agentapps/protocol';
15
+ import { NOOP_TELEMETRY } from './telemetry.js';
16
+ /**
17
+ * Request types that require sessionId validation (REQ-7 security).
18
+ * The app station MUST verify the instance owns the session before
19
+ * proxying secret/auth requests to the host.
20
+ */
21
+ const INSTANCE_REQUEST_TYPES = new Set([
22
+ // HOOK-REQ-25: conversation reads get the same session validation.
23
+ 'conversation_read',
24
+ 'get_system_secrets',
25
+ 'get_installation_secrets',
26
+ 'update_installation_secrets',
27
+ 'auth_url',
28
+ 'auth_status',
29
+ 'refresh_token',
30
+ 'refresh_token_response',
31
+ 'prompt',
32
+ 'prompt_result',
33
+ 'get_user_profile',
34
+ 'intent_call',
35
+ 'inbound_subscribe',
36
+ 'inbound_unsubscribe',
37
+ 'storage_put',
38
+ 'storage_get',
39
+ 'storage_query',
40
+ 'storage_update',
41
+ 'storage_delete',
42
+ 'object_put',
43
+ 'object_get',
44
+ 'object_delete',
45
+ 'object_list',
46
+ 'object_link',
47
+ // Volume storage requests (file_volume_*)
48
+ 'file_volume_read_dir',
49
+ 'file_volume_read_file',
50
+ 'file_volume_write_file',
51
+ 'file_volume_delete',
52
+ 'file_volume_stat',
53
+ ]);
54
+ const APP_STATION_VERSION = '0.1.0';
55
+ const DEFAULT_OPEN_TIMEOUT_MS = 60_000;
56
+ const DEFAULT_MAX_INFLIGHT = 128;
57
+ const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
58
+ class SpawnTimeoutError extends Error {
59
+ constructor(ms) {
60
+ super(`Instance spawn timed out after ${ms}ms`);
61
+ this.name = 'SpawnTimeoutError';
62
+ }
63
+ }
64
+ // ---------------------------------------------------------------------------
65
+ // AppStation
66
+ // ---------------------------------------------------------------------------
67
+ /**
68
+ * Agent App AppStation.
69
+ *
70
+ * Usage:
71
+ * ```ts
72
+ * const ctrl = new AppStation({ appId, appVersion, runtime });
73
+ * ctrl.accept(transport); // host connects
74
+ * // ... host sends initialize, session_open, tool_call, etc.
75
+ * await ctrl.shutdown();
76
+ * ```
77
+ */
78
+ export class AppStation {
79
+ config;
80
+ initialized = false;
81
+ /** The Host behind this connection, as declared at initialize (HOSTCAP-REQ-2). */
82
+ host = { name: '', version: '', capabilities: {} };
83
+ /** Tenant a single-user Host is bound to by its first session (HOSTCAP-REQ-6). */
84
+ boundUserId = null;
85
+ sessions = new Map();
86
+ instances = new Map();
87
+ hostTransport = null;
88
+ hostUnsub = null;
89
+ openTimeoutMs;
90
+ maxInflight;
91
+ idleTimeoutMs;
92
+ maxInstances;
93
+ telemetry;
94
+ /** Track promptIds per session to prevent replay attacks. */
95
+ promptIds = new Map();
96
+ constructor(config) {
97
+ this.config = config;
98
+ this.openTimeoutMs = config.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS;
99
+ this.maxInflight = config.maxInflightPerSession ?? DEFAULT_MAX_INFLIGHT;
100
+ this.idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
101
+ this.maxInstances = config.maxInstances ?? Number.POSITIVE_INFINITY;
102
+ this.telemetry = config.telemetry ?? NOOP_TELEMETRY;
103
+ }
104
+ // =========================================================================
105
+ // Public API
106
+ // =========================================================================
107
+ /** Accept a host connection on the given transport. */
108
+ accept(transport) {
109
+ this.hostTransport = transport;
110
+ this.hostUnsub = transport.onMessage((msg) => {
111
+ this.handleHostMessage(msg).catch((err) => {
112
+ // eslint-disable-next-line no-console
113
+ console.error('[app-station] unhandled error:', err);
114
+ });
115
+ });
116
+ }
117
+ /** Shut down the app station and all sessions. */
118
+ async shutdown() {
119
+ // Clear all idle timers and relay subscriptions
120
+ for (const managed of this.instances.values()) {
121
+ if (managed.idleTimer)
122
+ clearTimeout(managed.idleTimer);
123
+ managed.unsubscribe();
124
+ }
125
+ // Stop all instances
126
+ const stopPromises = [];
127
+ for (const managed of this.instances.values()) {
128
+ stopPromises.push(managed.handle.stop(5_000));
129
+ }
130
+ await Promise.allSettled(stopPromises);
131
+ this.instances.clear();
132
+ this.sessions.clear();
133
+ this.promptIds.clear();
134
+ this.hostUnsub?.();
135
+ await this.hostTransport?.close();
136
+ this.hostTransport = null;
137
+ this.initialized = false;
138
+ }
139
+ /** Number of active sessions. */
140
+ get sessionCount() {
141
+ return this.sessions.size;
142
+ }
143
+ /** Number of live instances. */
144
+ get instanceCount() {
145
+ return this.instances.size;
146
+ }
147
+ // =========================================================================
148
+ // Host message dispatch
149
+ // =========================================================================
150
+ async handleHostMessage(msg) {
151
+ const anyMsg = msg;
152
+ // Control-plane messages dispatched by type first — some carry
153
+ // sessionId (e.g., session_close) but are NOT session-plane.
154
+ switch (msg.type) {
155
+ case 'initialize':
156
+ this.handleInitialize(anyMsg);
157
+ return;
158
+ case 'session_open':
159
+ await this.handleSessionOpen(anyMsg);
160
+ return;
161
+ case 'session_close':
162
+ this.handleSessionClose(anyMsg);
163
+ return;
164
+ case 'controller_health':
165
+ this.handleControllerHealth(anyMsg);
166
+ return;
167
+ }
168
+ // Everything else is session-plane — route to instance by sessionId (REQ-6)
169
+ if (typeof anyMsg.sessionId === 'string') {
170
+ this.routeToInstance(anyMsg.sessionId, msg);
171
+ return;
172
+ }
173
+ this.sendError(msg.id, ErrorCode.UNKNOWN_MESSAGE_TYPE, `Unknown message type: ${msg.type}`);
174
+ }
175
+ // =========================================================================
176
+ // Control plane handlers
177
+ // =========================================================================
178
+ /** REQ-2: Handshake and capability negotiation. */
179
+ handleInitialize(msg) {
180
+ const versions = msg.supportedVersions;
181
+ const supports2 = Array.isArray(versions) && versions.includes('2.0');
182
+ if (!supports2) {
183
+ this.sendError(msg.id, ErrorCode.VERSION_UNSUPPORTED, 'Only protocol version 2.0 is supported');
184
+ return;
185
+ }
186
+ this.initialized = true;
187
+ // HOSTCAP-REQ-2: keep what the Host declared, minus the reserved flag.
188
+ const host = (msg.host ?? {});
189
+ const { directConnection: _reserved, ...declared } = (msg.capabilities ?? {});
190
+ this.host = { name: host.name ?? '', version: host.version ?? '', capabilities: declared };
191
+ // A new initialize is a new connection: a single-user binding starts over.
192
+ this.boundUserId = null;
193
+ const response = {
194
+ ...createEnvelope('initialized'),
195
+ id: msg.id,
196
+ negotiatedVersion: PROTOCOL_VERSION,
197
+ app: { id: this.config.appId, version: this.config.appVersion },
198
+ station: { version: APP_STATION_VERSION },
199
+ capabilities: {
200
+ directConnection: false,
201
+ asyncOpen: false,
202
+ push: true,
203
+ extensions: [],
204
+ },
205
+ limits: {
206
+ openTimeoutMs: this.openTimeoutMs,
207
+ maxInflightPerSession: this.maxInflight,
208
+ },
209
+ };
210
+ this.hostSend(response);
211
+ }
212
+ /** REQ-4, REQ-5: Tenant session open (idempotent, with instance reuse). */
213
+ async handleSessionOpen(msg) {
214
+ if (!this.initialized) {
215
+ this.sendError(msg.id, ErrorCode.INVALID_MESSAGE, 'AppStation not initialized — send initialize first');
216
+ return;
217
+ }
218
+ const installationId = msg.installationId;
219
+ const tenant = msg.tenant;
220
+ if (!installationId || !tenant?.userId) {
221
+ this.sendError(msg.id, ErrorCode.INVALID_MESSAGE, 'session_open requires installationId and tenant.userId');
222
+ return;
223
+ }
224
+ // HOSTCAP-REQ-6: a single-user Host is bound to the Tenant of its first session.
225
+ if (this.host.capabilities.multiUser !== true) {
226
+ if (this.boundUserId !== null && this.boundUserId !== tenant.userId) {
227
+ this.sendError(msg.id, ErrorCode.NOT_SUPPORTED, `This Host declared no multiUser support and is bound to another user; session_open as ${tenant.userId} rejected`);
228
+ return;
229
+ }
230
+ this.boundUserId = tenant.userId;
231
+ }
232
+ // Idempotent open (REQ-5): active session for same installation → return it
233
+ for (const [sessionId, session] of this.sessions) {
234
+ if (session.installationId === installationId) {
235
+ const reopen = {
236
+ ...createEnvelope('session_opened'),
237
+ id: msg.id,
238
+ sessionId,
239
+ instance: { appVersion: this.config.appVersion },
240
+ host: this.host,
241
+ };
242
+ this.hostSend(reopen);
243
+ return;
244
+ }
245
+ }
246
+ // Reuse live instance after session_close (REQ-5: instance lifetime ≠ session)
247
+ const existing = this.instances.get(installationId);
248
+ if (existing?.handle.isAlive()) {
249
+ // Cancel idle timer — session is back
250
+ if (existing.idleTimer) {
251
+ clearTimeout(existing.idleTimer);
252
+ existing.idleTimer = null;
253
+ }
254
+ const sessionId = generateSessionId();
255
+ this.sessions.set(sessionId, {
256
+ id: sessionId,
257
+ installationId,
258
+ tenant,
259
+ permissions: effectivePermissionsOf(msg),
260
+ pendingRequests: new Set(),
261
+ });
262
+ existing.sessions.add(sessionId);
263
+ existing.lastActivity = Date.now();
264
+ this.hostSend({
265
+ ...createEnvelope('session_opened'),
266
+ id: msg.id,
267
+ sessionId,
268
+ instance: { appVersion: this.config.appVersion },
269
+ host: this.host,
270
+ });
271
+ this.notifySessionOpened(existing.handle, sessionId, installationId, tenant);
272
+ return;
273
+ }
274
+ // Clean up dead instance if present
275
+ if (existing) {
276
+ existing.unsubscribe();
277
+ if (existing.idleTimer)
278
+ clearTimeout(existing.idleTimer);
279
+ this.instances.delete(installationId);
280
+ }
281
+ // Check max instances (REQ-10)
282
+ if (this.instances.size >= this.maxInstances) {
283
+ this.sendError(msg.id, ErrorCode.CONTROLLER_AT_CAPACITY, 'Maximum number of instances reached');
284
+ return;
285
+ }
286
+ // Spawn new instance with timeout (REQ-4)
287
+ const sessionId = generateSessionId();
288
+ this.emitSessionStatus(sessionId, 'starting');
289
+ const spawnSpan = this.telemetry.startSpan('agentapps.spawn', {
290
+ 'app.id': this.config.appId,
291
+ installationId,
292
+ });
293
+ const spawnStart = Date.now();
294
+ const timeout = rejectAfterMs(this.openTimeoutMs);
295
+ try {
296
+ const handle = await Promise.race([
297
+ this.config.runtime.spawn({
298
+ installationId,
299
+ tenant,
300
+ volumePath: this.config.resolveMountPath?.({
301
+ installationId,
302
+ tenant,
303
+ effectivePermissions: msg.effectivePermissions,
304
+ }),
305
+ }),
306
+ timeout.promise,
307
+ ]);
308
+ const spawnDuration = Date.now() - spawnStart;
309
+ this.telemetry.histogram('agentapps.spawn.duration_ms', spawnDuration, {
310
+ 'app.id': this.config.appId,
311
+ });
312
+ this.telemetry.counter('agentapps.spawn.count', 1, { 'app.id': this.config.appId });
313
+ spawnSpan.setStatus('ok');
314
+ const now = Date.now();
315
+ const managed = {
316
+ installationId,
317
+ handle,
318
+ unsubscribe: () => { }, // placeholder — set below
319
+ sessions: new Set([sessionId]),
320
+ idleTimer: null,
321
+ createdAt: now,
322
+ lastActivity: now,
323
+ };
324
+ // Wire instance→host relay with security validation
325
+ managed.unsubscribe = handle.onMessage((instanceMsg) => {
326
+ this.relayInstanceMessage(managed, instanceMsg);
327
+ });
328
+ this.instances.set(installationId, managed);
329
+ this.sessions.set(sessionId, {
330
+ id: sessionId,
331
+ installationId,
332
+ tenant,
333
+ permissions: effectivePermissionsOf(msg),
334
+ pendingRequests: new Set(),
335
+ });
336
+ this.telemetry.counter('agentapps.session.open', 1, { 'app.id': this.config.appId });
337
+ this.telemetry.gauge('agentapps.instances.active', this.instances.size, {
338
+ 'app.id': this.config.appId,
339
+ });
340
+ this.emitSessionStatus(sessionId, 'ready');
341
+ this.hostSend({
342
+ ...createEnvelope('session_opened'),
343
+ id: msg.id,
344
+ sessionId,
345
+ instance: { appVersion: this.config.appVersion },
346
+ host: this.host,
347
+ });
348
+ this.notifySessionOpened(handle, sessionId, installationId, tenant);
349
+ }
350
+ catch (err) {
351
+ spawnSpan.setStatus('error', String(err));
352
+ if (err instanceof SpawnTimeoutError) {
353
+ this.sendError(msg.id, ErrorCode.TIMEOUT, err.message);
354
+ }
355
+ else {
356
+ this.sendError(msg.id, ErrorCode.SPAWN_FAILED, `Failed to spawn instance: ${err}`);
357
+ }
358
+ }
359
+ finally {
360
+ timeout.clear();
361
+ spawnSpan.end();
362
+ }
363
+ }
364
+ /** REQ-4: Session close. Does NOT immediately stop the instance (REQ-4). */
365
+ handleSessionClose(msg) {
366
+ const sessionId = msg.sessionId;
367
+ if (!sessionId) {
368
+ this.sendError(msg.id, ErrorCode.INVALID_MESSAGE, 'session_close requires sessionId');
369
+ return;
370
+ }
371
+ const session = this.sessions.get(sessionId);
372
+ if (!session) {
373
+ this.sendError(msg.id, ErrorCode.SESSION_NOT_FOUND, `Session ${sessionId} not found`);
374
+ return;
375
+ }
376
+ // Remove session
377
+ this.sessions.delete(sessionId);
378
+ this.promptIds.delete(sessionId);
379
+ this.telemetry.counter('agentapps.session.close', 1, { 'app.id': this.config.appId });
380
+ // Update instance: remove session, start idle timer if no sessions left
381
+ const managed = this.instances.get(session.installationId);
382
+ if (managed) {
383
+ managed.sessions.delete(sessionId);
384
+ if (managed.sessions.size === 0) {
385
+ this.resetIdleTimer(managed);
386
+ }
387
+ }
388
+ this.hostSend({
389
+ ...createEnvelope('session_closed'),
390
+ id: msg.id,
391
+ sessionId,
392
+ });
393
+ }
394
+ /** REQ-8: Aggregated app station health. */
395
+ handleControllerHealth(msg) {
396
+ const verbose = msg.verbose ?? false;
397
+ const allManaged = [...this.instances.values()];
398
+ let readyCount = 0;
399
+ let crashedCount = 0;
400
+ const unhealthy = [];
401
+ const allDetails = [];
402
+ for (const managed of allManaged) {
403
+ const alive = managed.handle.isAlive();
404
+ const uptime = Math.floor((Date.now() - managed.createdAt) / 1000);
405
+ const lastUsed = new Date(managed.lastActivity).toISOString();
406
+ const status = alive ? 'ready' : 'crashed';
407
+ if (alive) {
408
+ readyCount++;
409
+ }
410
+ else {
411
+ crashedCount++;
412
+ if (unhealthy.length < 50) {
413
+ unhealthy.push({
414
+ instanceId: managed.handle.instanceId,
415
+ installationId: managed.installationId,
416
+ status,
417
+ uptime,
418
+ lastUsed,
419
+ });
420
+ }
421
+ }
422
+ if (verbose) {
423
+ allDetails.push({
424
+ instanceId: managed.handle.instanceId,
425
+ installationId: managed.installationId,
426
+ status,
427
+ uptime,
428
+ lastUsed,
429
+ });
430
+ }
431
+ }
432
+ const health = {
433
+ ...createEnvelope('controller_health_status'),
434
+ id: msg.id,
435
+ status: crashedCount > 0 ? 'degraded' : 'ready',
436
+ counts: {
437
+ total: allManaged.length,
438
+ ready: readyCount,
439
+ degraded: 0,
440
+ crashed: crashedCount,
441
+ starting: 0,
442
+ },
443
+ unhealthy,
444
+ };
445
+ if (verbose) {
446
+ health.instances = allDetails;
447
+ }
448
+ this.hostSend(health);
449
+ }
450
+ // =========================================================================
451
+ // Session-plane routing (REQ-6, REQ-10)
452
+ // =========================================================================
453
+ routeToInstance(sessionId, msg) {
454
+ const session = this.sessions.get(sessionId);
455
+ if (!session) {
456
+ this.sendError(msg.id, ErrorCode.SESSION_NOT_FOUND, `Session ${sessionId} not found`);
457
+ return;
458
+ }
459
+ // Backpressure (REQ-10)
460
+ if (session.pendingRequests.size >= this.maxInflight) {
461
+ this.sendError(msg.id, ErrorCode.RATE_LIMITED, `Session ${sessionId} exceeds max in-flight (${this.maxInflight})`);
462
+ return;
463
+ }
464
+ const managed = this.instances.get(session.installationId);
465
+ if (!managed?.handle.isAlive()) {
466
+ this.sendError(msg.id, ErrorCode.SESSION_NOT_FOUND, `Instance for session ${sessionId} is no longer alive`);
467
+ return;
468
+ }
469
+ // Edge case of HOSTCAP: a Host that cannot receive pushed events cannot subscribe.
470
+ if (msg.type === 'subscribe' && this.host.capabilities.push !== true) {
471
+ this.sendError(msg.id, ErrorCode.NOT_SUPPORTED, 'This Host declared no push support, so it cannot receive subscription events');
472
+ return;
473
+ }
474
+ // POLICY-REQ-8: keep the Effective Permissions the Host last announced.
475
+ if (msg.type === 'permissions_changed') {
476
+ session.permissions = effectivePermissionsOf(msg);
477
+ }
478
+ // POLICY-REQ-8: a basic profile carries no email and no avatar.
479
+ if (msg.type === 'user_profile_result') {
480
+ const anyMsg = msg;
481
+ if (session.basicProfileRequests?.delete(anyMsg.requestId)) {
482
+ const profile = anyMsg.profile;
483
+ if (profile) {
484
+ const { email: _email, avatarUrl: _avatar, ...basic } = profile;
485
+ msg = { ...msg, profile: basic };
486
+ }
487
+ }
488
+ }
489
+ // Track in-flight request
490
+ session.pendingRequests.add(msg.id);
491
+ // Reset idle timer on activity
492
+ managed.lastActivity = Date.now();
493
+ if (managed.idleTimer) {
494
+ clearTimeout(managed.idleTimer);
495
+ managed.idleTimer = null;
496
+ }
497
+ this.telemetry.counter('agentapps.message.sent', 1, {
498
+ 'app.id': this.config.appId,
499
+ 'message.type': msg.type,
500
+ });
501
+ // Proxy verbatim to the instance (REQ-6)
502
+ managed.handle.send(msg);
503
+ }
504
+ // =========================================================================
505
+ // Instance → Host relay
506
+ // =========================================================================
507
+ /**
508
+ * Relay a message from an instance to the host.
509
+ *
510
+ * Security (REQ-7): validates sessionId on request types to prevent
511
+ * a compromised instance from reading another tenant's secrets.
512
+ */
513
+ relayInstanceMessage(managed, instanceMsg) {
514
+ const forwarded = { ...instanceMsg };
515
+ const msgSessionId = forwarded.sessionId;
516
+ // Security: validate sessionId on request types (REQ-7)
517
+ if (msgSessionId && INSTANCE_REQUEST_TYPES.has(forwarded.type)) {
518
+ if (!managed.sessions.has(msgSessionId)) {
519
+ // eslint-disable-next-line no-console
520
+ console.error(`[app-station] Instance ${managed.installationId} sent request with ` +
521
+ `sessionId ${msgSessionId} it doesn't own — dropped`);
522
+ return;
523
+ }
524
+ }
525
+ // POLICY-REQ-8: Requests gated by a Manifest Permission, checked by name.
526
+ if (msgSessionId && this.denyByPermission(managed, forwarded, msgSessionId))
527
+ return;
528
+ // Security: validate promptId uniqueness per session to prevent replay attacks
529
+ if (forwarded.type === 'prompt' && msgSessionId) {
530
+ const promptId = forwarded.promptId;
531
+ if (promptId) {
532
+ let sessionPromptIds = this.promptIds.get(msgSessionId);
533
+ if (!sessionPromptIds) {
534
+ sessionPromptIds = new Set();
535
+ this.promptIds.set(msgSessionId, sessionPromptIds);
536
+ }
537
+ if (sessionPromptIds.has(promptId)) {
538
+ // eslint-disable-next-line no-console
539
+ console.error(`[app-station] Duplicate promptId ${promptId} from session ${msgSessionId} — dropped`);
540
+ return;
541
+ }
542
+ sessionPromptIds.add(promptId);
543
+ // Rate limit: warn if too many requests
544
+ if (sessionPromptIds.size > 100) {
545
+ // eslint-disable-next-line no-console
546
+ console.warn(`[app-station] Session ${msgSessionId} has ${sessionPromptIds.size} pending requests — possible abuse`);
547
+ }
548
+ }
549
+ }
550
+ // Track completed requests for backpressure
551
+ if (msgSessionId) {
552
+ const session = this.sessions.get(msgSessionId);
553
+ if (session) {
554
+ session.pendingRequests.delete(forwarded.id);
555
+ }
556
+ }
557
+ this.telemetry.counter('agentapps.message.received', 1, {
558
+ 'app.id': this.config.appId,
559
+ 'message.type': forwarded.type,
560
+ });
561
+ this.hostSend(forwarded);
562
+ }
563
+ // =========================================================================
564
+ // Idle timeout (REQ-4, REQ-5)
565
+ // =========================================================================
566
+ resetIdleTimer(managed) {
567
+ if (managed.idleTimer)
568
+ clearTimeout(managed.idleTimer);
569
+ managed.idleTimer = setTimeout(() => {
570
+ this.handleIdleTimeout(managed);
571
+ }, this.idleTimeoutMs);
572
+ }
573
+ handleIdleTimeout(managed) {
574
+ // Emit session_status: idle_stopped for any remaining sessions (REQ-5)
575
+ for (const sessionId of managed.sessions) {
576
+ this.emitSessionStatus(sessionId, 'idle_stopped');
577
+ this.sessions.delete(sessionId);
578
+ }
579
+ managed.sessions.clear();
580
+ // Stop instance
581
+ managed.unsubscribe();
582
+ managed.handle.stop(5_000).catch(() => { });
583
+ this.instances.delete(managed.installationId);
584
+ this.telemetry.gauge('agentapps.instances.active', this.instances.size, {
585
+ 'app.id': this.config.appId,
586
+ });
587
+ }
588
+ // =========================================================================
589
+ // Helpers
590
+ // =========================================================================
591
+ /** Emit a session_status notification to the host (REQ-5). */
592
+ emitSessionStatus(sessionId, status) {
593
+ this.hostSend({
594
+ ...createEnvelope('session_status'),
595
+ sessionId,
596
+ status,
597
+ });
598
+ }
599
+ /** Send a message to the host. */
600
+ /**
601
+ * Answer an Instance's Request with PERMISSION_DENIED when the Permission
602
+ * it needs is not among the session's Effective Permissions. Returns true
603
+ * when the Request was answered here and must not reach the Host.
604
+ *
605
+ * @spec POLICY-REQ-8
606
+ */
607
+ denyByPermission(managed, msg, sessionId) {
608
+ const session = this.sessions.get(sessionId);
609
+ const permissions = session?.permissions ?? {};
610
+ const deny = (permission, result) => {
611
+ const reason = `The ${permission} Permission is not granted to this Installation`;
612
+ // POLICY-NFR-1: every deny is audited.
613
+ // eslint-disable-next-line no-console
614
+ console.error(`[policy] deny: installation=${managed.installationId} request=${msg.type} permission=${permission} at=${new Date().toISOString()}`);
615
+ managed.handle.send({
616
+ ...createEnvelope(result.type),
617
+ sessionId,
618
+ requestId: msg.requestId,
619
+ ...result,
620
+ ...(result.error === undefined
621
+ ? {}
622
+ : {
623
+ error: {
624
+ code: ErrorCode.PERMISSION_DENIED,
625
+ message: reason,
626
+ details: { layer: 'permission', permission, reason },
627
+ },
628
+ }),
629
+ });
630
+ return true;
631
+ };
632
+ if (msg.type === 'intent_call' && permissions.intents !== true) {
633
+ return deny('intents', { type: 'intent_result', success: false, error: true, duration: 0 });
634
+ }
635
+ if (msg.type === 'get_user_profile') {
636
+ if (permissions.profile !== 'basic' && permissions.profile !== 'full') {
637
+ managed.handle.send({
638
+ ...createEnvelope('user_profile_result'),
639
+ sessionId,
640
+ requestId: msg.requestId,
641
+ profile: null,
642
+ error: 'The profile Permission is not granted to this Installation',
643
+ code: ErrorCode.PERMISSION_DENIED,
644
+ });
645
+ return true;
646
+ }
647
+ if (permissions.profile === 'basic' && session) {
648
+ session.basicProfileRequests ??= new Set();
649
+ session.basicProfileRequests.add(msg.requestId);
650
+ }
651
+ }
652
+ return false;
653
+ }
654
+ hostSend(msg) {
655
+ this.hostTransport?.send(msg);
656
+ }
657
+ /**
658
+ * Tell the Instance its session is established and which Host is behind it
659
+ * (HOSTCAP-REQ-2), so the SDK can expose `ctx.host`.
660
+ */
661
+ notifySessionOpened(handle, sessionId, installationId, tenant) {
662
+ handle.send({
663
+ ...createEnvelope('session_opened'),
664
+ sessionId,
665
+ installationId,
666
+ tenant,
667
+ host: this.host,
668
+ });
669
+ }
670
+ /** Send an error response to the host. */
671
+ sendError(requestId, code, message) {
672
+ const err = {
673
+ ...createEnvelope('error'),
674
+ id: requestId,
675
+ error: { code, message },
676
+ };
677
+ this.hostSend(err);
678
+ }
679
+ }
680
+ // ---------------------------------------------------------------------------
681
+ // Utilities
682
+ // ---------------------------------------------------------------------------
683
+ function generateSessionId() {
684
+ return `sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
685
+ }
686
+ function rejectAfterMs(ms) {
687
+ let timer;
688
+ const promise = new Promise((_, reject) => {
689
+ timer = setTimeout(() => reject(new SpawnTimeoutError(ms)), ms);
690
+ });
691
+ return {
692
+ promise,
693
+ clear: () => {
694
+ if (timer)
695
+ clearTimeout(timer);
696
+ },
697
+ };
698
+ }
699
+ /** The `permissions` object of a message's Effective Permissions, if any. */
700
+ function effectivePermissionsOf(msg) {
701
+ const ep = (msg.effectivePermissions ?? msg.permissions);
702
+ if (!ep)
703
+ return undefined;
704
+ return ('permissions' in ep ? ep.permissions : ep);
705
+ }
706
+ //# sourceMappingURL=app-station.js.map