The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit 5ab277316767Commit detailsView latest

packages/persistence/src/hosted.ts 1916 lines · 74.1 KB · typescript
1
import { neon, type NeonQueryFunction } from '@neondatabase/serverless';
2
import { randomBytes } from 'node:crypto';
3
import {
4
  DEFAULT_EXTENSION_URI,
5
  FederatedInteractionSchema,
6
  LiveSessionAcceptanceSchema,
7
  LiveSessionActivationSchema,
8
  LiveSessionEventSchema,
9
  LiveSessionOfferSchema,
10
  HostedMessageSchema,
11
  HostedThreadSchema,
12
  PublicAgentCardSchema,
13
  canonicalHash,
14
  type FederatedInteraction,
15
  type AgentPresence,
16
  type LiveSessionActivation,
17
  type LiveSessionEvent,
18
  type LiveSessionInsight,
19
  type HostedMessage,
20
  type HostedThread,
21
  type PublicAgentCard,
22
} from '../../protocol/src/index.js';
23
import type { AgentProfile } from './onboarding.js';
24
import {
25
  decryptGatewayPayload,
26
  encryptGatewayPayload,
27
  attestSessionRecord,
28
  getSessionKeyId,
29
  getSessionVerificationKey,
30
  issueSessionGrant,
31
  signSessionControl,
32
  verifySessionGrant,
33
} from './relay.js';
34
import { postRuntimeJson, resolvePublicRuntimeEndpoint } from './runtime.js';
35
36
export type HostedRecordKind =
37
  | 'agent'
38
  | 'delegation'
39
  | 'contract'
40
  | 'interaction'
41
  | 'event'
42
  | 'receipt'
43
  | 'feedback'
44
  | 'conflict'
45
  | 'profile'
46
  | 'consent'
47
  | 'revocation'
48
  | 'project'
49
  | 'agent_profile'
50
  | 'installation'
51
  | 'setup_request'
52
  | 'publication'
53
  | 'presence';
54
55
export type { PublicAgentCard, FederatedInteraction } from '../../protocol/src/index.js';
56
57
type ContextualProfile = {
58
  recordId: string;
59
  agentVersion: string;
60
  sampleSize: number;
61
  updatedAt: string;
62
  completion: number;
63
  acceptance: number;
64
  specification: number;
65
  deadline: number;
66
  communication: number;
67
  evidence: number;
68
  scope: number;
69
  disputes: number;
70
};
71
72
function normalizePublicAgentCard(value: unknown): PublicAgentCard {
73
  const current = PublicAgentCardSchema.safeParse(value);
74
  if (current.success) return current.data;
75
  const legacy = value as Record<string, unknown>;
76
  const agentId = String(legacy.agentId ?? '');
77
  const baseUrl = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
78
    /\/$/,
79
    '',
80
  );
81
  return PublicAgentCardSchema.parse({
82
    protocolVersion: '0.1',
83
    agentId,
84
    name: legacy.name,
85
    description: '',
86
    framework: legacy.framework,
87
    agentVersion: '1.0.0',
88
    capabilities: legacy.capabilities,
89
    limitations: legacy.limitations,
90
    assurance: legacy.assurance,
91
    transports:
92
      typeof legacy.a2aEndpoint === 'string'
93
        ? [
94
            {
95
              protocol: 'A2A/1.0',
96
              protocolBinding: 'JSONRPC',
97
              endpoint: legacy.a2aEndpoint,
98
              managedBy: 'agent',
99
            },
100
          ]
101
        : [],
102
    cardUrl: `${baseUrl}/agents/${encodeURIComponent(agentId)}/card.json`,
103
    a2aAgentCardUrl: `${baseUrl}/agents/${encodeURIComponent(agentId)}/a2a-agent-card.json`,
104
    extensionUri: DEFAULT_EXTENSION_URI,
105
    publishedAt: legacy.publishedAt,
106
    updatedAt: legacy.updatedAt,
107
  });
108
}
109
110
export function buildPublicAgentCard(
111
  agent: AgentProfile,
112
  baseUrl: string,
113
  previous?: PublicAgentCard,
114
): PublicAgentCard {
115
  const now = new Date().toISOString();
116
  const root = baseUrl.replace(/\/$/, '');
117
  return PublicAgentCardSchema.parse({
118
    protocolVersion: '0.1',
119
    agentId: agent.agentId,
120
    name: agent.name,
121
    description: agent.description ?? '',
122
    framework: agent.framework,
123
    agentVersion: agent.agentVersion ?? '1.0.0',
124
    capabilities: agent.capabilities,
125
    limitations: agent.limitations,
126
    assurance: 'oauth_authenticated',
127
    agentMode: agent.agentMode ?? (agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat'),
128
    transports:
129
      (agent.agentMode ?? (agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat')) ===
130
      'temporary_chat'
131
        ? [
132
            {
133
              protocol: 'A2A/1.0',
134
              protocolBinding: 'JSONRPC',
135
              endpoint: `${root}/a2a/temporary/${encodeURIComponent(agent.agentId)}`,
136
              managedBy: 'openclasp',
137
            },
138
          ]
139
        : agent.a2aEndpoint
140
          ? [
141
              {
142
                protocol: 'A2A/1.0',
143
                protocolBinding: 'JSONRPC',
144
                endpoint: agent.a2aEndpoint,
145
                managedBy: 'agent',
146
              },
147
            ]
148
          : [],
149
    cardUrl: `${root}/agents/${encodeURIComponent(agent.agentId)}/card.json`,
150
    a2aAgentCardUrl: `${root}/agents/${encodeURIComponent(agent.agentId)}/a2a-agent-card.json`,
151
    extensionUri: DEFAULT_EXTENSION_URI,
152
    publishedAt: previous?.publishedAt ?? now,
153
    updatedAt: now,
154
  });
155
}
156
157
const normalized = (value: string) =>
158
  value
159
    .trim()
160
    .toLowerCase()
161
    .replace(/[^a-z0-9]+/g, '_');
162
163
export const AGENT_ONLINE_WINDOW_MS = 2 * 60_000;
164
165
export function resolveAgentPresence(lastSeenAt?: string, now = new Date()): AgentPresence {
166
  const online = Boolean(
167
    lastSeenAt && now.getTime() - Date.parse(lastSeenAt) <= AGENT_ONLINE_WINDOW_MS,
168
  );
169
  return {
170
    status: online ? 'online' : 'offline',
171
    ...(lastSeenAt ? { lastSeenAt } : {}),
172
    checkedAt: now.toISOString(),
173
  };
174
}
175
176
export function canAutoAcceptInteraction(
177
  agent: AgentProfile,
178
  interaction: FederatedInteraction,
179
): boolean {
180
  if (agent.autoAcceptPolicy !== 'safe_matching' || agent.status !== 'active') return false;
181
  const categories = new Set(
182
    [...(agent.autoAcceptTaskCategories ?? []), ...(agent.capabilities ?? [])].map(normalized),
183
  );
184
  const taskCategory = normalized(interaction.contract.taskCategory);
185
  if (!taskCategory || !categories.has(taskCategory)) return false;
186
  if (interaction.contract.allowedData.length > 0) return false;
187
  if (
188
    /\b(password|secret|api[_ -]?key|access[_ -]?token|credential|bank|payment|medical|health|ssn|personal[_ -]?data|customer[_ -]?record)\b/i.test(
189
      `${interaction.contract.purpose} ${interaction.contract.requestedOutcome}`,
190
    )
191
  )
192
    return false;
193
  if (interaction.contract.humanApprovalRequirements.length > 0) return false;
194
  if (interaction.contract.retentionDays > 30) return false;
195
  if (interaction.contract.allowedActions.length > 0) {
196
    const capabilities = new Set((agent.capabilities ?? []).map(normalized));
197
    if (
198
      !interaction.contract.allowedActions.every((action) => capabilities.has(normalized(action)))
199
    )
200
      return false;
201
  }
202
  return true;
203
}
204
205
export type AccountSettings = {
206
  displayName: string;
207
  contributionEnabled: boolean;
208
  retentionDays: number;
209
  evidenceSharing: 'never' | 'ask' | 'contract_only';
210
  rawConversationsStored: false;
211
};
212
213
const defaults: AccountSettings = {
214
  displayName: '',
215
  contributionEnabled: false,
216
  retentionDays: 30,
217
  evidenceSharing: 'ask',
218
  rawConversationsStored: false,
219
};
220
221
export class HostedRepository {
222
  private readonly sql: NeonQueryFunction<false, false>;
223
  private initialized?: Promise<void>;
224
225
  constructor(databaseUrl: string) {
226
    this.sql = neon(databaseUrl);
227
  }
228
229
  private gatewaySecret() {
230
    const value = process.env.OPENCLASP_RELAY_ENCRYPTION_KEY;
231
    if (!value || value.length < 32) throw new Error('Gateway encryption is not configured');
232
    return value;
233
  }
234
235
  ensureSchema(): Promise<void> {
236
    return (this.initialized ??= (async () => {
237
      await this.sql`
238
        CREATE TABLE IF NOT EXISTS openclasp_records (
239
          operator_id TEXT NOT NULL,
240
          kind TEXT NOT NULL,
241
          record_id TEXT NOT NULL,
242
          payload JSONB NOT NULL,
243
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
244
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
245
          PRIMARY KEY (operator_id, kind, record_id)
246
        )
247
      `;
248
      await this.sql`
249
        CREATE INDEX IF NOT EXISTS openclasp_records_operator_created
250
        ON openclasp_records(operator_id, created_at DESC)
251
      `;
252
      await this.sql`
253
        CREATE TABLE IF NOT EXISTS openclasp_account_settings (
254
          operator_id TEXT PRIMARY KEY,
255
          display_name TEXT NOT NULL DEFAULT '',
256
          contribution_enabled BOOLEAN NOT NULL DEFAULT FALSE,
257
          retention_days INTEGER NOT NULL DEFAULT 30 CHECK (retention_days BETWEEN 0 AND 3650),
258
          evidence_sharing TEXT NOT NULL DEFAULT 'ask'
259
            CHECK (evidence_sharing IN ('never', 'ask', 'contract_only')),
260
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
261
        )
262
      `;
263
      await this.sql`
264
        CREATE TABLE IF NOT EXISTS openclasp_public_agents (
265
          agent_id TEXT PRIMARY KEY,
266
          operator_id TEXT NOT NULL,
267
          card JSONB NOT NULL,
268
          published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
269
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
270
        )
271
      `;
272
      await this.sql`
273
        CREATE INDEX IF NOT EXISTS openclasp_public_agents_updated
274
        ON openclasp_public_agents(updated_at DESC)
275
      `;
276
      await this.sql`
277
        CREATE TABLE IF NOT EXISTS openclasp_federated_interactions (
278
          interaction_id TEXT PRIMARY KEY,
279
          initiator_operator_id TEXT NOT NULL,
280
          responder_operator_id TEXT NOT NULL,
281
          initiator_agent_id TEXT NOT NULL,
282
          responder_agent_id TEXT NOT NULL,
283
          status TEXT NOT NULL,
284
          payload JSONB NOT NULL,
285
          expires_at TIMESTAMPTZ NOT NULL,
286
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
287
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
288
        )
289
      `;
290
      await this.sql`
291
        CREATE INDEX IF NOT EXISTS openclasp_federated_interactions_participants
292
        ON openclasp_federated_interactions(initiator_operator_id, responder_operator_id, updated_at DESC)
293
      `;
294
      await this.sql`
295
        CREATE TABLE IF NOT EXISTS openclasp_agent_runtimes (
296
          agent_id TEXT PRIMARY KEY,
297
          operator_id TEXT NOT NULL,
298
          endpoint TEXT NOT NULL,
299
          secret_ciphertext TEXT NOT NULL,
300
          secret_iv TEXT NOT NULL,
301
          secret_auth_tag TEXT NOT NULL,
302
          status TEXT NOT NULL CHECK (status IN ('verified', 'disabled')),
303
          verified_at TIMESTAMPTZ NOT NULL,
304
          last_delivery_at TIMESTAMPTZ,
305
          last_error TEXT,
306
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
307
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
308
        )
309
      `;
310
      await this.sql`
311
        ALTER TABLE openclasp_agent_runtimes
312
        ADD COLUMN IF NOT EXISTS a2a_endpoint TEXT,
313
        ADD COLUMN IF NOT EXISTS last_seen_at TIMESTAMPTZ
314
      `;
315
      await this.sql`
316
        CREATE TABLE IF NOT EXISTS openclasp_live_sessions (
317
          interaction_id TEXT PRIMARY KEY,
318
          initiator_agent_id TEXT NOT NULL,
319
          responder_agent_id TEXT NOT NULL,
320
          initiator_session_id TEXT NOT NULL,
321
          responder_session_id TEXT NOT NULL,
322
          initiator_endpoint TEXT NOT NULL,
323
          responder_endpoint TEXT NOT NULL,
324
          status TEXT NOT NULL CHECK (status IN ('preparing', 'active', 'completed', 'failed')),
325
          expires_at TIMESTAMPTZ NOT NULL,
326
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
327
          activated_at TIMESTAMPTZ,
328
          completed_at TIMESTAMPTZ,
329
          last_error TEXT
330
        )
331
      `;
332
      await this.sql`
333
        CREATE TABLE IF NOT EXISTS openclasp_live_session_events (
334
          interaction_id TEXT NOT NULL,
335
          event_id TEXT NOT NULL,
336
          agent_id TEXT NOT NULL,
337
          sequence INTEGER NOT NULL,
338
          event JSONB NOT NULL,
339
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
340
          PRIMARY KEY (interaction_id, event_id),
341
          UNIQUE (interaction_id, agent_id, sequence)
342
        )
343
      `;
344
      await this.sql`
345
        CREATE TABLE IF NOT EXISTS openclasp_hosted_threads (
346
          thread_id TEXT PRIMARY KEY,
347
          interaction_id TEXT NOT NULL UNIQUE,
348
          participant_a_agent_id TEXT NOT NULL,
349
          participant_b_agent_id TEXT NOT NULL,
350
          status TEXT NOT NULL CHECK (status IN ('open', 'closed')) DEFAULT 'open',
351
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
352
          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
353
          expires_at TIMESTAMPTZ NOT NULL
354
        )
355
      `;
356
      await this.sql`
357
        CREATE INDEX IF NOT EXISTS openclasp_hosted_threads_participants
358
        ON openclasp_hosted_threads(participant_a_agent_id, participant_b_agent_id, updated_at DESC)
359
      `;
360
      await this.sql`
361
        CREATE TABLE IF NOT EXISTS openclasp_hosted_messages (
362
          message_id TEXT PRIMARY KEY,
363
          thread_id TEXT NOT NULL REFERENCES openclasp_hosted_threads(thread_id) ON DELETE CASCADE,
364
          interaction_id TEXT NOT NULL,
365
          sender_agent_id TEXT NOT NULL,
366
          recipient_agent_id TEXT NOT NULL,
367
          request_key TEXT NOT NULL,
368
          content_ciphertext TEXT NOT NULL,
369
          content_iv TEXT NOT NULL,
370
          content_auth_tag TEXT NOT NULL,
371
          content_hash TEXT NOT NULL,
372
          delivery TEXT NOT NULL CHECK (delivery IN ('accepted', 'delivered', 'read')),
373
          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
374
          read_at TIMESTAMPTZ
375
        )
376
      `;
377
      await this.sql`
378
        CREATE UNIQUE INDEX IF NOT EXISTS openclasp_hosted_messages_dedup
379
        ON openclasp_hosted_messages(thread_id, sender_agent_id, request_key)
380
      `;
381
      await this.sql`
382
        CREATE INDEX IF NOT EXISTS openclasp_hosted_messages_thread_created
383
        ON openclasp_hosted_messages(thread_id, created_at ASC)
384
      `;
385
    })());
386
  }
387
388
  getRuntimeVerificationKey() {
389
    return {
390
      algorithm: 'Ed25519' as const,
391
      keyId: getSessionKeyId(this.gatewaySecret()),
392
      publicKey: getSessionVerificationKey(this.gatewaySecret()),
393
    };
394
  }
395
396
  async upsert(
397
    operatorId: string,
398
    kind: HostedRecordKind,
399
    recordId: string,
400
    payload: unknown,
401
  ): Promise<void> {
402
    await this.ensureSchema();
403
    const encoded = JSON.stringify(payload);
404
    await this.sql`
405
      INSERT INTO openclasp_records(operator_id, kind, record_id, payload)
406
      VALUES (${operatorId}, ${kind}, ${recordId}, ${encoded}::jsonb)
407
      ON CONFLICT (operator_id, kind, record_id)
408
      DO UPDATE SET payload = EXCLUDED.payload, updated_at = NOW()
409
    `;
410
  }
411
412
  async list(
413
    operatorId: string,
414
  ): Promise<{ kind: HostedRecordKind; recordId: string; payload: any }[]> {
415
    await this.ensureSchema();
416
    const rows = await this.sql`
417
      SELECT kind, record_id, payload
418
      FROM openclasp_records
419
      WHERE operator_id = ${operatorId}
420
      ORDER BY created_at ASC
421
    `;
422
    return rows.map((row) => ({
423
      kind: row.kind as HostedRecordKind,
424
      recordId: String(row.record_id),
425
      payload: row.payload,
426
    }));
427
  }
428
429
  async dashboard(operatorId: string) {
430
    const rows = await this.list(operatorId);
431
    const [federatedInteractions, runtimes, liveSessionRows, liveEventRows] = await Promise.all([
432
      this.listFederatedInteractions(operatorId),
433
      this.listAgentRuntimes(operatorId),
434
      this.sql`
435
        SELECT session.interaction_id, session.initiator_agent_id, session.responder_agent_id,
436
          session.status, session.created_at, session.activated_at, session.completed_at,
437
          session.expires_at, session.last_error
438
        FROM openclasp_live_sessions session
439
        INNER JOIN openclasp_federated_interactions interaction
440
          ON interaction.interaction_id = session.interaction_id
441
        WHERE interaction.initiator_operator_id = ${operatorId}
442
           OR interaction.responder_operator_id = ${operatorId}
443
        ORDER BY session.created_at DESC
444
      `,
445
      this.sql`
446
        SELECT events.event
447
        FROM openclasp_live_session_events events
448
        INNER JOIN openclasp_federated_interactions interaction
449
          ON interaction.interaction_id = events.interaction_id
450
        WHERE interaction.initiator_operator_id = ${operatorId}
451
           OR interaction.responder_operator_id = ${operatorId}
452
        ORDER BY events.created_at ASC
453
      `,
454
    ]);
455
    const ofKind = (kind: HostedRecordKind) =>
456
      rows.filter((row) => row.kind === kind).map((row) => row.payload);
457
    const agentProfiles = ofKind('agent_profile') as AgentProfile[];
458
    const hostedThreads = (
459
      await Promise.all(
460
        agentProfiles
461
          .filter(
462
            (agent) =>
463
              (agent.agentMode ?? (agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat')) ===
464
              'temporary_chat',
465
          )
466
          .map((agent) => this.listHostedThreads(operatorId, agent.agentId)),
467
      )
468
    ).flat();
469
    const presence = new Map(
470
      rows
471
        .filter((row) => row.kind === 'presence')
472
        .map((row) => [row.recordId, String(row.payload.lastSeenAt)]),
473
    );
474
    return {
475
      agents: [...ofKind('agent_profile'), ...ofKind('agent')].map((agent) => ({
476
        ...agent,
477
        presence: resolveAgentPresence(presence.get(String(agent.agentId))),
478
      })),
479
      projects: ofKind('project'),
480
      installations: ofKind('installation'),
481
      setupRequests: ofKind('setup_request'),
482
      publications: ofKind('publication'),
483
      interactions: ofKind('interaction'),
484
      events: [...ofKind('event'), ...liveEventRows.map((row) => row.event)],
485
      conflicts: ofKind('conflict'),
486
      receipts: ofKind('receipt'),
487
      profiles: ofKind('profile'),
488
      federatedInteractions,
489
      liveSessions: liveSessionRows.map((row) => ({
490
        interactionId: String(row.interaction_id),
491
        initiatorAgentId: String(row.initiator_agent_id),
492
        responderAgentId: String(row.responder_agent_id),
493
        status: String(row.status),
494
        createdAt: new Date(String(row.created_at)).toISOString(),
495
        ...(row.activated_at
496
          ? { activatedAt: new Date(String(row.activated_at)).toISOString() }
497
          : {}),
498
        ...(row.completed_at
499
          ? { completedAt: new Date(String(row.completed_at)).toISOString() }
500
          : {}),
501
        expiresAt: new Date(String(row.expires_at)).toISOString(),
502
        ...(row.last_error ? { lastError: String(row.last_error) } : {}),
503
      })),
504
      hostedThreads,
505
      runtimes,
506
    };
507
  }
508
509
  async publishAgent(operatorId: string, card: PublicAgentCard): Promise<PublicAgentCard> {
510
    await this.ensureSchema();
511
    card = PublicAgentCardSchema.parse(card);
512
    const runtimes = await this.sql`
513
      SELECT a2a_endpoint, endpoint FROM openclasp_agent_runtimes
514
      WHERE operator_id = ${operatorId} AND agent_id = ${card.agentId} AND status = 'verified'
515
    `;
516
    if (runtimes[0]) {
517
      card = PublicAgentCardSchema.parse({
518
        ...card,
519
        agentMode: 'persistent_runtime',
520
        transports: [
521
          {
522
            protocol: 'A2A/1.0',
523
            protocolBinding: 'JSONRPC',
524
            endpoint: String(runtimes[0].a2a_endpoint ?? runtimes[0].endpoint),
525
            managedBy: 'agent',
526
          },
527
        ],
528
      });
529
    }
530
    const encoded = JSON.stringify(card);
531
    const rows = await this.sql`
532
      INSERT INTO openclasp_public_agents(agent_id, operator_id, card, published_at, updated_at)
533
      VALUES (${card.agentId}, ${operatorId}, ${encoded}::jsonb, NOW(), NOW())
534
      ON CONFLICT (agent_id) DO UPDATE SET
535
        card = EXCLUDED.card,
536
        updated_at = NOW()
537
      WHERE openclasp_public_agents.operator_id = ${operatorId}
538
      RETURNING card
539
    `;
540
    const published = rows[0]?.card as PublicAgentCard | undefined;
541
    if (!published) throw new Error('Agent ID is already owned by another operator');
542
    return published;
543
  }
544
545
  async unpublishAgent(operatorId: string, agentId: string): Promise<boolean> {
546
    await this.ensureSchema();
547
    const rows = await this.sql`
548
      DELETE FROM openclasp_public_agents
549
      WHERE agent_id = ${agentId} AND operator_id = ${operatorId}
550
      RETURNING agent_id
551
    `;
552
    return rows.length > 0;
553
  }
554
555
  async getPublishedAgent(agentId: string): Promise<PublicAgentCard | undefined> {
556
    await this.ensureSchema();
557
    const rows = await this.sql`
558
      SELECT agents.card, runtime.a2a_endpoint, runtime.endpoint, profile.payload AS profile
559
      FROM openclasp_public_agents agents
560
      LEFT JOIN openclasp_agent_runtimes runtime
561
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
562
      LEFT JOIN openclasp_records profile
563
        ON profile.operator_id = agents.operator_id AND profile.kind = 'agent_profile'
564
        AND profile.record_id = agents.agent_id
565
      WHERE agents.agent_id = ${agentId}
566
    `;
567
    if (!rows[0]?.card) return undefined;
568
    let card = normalizePublicAgentCard(rows[0].card);
569
    const profile = rows[0].profile as Partial<AgentProfile> | undefined;
570
    const mode =
571
      profile?.agentMode ??
572
      (rows[0].a2a_endpoint || rows[0].endpoint ? 'persistent_runtime' : 'temporary_chat');
573
    if (mode === 'temporary_chat') {
574
      const root = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
575
        /\/$/,
576
        '',
577
      );
578
      card = PublicAgentCardSchema.parse({
579
        ...card,
580
        agentMode: 'temporary_chat',
581
        transports: [
582
          {
583
            protocol: 'A2A/1.0',
584
            protocolBinding: 'JSONRPC',
585
            endpoint: `${root}/a2a/temporary/${encodeURIComponent(agentId)}`,
586
            managedBy: 'openclasp',
587
          },
588
        ],
589
      });
590
    } else if (rows[0].a2a_endpoint || rows[0].endpoint)
591
      card = PublicAgentCardSchema.parse({
592
        ...card,
593
        agentMode: 'persistent_runtime',
594
        transports: [
595
          {
596
            protocol: 'A2A/1.0',
597
            protocolBinding: 'JSONRPC',
598
            endpoint: String(rows[0].a2a_endpoint ?? rows[0].endpoint),
599
            managedBy: 'agent',
600
          },
601
        ],
602
      });
603
    return { ...card, presence: await this.getAgentPresence(agentId) };
604
  }
605
606
  async searchPublishedAgents(input: {
607
    query?: string | undefined;
608
    capability?: string | undefined;
609
    limit?: number | undefined;
610
  }): Promise<PublicAgentCard[]> {
611
    await this.ensureSchema();
612
    const rows = await this.sql`
613
      SELECT agents.card, runtime.a2a_endpoint, runtime.endpoint, profile.payload AS profile
614
      FROM openclasp_public_agents agents
615
      LEFT JOIN openclasp_agent_runtimes runtime
616
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
617
      LEFT JOIN openclasp_records profile
618
        ON profile.operator_id = agents.operator_id AND profile.kind = 'agent_profile'
619
        AND profile.record_id = agents.agent_id
620
      ORDER BY agents.updated_at DESC LIMIT 100
621
    `;
622
    const query = input.query?.trim().toLowerCase();
623
    const capability = input.capability?.trim().toLowerCase();
624
    const presenceRows = await this.sql`
625
      SELECT records.record_id, records.payload
626
      FROM openclasp_records records
627
      INNER JOIN openclasp_public_agents agents ON agents.agent_id = records.record_id
628
      WHERE records.kind = 'presence'
629
    `;
630
    const presence = new Map(
631
      presenceRows.map((row) => [String(row.record_id), String(row.payload.lastSeenAt)]),
632
    );
633
    return rows
634
      .map((row) => {
635
        let card = normalizePublicAgentCard(row.card);
636
        const profile = row.profile as Partial<AgentProfile> | undefined;
637
        const mode =
638
          profile?.agentMode ??
639
          (row.a2a_endpoint || row.endpoint ? 'persistent_runtime' : 'temporary_chat');
640
        if (mode === 'temporary_chat') {
641
          const root = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
642
            /\/$/,
643
            '',
644
          );
645
          card = PublicAgentCardSchema.parse({
646
            ...card,
647
            agentMode: 'temporary_chat',
648
            transports: [
649
              {
650
                protocol: 'A2A/1.0',
651
                protocolBinding: 'JSONRPC',
652
                endpoint: `${root}/a2a/temporary/${encodeURIComponent(card.agentId)}`,
653
                managedBy: 'openclasp',
654
              },
655
            ],
656
          });
657
        } else if (row.a2a_endpoint || row.endpoint)
658
          card = PublicAgentCardSchema.parse({
659
            ...card,
660
            agentMode: 'persistent_runtime',
661
            transports: [
662
              {
663
                protocol: 'A2A/1.0',
664
                protocolBinding: 'JSONRPC',
665
                endpoint: String(row.a2a_endpoint ?? row.endpoint),
666
                managedBy: 'agent',
667
              },
668
            ],
669
          });
670
        return { ...card, presence: resolveAgentPresence(presence.get(card.agentId)) };
671
      })
672
      .filter(
673
        (card) =>
674
          (!query ||
675
            card.name.toLowerCase().includes(query) ||
676
            card.framework.toLowerCase().includes(query)) &&
677
          (!capability ||
678
            card.capabilities.some((value) => value.toLowerCase().includes(capability))),
679
      )
680
      .slice(0, Math.min(Math.max(input.limit ?? 20, 1), 50));
681
  }
682
683
  async touchAgentPresence(operatorId: string, agentId: string): Promise<AgentPresence> {
684
    await this.ensureSchema();
685
    const owned = await this.sql`
686
      SELECT 1 FROM openclasp_records
687
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
688
    `;
689
    if (!owned.length) throw new Error('Agent is not owned by this account');
690
    const lastSeenAt = new Date().toISOString();
691
    await this.upsert(operatorId, 'presence', agentId, { lastSeenAt });
692
    await this.sql`
693
      UPDATE openclasp_agent_runtimes SET last_seen_at = ${lastSeenAt}, updated_at = NOW()
694
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId} AND status = 'verified'
695
    `;
696
    return resolveAgentPresence(lastSeenAt);
697
  }
698
699
  async getAgentPresence(agentId: string): Promise<AgentPresence> {
700
    await this.ensureSchema();
701
    const rows = await this.sql`
702
      SELECT records.payload
703
      FROM openclasp_public_agents agents
704
      LEFT JOIN openclasp_records records
705
        ON records.operator_id = agents.operator_id
706
        AND records.kind = 'presence'
707
        AND records.record_id = agents.agent_id
708
      WHERE agents.agent_id = ${agentId}
709
      LIMIT 1
710
    `;
711
    if (!rows.length) throw new Error('Published agent not found');
712
    const lastSeenAt = rows[0]?.payload?.lastSeenAt;
713
    return resolveAgentPresence(typeof lastSeenAt === 'string' ? lastSeenAt : undefined);
714
  }
715
716
  async listAgentRuntimes(operatorId: string) {
717
    await this.ensureSchema();
718
    const rows = await this.sql`
719
      SELECT agent_id, endpoint, a2a_endpoint, status, verified_at, last_seen_at, last_error, updated_at
720
      FROM openclasp_agent_runtimes
721
      WHERE operator_id = ${operatorId}
722
      ORDER BY updated_at DESC
723
    `;
724
    return rows.map((row) => ({
725
      agentId: String(row.agent_id),
726
      endpoint: String(row.endpoint),
727
      a2aEndpoint: String(row.a2a_endpoint ?? row.endpoint),
728
      status: row.status as 'verified' | 'disabled',
729
      verifiedAt: new Date(String(row.verified_at)).toISOString(),
730
      ...(row.last_seen_at ? { lastSeenAt: new Date(String(row.last_seen_at)).toISOString() } : {}),
731
      ...(row.last_error ? { lastError: String(row.last_error) } : {}),
732
      updatedAt: new Date(String(row.updated_at)).toISOString(),
733
    }));
734
  }
735
736
  async registerAgentRuntime(operatorId: string, agentId: string, endpoint: string) {
737
    await this.ensureSchema();
738
    const owned = await this.sql`
739
      SELECT 1 FROM openclasp_records
740
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
741
    `;
742
    if (!owned.length) throw new Error('Agent is not owned by this account');
743
    const challenge = crypto.randomUUID();
744
    const verification = await postRuntimeJson(endpoint, {
745
      type: 'openclasp.runtime.verify',
746
      version: '1',
747
      agentId,
748
      challenge,
749
    });
750
    if (
751
      verification.status < 200 ||
752
      verification.status >= 300 ||
753
      !verification.body ||
754
      typeof verification.body !== 'object' ||
755
      (verification.body as { type?: unknown }).type !== 'openclasp.runtime.verified' ||
756
      (verification.body as { version?: unknown }).version !== '1' ||
757
      (verification.body as { agentId?: unknown }).agentId !== agentId ||
758
      (verification.body as { challenge?: unknown }).challenge !== challenge
759
    )
760
      throw new Error('Runtime endpoint did not return the verification challenge');
761
    const a2aEndpointValue = (verification.body as { a2aEndpoint?: unknown }).a2aEndpoint;
762
    const a2aEndpoint =
763
      typeof a2aEndpointValue === 'string' && a2aEndpointValue ? a2aEndpointValue : endpoint;
764
    await resolvePublicRuntimeEndpoint(a2aEndpoint);
765
    const runtimeSecret = randomBytes(32).toString('base64url');
766
    const encrypted = encryptGatewayPayload(this.gatewaySecret(), runtimeSecret);
767
    const verifiedAt = new Date().toISOString();
768
    const saved = await this.sql`
769
      INSERT INTO openclasp_agent_runtimes(
770
        agent_id, operator_id, endpoint, a2a_endpoint, secret_ciphertext, secret_iv, secret_auth_tag,
771
        status, verified_at, last_seen_at, updated_at
772
      ) VALUES (
773
        ${agentId}, ${operatorId}, ${endpoint}, ${a2aEndpoint}, ${encrypted.ciphertext},
774
        ${encrypted.iv}, ${encrypted.authTag}, 'verified', ${verifiedAt}, ${verifiedAt}, NOW()
775
      )
776
      ON CONFLICT (agent_id) DO UPDATE SET
777
        operator_id = EXCLUDED.operator_id,
778
        endpoint = EXCLUDED.endpoint,
779
        a2a_endpoint = EXCLUDED.a2a_endpoint,
780
        secret_ciphertext = EXCLUDED.secret_ciphertext,
781
        secret_iv = EXCLUDED.secret_iv,
782
        secret_auth_tag = EXCLUDED.secret_auth_tag,
783
        status = 'verified',
784
        verified_at = EXCLUDED.verified_at,
785
        last_seen_at = EXCLUDED.last_seen_at,
786
        last_error = NULL,
787
        updated_at = NOW()
788
      WHERE openclasp_agent_runtimes.operator_id = ${operatorId}
789
      RETURNING agent_id
790
    `;
791
    if (!saved.length) throw new Error('Agent runtime is owned by another account');
792
    await this.sql`
793
      UPDATE openclasp_public_agents
794
      SET card = jsonb_set(
795
          jsonb_set(
796
            card,
797
            '{transports}',
798
            ${JSON.stringify([
799
              {
800
                protocol: 'A2A/1.0',
801
                protocolBinding: 'JSONRPC',
802
                endpoint: a2aEndpoint,
803
                managedBy: 'agent',
804
              },
805
            ])}::jsonb
806
          ),
807
          '{agentMode}', '"persistent_runtime"'::jsonb
808
        ), updated_at = NOW()
809
      WHERE agent_id = ${agentId} AND operator_id = ${operatorId}
810
    `;
811
    await this.sql`
812
      UPDATE openclasp_records
813
      SET payload = jsonb_set(
814
          jsonb_set(payload, '{a2aEndpoint}', to_jsonb(${a2aEndpoint}::text)),
815
          '{agentMode}', '"persistent_runtime"'::jsonb
816
        ),
817
        updated_at = NOW()
818
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
819
    `;
820
    await this.touchAgentPresence(operatorId, agentId);
821
    return {
822
      agentId,
823
      endpoint,
824
      a2aEndpoint,
825
      status: 'verified' as const,
826
      verifiedAt,
827
      verificationKey: getSessionVerificationKey(this.gatewaySecret()),
828
    };
829
  }
830
831
  async disableAgentRuntime(operatorId: string, agentId: string) {
832
    await this.ensureSchema();
833
    const rows = await this.sql`
834
      UPDATE openclasp_agent_runtimes
835
      SET status = 'disabled', updated_at = NOW()
836
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
837
      RETURNING agent_id
838
    `;
839
    if (!rows.length) throw new Error('Agent runtime not found');
840
    return { agentId, status: 'disabled' as const };
841
  }
842
843
  async deleteAgent(operatorId: string, agentId: string) {
844
    await this.ensureSchema();
845
    const owned = await this.sql`
846
      SELECT 1 FROM openclasp_records
847
      WHERE operator_id = ${operatorId}
848
        AND kind = 'agent_profile'
849
        AND record_id = ${agentId}
850
      LIMIT 1
851
    `;
852
    if (!owned.length) throw new Error('Owned agent not found');
853
    const openInteractions = await this.sql`
854
      SELECT interaction_id FROM openclasp_federated_interactions
855
      WHERE (initiator_agent_id = ${agentId} OR responder_agent_id = ${agentId})
856
        AND status IN ('pending', 'active')
857
      LIMIT 1
858
    `;
859
    if (openInteractions.length) {
860
      const error = new Error('Finish or reject the agent’s open interactions before deleting it');
861
      Object.assign(error, { statusCode: 409 });
862
      throw error;
863
    }
864
    await this.sql`
865
      DELETE FROM openclasp_hosted_threads
866
      WHERE participant_a_agent_id = ${agentId} OR participant_b_agent_id = ${agentId}
867
    `;
868
    await this.sql`
869
      DELETE FROM openclasp_public_agents
870
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
871
    `;
872
    await this.sql`
873
      DELETE FROM openclasp_agent_runtimes
874
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
875
    `;
876
    await this.sql`
877
      DELETE FROM openclasp_records
878
      WHERE operator_id = ${operatorId}
879
        AND (
880
          (record_id = ${agentId} AND kind IN ('agent', 'agent_profile', 'publication', 'presence'))
881
          OR (kind = 'installation' AND payload->>'agentId' = ${agentId})
882
          OR (kind = 'setup_request' AND payload->>'existingAgentId' = ${agentId})
883
        )
884
    `;
885
    return {
886
      agentId,
887
      deleted: true as const,
888
      historyRetained: true as const,
889
    };
890
  }
891
892
  private async sessionParticipant(agentId: string) {
893
    const rows = await this.sql`
894
      SELECT agents.operator_id, agents.card, profile.payload AS profile,
895
        runtime.endpoint, runtime.a2a_endpoint
896
      FROM openclasp_public_agents agents
897
      LEFT JOIN openclasp_records profile
898
        ON profile.operator_id = agents.operator_id
899
        AND profile.kind = 'agent_profile'
900
        AND profile.record_id = agents.agent_id
901
      LEFT JOIN openclasp_agent_runtimes runtime
902
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
903
      WHERE agents.agent_id = ${agentId}
904
      LIMIT 1
905
    `;
906
    const row = rows[0];
907
    if (!row) throw new Error(`Published agent ${agentId} was not found`);
908
    const card = normalizePublicAgentCard(row.card);
909
    const profile = row.profile as Partial<AgentProfile> | undefined;
910
    const mode =
911
      profile?.agentMode ??
912
      (row.endpoint || row.a2a_endpoint ? 'persistent_runtime' : 'temporary_chat');
913
    if (mode === 'persistent_runtime' && !row.endpoint)
914
      throw new Error(`Agent ${agentId} does not have a verified live runtime`);
915
    const baseUrl = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
916
      /\/$/,
917
      '',
918
    );
919
    return {
920
      agentId,
921
      operatorId: String(row.operator_id),
922
      mode: mode as 'persistent_runtime' | 'temporary_chat',
923
      ...(row.endpoint ? { callbackEndpoint: String(row.endpoint) } : {}),
924
      a2aEndpoint:
925
        mode === 'temporary_chat'
926
          ? `${baseUrl}/a2a/temporary/${encodeURIComponent(agentId)}`
927
          : String(row.a2a_endpoint ?? row.endpoint),
928
      card: PublicAgentCardSchema.parse({ ...card, agentMode: mode }),
929
    };
930
  }
931
932
  private async signedRuntimeRequest(
933
    runtime: { callbackEndpoint: string },
934
    requestId: string,
935
    value: unknown,
936
  ) {
937
    const body = JSON.stringify(value);
938
    const timestamp = new Date().toISOString();
939
    return postRuntimeJson(runtime.callbackEndpoint, value, {
940
      'openclasp-request-id': requestId,
941
      'openclasp-timestamp': timestamp,
942
      'openclasp-signature': `v1=${signSessionControl(this.gatewaySecret(), requestId, timestamp, body)}`,
943
    });
944
  }
945
946
  private sessionGrant(
947
    interaction: FederatedInteraction,
948
    senderAgentId: string,
949
    recipientAgentId: string,
950
  ) {
951
    return issueSessionGrant(this.gatewaySecret(), {
952
      interactionId: interaction.interactionId,
953
      senderAgentId,
954
      recipientAgentId,
955
      expiresAt: Math.min(Date.parse(interaction.expiresAt), Date.now() + 60 * 60_000),
956
    });
957
  }
958
959
  private async privateCounterpartyInsights(
960
    viewerOperatorId: string,
961
    counterparty: { agentId: string; card: PublicAgentCard },
962
    taskCategory: string,
963
  ): Promise<LiveSessionInsight[]> {
964
    const rows = await this.sql`
965
      SELECT record_id, payload
966
      FROM openclasp_records
967
      WHERE operator_id = ${viewerOperatorId}
968
        AND kind = 'profile'
969
        AND payload->>'agentId' = ${counterparty.agentId}
970
        AND payload->>'taskCategory' = ${taskCategory}
971
      ORDER BY (payload->>'sampleSize')::integer DESC, updated_at DESC
972
    `;
973
    const profiles: ContextualProfile[] = rows
974
      .map<Record<string, unknown>>((row) => ({
975
        recordId: String(row.record_id),
976
        ...(row.payload as Record<string, unknown>),
977
      }))
978
      .filter(
979
        (profile) =>
980
          typeof profile.agentVersion === 'string' &&
981
          typeof profile.sampleSize === 'number' &&
982
          typeof profile.updatedAt === 'string' &&
983
          typeof profile.completion === 'number' &&
984
          typeof profile.acceptance === 'number' &&
985
          typeof profile.specification === 'number' &&
986
          typeof profile.deadline === 'number' &&
987
          typeof profile.communication === 'number' &&
988
          typeof profile.evidence === 'number' &&
989
          typeof profile.scope === 'number' &&
990
          typeof profile.disputes === 'number',
991
      ) as ContextualProfile[];
992
    const exact = profiles.find(
993
      (profile) => profile.agentVersion === counterparty.card.agentVersion,
994
    );
995
    const current = exact ?? profiles[0];
996
    const insights: LiveSessionInsight[] = [];
997
    if (!current) {
998
      insights.push({
999
        code: 'limited_verified_history',
1000
        severity: 'caution',
1001
        message: `No eligible ${taskCategory} history is available for this agent version. Ask for task-relevant evidence.`,
1002
        evidenceReferences: [],
1003
      });
1004
    } else {
1005
      const ageDays = Math.max(
1006
        0,
1007
        (Date.now() - Date.parse(String(current.updatedAt))) / 86_400_000,
1008
      );
1009
      const freshness = Math.exp(-ageDays / 180);
1010
      const sampleSize = Number(current.sampleSize);
1011
      const confidence = Math.min(0.95, (sampleSize / (sampleSize + 5)) * freshness);
1012
      const versionChanged = current.agentVersion !== counterparty.card.agentVersion;
1013
      const reference = `openclasp:profile:${current.recordId}`;
1014
      insights.push({
1015
        code: versionChanged ? 'version_history_only' : 'contextual_history',
1016
        severity: versionChanged || confidence < 0.25 ? 'caution' : 'info',
1017
        message: versionChanged
1018
          ? `Only prior-version ${taskCategory} history is available (${sampleSize} eligible interaction${sampleSize === 1 ? '' : 's'}); confidence is reduced for version ${counterparty.card.agentVersion}.`
1019
          : `Based on ${sampleSize} eligible ${taskCategory} interaction${sampleSize === 1 ? '' : 's'}; confidence ${(confidence * 100).toFixed(0)}%.`,
1020
        evidenceReferences: [reference],
1021
      });
1022
      const weakDimensions = [
1023
        ['completion', Number(current.completion)],
1024
        ['output acceptance', Number(current.acceptance)],
1025
        ['specification adherence', Number(current.specification)],
1026
        ['deadline reliability', Number(current.deadline)],
1027
        ['communication quality', Number(current.communication)],
1028
        ['evidence quality', Number(current.evidence)],
1029
        ['scope adherence', Number(current.scope)],
1030
      ].filter(([, score]) => Number(score) < 0.7);
1031
      if (weakDimensions.length)
1032
        insights.push({
1033
          code: 'historical_weaknesses',
1034
          severity: weakDimensions.some(([, score]) => Number(score) < 0.5) ? 'high' : 'caution',
1035
          message: `Observed weaker areas: ${weakDimensions
1036
            .map(([name, score]) => `${String(name)} ${(Number(score) * 100).toFixed(0)}%`)
1037
            .join(', ')}.`,
1038
          evidenceReferences: [reference],
1039
        });
1040
      if (Number(current.disputes) > 0.25)
1041
        insights.push({
1042
          code: 'elevated_dispute_history',
1043
          severity: Number(current.disputes) >= 0.5 ? 'high' : 'caution',
1044
          message: `Eligible feedback shows a ${(Number(current.disputes) * 100).toFixed(0)}% dispute rate in this task category.`,
1045
          evidenceReferences: [reference],
1046
        });
1047
    }
1048
    if (counterparty.card.limitations.length)
1049
      insights.push({
1050
        code: 'declared_limitations',
1051
        severity: 'info',
1052
        message: `Counterparty declares: ${counterparty.card.limitations.join('; ')}`,
1053
        evidenceReferences: [counterparty.card.cardUrl],
1054
      });
1055
    return insights;
1056
  }
1057
1058
  async brokerLiveSession(interaction: FederatedInteraction) {
1059
    await this.ensureSchema();
1060
    const existing = await this.sql`
1061
      SELECT status FROM openclasp_live_sessions
1062
      WHERE interaction_id = ${interaction.interactionId}
1063
    `;
1064
    if (existing[0]?.status === 'active') return;
1065
    const [initiator, responder] = await Promise.all([
1066
      this.sessionParticipant(interaction.initiatorAgentId),
1067
      this.sessionParticipant(interaction.responderAgentId),
1068
    ]);
1069
    if (initiator.mode === 'temporary_chat' && responder.mode === 'temporary_chat')
1070
      throw new Error('Temporary-to-temporary hosted conversations are not supported in this MVP');
1071
    const [initiatorInsights, responderInsights] = await Promise.all([
1072
      this.privateCounterpartyInsights(
1073
        initiator.operatorId,
1074
        responder,
1075
        interaction.contract.taskCategory,
1076
      ),
1077
      this.privateCounterpartyInsights(
1078
        responder.operatorId,
1079
        initiator,
1080
        interaction.contract.taskCategory,
1081
      ),
1082
    ]);
1083
    const issuedAt = new Date().toISOString();
1084
    const makeOffer = (
1085
      runtime: typeof initiator,
1086
      counterparty: typeof responder,
1087
      role: 'initiator' | 'responder',
1088
      privateInsights: LiveSessionInsight[],
1089
    ) =>
1090
      LiveSessionOfferSchema.parse({
1091
        type: 'openclasp.session.offer',
1092
        version: '1',
1093
        offerId: crypto.randomUUID(),
1094
        interactionId: interaction.interactionId,
1095
        agentId: runtime.agentId,
1096
        role,
1097
        counterparty: {
1098
          agentId: counterparty.agentId,
1099
          name: counterparty.card.name,
1100
          agentVersion: counterparty.card.agentVersion,
1101
          capabilities: counterparty.card.capabilities,
1102
        },
1103
        contract: interaction.contract,
1104
        contractHash: interaction.termsHash,
1105
        privateInsights,
1106
        issuedAt,
1107
        expiresAt: interaction.expiresAt,
1108
      });
1109
    const initiatorOffer = makeOffer(initiator, responder, 'initiator', initiatorInsights);
1110
    const responderOffer = makeOffer(responder, initiator, 'responder', responderInsights);
1111
    const prepare = async (
1112
      participant: typeof initiator,
1113
      offer: typeof initiatorOffer,
1114
      label: 'Initiator' | 'Responder',
1115
    ) => {
1116
      if (participant.mode === 'temporary_chat')
1117
        return LiveSessionAcceptanceSchema.parse({
1118
          type: 'openclasp.session.accepted',
1119
          version: '1',
1120
          offerId: offer.offerId,
1121
          interactionId: interaction.interactionId,
1122
          agentId: participant.agentId,
1123
          sessionId: crypto.randomUUID(),
1124
          a2aEndpoint: participant.a2aEndpoint,
1125
          expiresAt: interaction.expiresAt,
1126
        });
1127
      if (!participant.callbackEndpoint) throw new Error(`${label} runtime is not configured`);
1128
      const response = await this.signedRuntimeRequest(
1129
        { callbackEndpoint: participant.callbackEndpoint },
1130
        offer.offerId,
1131
        offer,
1132
      );
1133
      if (response.status < 200 || response.status >= 300)
1134
        throw new Error(`${label} runtime is not live (HTTP ${response.status})`);
1135
      return LiveSessionAcceptanceSchema.parse(response.body);
1136
    };
1137
    const [initiatorAcceptance, responderAcceptance] = await Promise.all([
1138
      prepare(initiator, initiatorOffer, 'Initiator'),
1139
      prepare(responder, responderOffer, 'Responder'),
1140
    ]);
1141
    if (
1142
      initiatorAcceptance.offerId !== initiatorOffer.offerId ||
1143
      initiatorAcceptance.agentId !== initiator.agentId ||
1144
      responderAcceptance.offerId !== responderOffer.offerId ||
1145
      responderAcceptance.agentId !== responder.agentId
1146
    )
1147
      throw new Error('Runtime returned a mismatched live-session acceptance');
1148
    await Promise.all([
1149
      ...(initiator.mode === 'persistent_runtime'
1150
        ? [resolvePublicRuntimeEndpoint(initiatorAcceptance.a2aEndpoint)]
1151
        : []),
1152
      ...(responder.mode === 'persistent_runtime'
1153
        ? [resolvePublicRuntimeEndpoint(responderAcceptance.a2aEndpoint)]
1154
        : []),
1155
    ]);
1156
    await this.sql`
1157
      INSERT INTO openclasp_live_sessions(
1158
        interaction_id, initiator_agent_id, responder_agent_id,
1159
        initiator_session_id, responder_session_id,
1160
        initiator_endpoint, responder_endpoint, status, expires_at
1161
      ) VALUES (
1162
        ${interaction.interactionId}, ${interaction.initiatorAgentId}, ${interaction.responderAgentId},
1163
        ${initiatorAcceptance.sessionId}, ${responderAcceptance.sessionId},
1164
        ${initiatorAcceptance.a2aEndpoint}, ${responderAcceptance.a2aEndpoint},
1165
        'preparing', ${interaction.expiresAt}
1166
      )
1167
      ON CONFLICT (interaction_id) DO UPDATE SET
1168
        initiator_session_id = EXCLUDED.initiator_session_id,
1169
        responder_session_id = EXCLUDED.responder_session_id,
1170
        initiator_endpoint = EXCLUDED.initiator_endpoint,
1171
        responder_endpoint = EXCLUDED.responder_endpoint,
1172
        status = 'preparing', expires_at = EXCLUDED.expires_at, last_error = NULL
1173
    `;
1174
    const baseUrl = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
1175
      /\/$/,
1176
      '',
1177
    );
1178
    const activatedAt = new Date().toISOString();
1179
    const verificationKey = getSessionVerificationKey(this.gatewaySecret());
1180
    const makeActivation = (
1181
      agentId: string,
1182
      sessionId: string,
1183
      role: 'initiator' | 'responder',
1184
      peerAgentId: string,
1185
      peerSessionId: string,
1186
      peerEndpoint: string,
1187
      privateInsights: LiveSessionInsight[],
1188
    ): LiveSessionActivation => {
1189
      const bearerToken = this.sessionGrant(interaction, agentId, peerAgentId);
1190
      return LiveSessionActivationSchema.parse({
1191
        type: 'openclasp.session.activation',
1192
        version: '1',
1193
        activationId: crypto.randomUUID(),
1194
        interactionId: interaction.interactionId,
1195
        agentId,
1196
        sessionId,
1197
        role,
1198
        peer: {
1199
          agentId: peerAgentId,
1200
          sessionId: peerSessionId,
1201
          endpoint: peerEndpoint,
1202
          bearerToken,
1203
          verificationKey,
1204
        },
1205
        reporting: {
1206
          endpoint: `${baseUrl}/sessions/${encodeURIComponent(interaction.interactionId)}/events`,
1207
          bearerToken,
1208
        },
1209
        privateInsights,
1210
        contractHash: interaction.termsHash,
1211
        activatedAt,
1212
        expiresAt: interaction.expiresAt,
1213
      });
1214
    };
1215
    const initiatorActivation = makeActivation(
1216
      initiator.agentId,
1217
      initiatorAcceptance.sessionId,
1218
      'initiator',
1219
      responder.agentId,
1220
      responderAcceptance.sessionId,
1221
      responderAcceptance.a2aEndpoint,
1222
      initiatorInsights,
1223
    );
1224
    const responderActivation = makeActivation(
1225
      responder.agentId,
1226
      responderAcceptance.sessionId,
1227
      'responder',
1228
      initiator.agentId,
1229
      initiatorAcceptance.sessionId,
1230
      initiatorAcceptance.a2aEndpoint,
1231
      responderInsights,
1232
    );
1233
    try {
1234
      const activate = async (
1235
        participant: typeof initiator,
1236
        activation: LiveSessionActivation,
1237
        label: 'Initiator' | 'Responder',
1238
      ) => {
1239
        if (participant.mode === 'temporary_chat') return;
1240
        if (!participant.callbackEndpoint) throw new Error(`${label} runtime is not configured`);
1241
        const response = await this.signedRuntimeRequest(
1242
          { callbackEndpoint: participant.callbackEndpoint },
1243
          activation.activationId,
1244
          activation,
1245
        );
1246
        if (response.status < 200 || response.status >= 300)
1247
          throw new Error(`${label} activation failed with HTTP ${response.status}`);
1248
      };
1249
      await activate(responder, responderActivation, 'Responder');
1250
      await activate(initiator, initiatorActivation, 'Initiator');
1251
      await this.sql`
1252
        UPDATE openclasp_live_sessions
1253
        SET status = 'active', activated_at = NOW(), last_error = NULL
1254
        WHERE interaction_id = ${interaction.interactionId}
1255
      `;
1256
      await this.sql`
1257
        UPDATE openclasp_agent_runtimes
1258
        SET last_seen_at = NOW(), last_error = NULL, updated_at = NOW()
1259
        WHERE agent_id IN (${initiator.agentId}, ${responder.agentId})
1260
      `;
1261
      await Promise.all([
1262
        this.touchAgentPresence(initiator.operatorId, initiator.agentId),
1263
        this.touchAgentPresence(responder.operatorId, responder.agentId),
1264
      ]);
1265
    } catch (error) {
1266
      const reason =
1267
        error instanceof Error ? error.message.slice(0, 500) : 'Session activation failed';
1268
      await this.sql`
1269
        UPDATE openclasp_live_sessions SET status = 'failed', last_error = ${reason}
1270
        WHERE interaction_id = ${interaction.interactionId}
1271
      `;
1272
      throw error;
1273
    }
1274
  }
1275
1276
  async getLiveSession(operatorId: string, interactionId: string, agentId: string) {
1277
    await this.ensureSchema();
1278
    const rows = await this.sql`
1279
      SELECT session.*, interaction.payload,
1280
        initiator.operator_id AS initiator_operator_id,
1281
        responder.operator_id AS responder_operator_id
1282
      FROM openclasp_live_sessions session
1283
      INNER JOIN openclasp_federated_interactions interaction
1284
        ON interaction.interaction_id = session.interaction_id
1285
      INNER JOIN openclasp_public_agents initiator
1286
        ON initiator.agent_id = session.initiator_agent_id
1287
      INNER JOIN openclasp_public_agents responder
1288
        ON responder.agent_id = session.responder_agent_id
1289
      WHERE session.interaction_id = ${interactionId} AND session.status = 'active'
1290
      LIMIT 1
1291
    `;
1292
    const row = rows[0];
1293
    if (!row) throw new Error('Active live session not found');
1294
    const isInitiator = row.initiator_agent_id === agentId;
1295
    const isResponder = row.responder_agent_id === agentId;
1296
    if (!isInitiator && !isResponder) throw new Error('Agent is not a session participant');
1297
    const owner = isInitiator ? row.initiator_operator_id : row.responder_operator_id;
1298
    if (owner !== operatorId) throw new Error('Agent is not owned by this account');
1299
    const interaction = FederatedInteractionSchema.parse(row.payload);
1300
    const peerAgentId = String(isInitiator ? row.responder_agent_id : row.initiator_agent_id);
1301
    const peer = await this.sessionParticipant(peerAgentId);
1302
    const privateInsights = await this.privateCounterpartyInsights(
1303
      String(owner),
1304
      peer,
1305
      interaction.contract.taskCategory,
1306
    );
1307
    const bearerToken = this.sessionGrant(interaction, agentId, peerAgentId);
1308
    return {
1309
      type: 'openclasp.session.activation' as const,
1310
      version: '1' as const,
1311
      activationId: crypto.randomUUID(),
1312
      interactionId,
1313
      agentId,
1314
      sessionId: String(isInitiator ? row.initiator_session_id : row.responder_session_id),
1315
      role: isInitiator ? ('initiator' as const) : ('responder' as const),
1316
      peer: {
1317
        agentId: peerAgentId,
1318
        sessionId: String(isInitiator ? row.responder_session_id : row.initiator_session_id),
1319
        endpoint: String(isInitiator ? row.responder_endpoint : row.initiator_endpoint),
1320
        bearerToken,
1321
        verificationKey: getSessionVerificationKey(this.gatewaySecret()),
1322
      },
1323
      reporting: {
1324
        endpoint: `${(process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(/\/$/, '')}/sessions/${encodeURIComponent(interactionId)}/events`,
1325
        bearerToken,
1326
      },
1327
      privateInsights,
1328
      contractHash: interaction.termsHash,
1329
      activatedAt: row.activated_at
1330
        ? new Date(String(row.activated_at)).toISOString()
1331
        : new Date().toISOString(),
1332
      expiresAt: new Date(String(row.expires_at)).toISOString(),
1333
    };
1334
  }
1335
1336
  private async ownedTemporaryAgent(operatorId: string, agentId: string) {
1337
    const rows = await this.sql`
1338
      SELECT payload FROM openclasp_records
1339
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
1340
      LIMIT 1
1341
    `;
1342
    const profile = rows[0]?.payload as Partial<AgentProfile> | undefined;
1343
    if (!profile) throw new Error('Agent is not owned by this account');
1344
    const mode =
1345
      profile.agentMode ?? (profile.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat');
1346
    if (mode !== 'temporary_chat')
1347
      throw new Error('Hosted conversations are available only to temporary chat agents');
1348
    return profile;
1349
  }
1350
1351
  private hostedMessage(row: Record<string, any>): HostedMessage {
1352
    const decrypted = decryptGatewayPayload(this.gatewaySecret(), {
1353
      ciphertext: String(row.content_ciphertext),
1354
      iv: String(row.content_iv),
1355
      authTag: String(row.content_auth_tag),
1356
    }) as { content?: unknown };
1357
    return HostedMessageSchema.parse({
1358
      messageId: String(row.message_id),
1359
      threadId: String(row.thread_id),
1360
      interactionId: String(row.interaction_id),
1361
      senderAgentId: String(row.sender_agent_id),
1362
      recipientAgentId: String(row.recipient_agent_id),
1363
      contentType: 'text/plain',
1364
      content: decrypted.content,
1365
      contentHash: String(row.content_hash),
1366
      delivery: row.delivery,
1367
      createdAt: new Date(String(row.created_at)).toISOString(),
1368
      ...(row.read_at ? { readAt: new Date(String(row.read_at)).toISOString() } : {}),
1369
    });
1370
  }
1371
1372
  private async storeHostedMessage(input: {
1373
    interactionId: string;
1374
    senderAgentId: string;
1375
    recipientAgentId: string;
1376
    requestKey: string;
1377
    content: string;
1378
    delivery: 'accepted' | 'delivered';
1379
  }) {
1380
    const content = input.content.trim();
1381
    if (!content || content.length > 20_000)
1382
      throw new Error('Message must contain 1-20000 characters');
1383
    const sessions = await this.sql`
1384
      SELECT session.status, interaction.status AS interaction_status,
1385
        session.initiator_agent_id, session.responder_agent_id
1386
      FROM openclasp_live_sessions session
1387
      INNER JOIN openclasp_federated_interactions interaction
1388
        ON interaction.interaction_id = session.interaction_id
1389
      WHERE session.interaction_id = ${input.interactionId}
1390
      LIMIT 1
1391
    `;
1392
    const session = sessions[0];
1393
    if (!session || session.status !== 'active' || session.interaction_status !== 'active')
1394
      throw new Error('Active interaction not found');
1395
    const participants = new Set([
1396
      String(session.initiator_agent_id),
1397
      String(session.responder_agent_id),
1398
    ]);
1399
    if (!participants.has(input.senderAgentId) || !participants.has(input.recipientAgentId))
1400
      throw new Error('Message participants do not match the active interaction');
1401
    const now = new Date();
1402
    const threadId = input.interactionId;
1403
    const expiresAt = new Date(now.getTime() + 30 * 86_400_000).toISOString();
1404
    await this.sql`
1405
      INSERT INTO openclasp_hosted_threads(
1406
        thread_id, interaction_id, participant_a_agent_id, participant_b_agent_id,
1407
        status, expires_at
1408
      ) VALUES (
1409
        ${threadId}, ${input.interactionId}, ${String(session.initiator_agent_id)},
1410
        ${String(session.responder_agent_id)}, 'open', ${expiresAt}
1411
      )
1412
      ON CONFLICT (thread_id) DO UPDATE SET updated_at = NOW()
1413
      WHERE openclasp_hosted_threads.status = 'open'
1414
    `;
1415
    const thread = await this.sql`
1416
      SELECT status, expires_at FROM openclasp_hosted_threads WHERE thread_id = ${threadId}
1417
    `;
1418
    if (thread[0]?.status !== 'open') throw new Error('Hosted thread is closed');
1419
    if (Date.parse(String(thread[0].expires_at)) <= Date.now())
1420
      throw new Error('Hosted thread has expired');
1421
    const encrypted = encryptGatewayPayload(this.gatewaySecret(), { content });
1422
    const messageId = crypto.randomUUID();
1423
    const contentHash = canonicalHash(content);
1424
    const inserted = await this.sql`
1425
      INSERT INTO openclasp_hosted_messages(
1426
        message_id, thread_id, interaction_id, sender_agent_id, recipient_agent_id,
1427
        request_key, content_ciphertext, content_iv, content_auth_tag, content_hash, delivery
1428
      ) VALUES (
1429
        ${messageId}, ${threadId}, ${input.interactionId}, ${input.senderAgentId},
1430
        ${input.recipientAgentId}, ${input.requestKey}, ${encrypted.ciphertext}, ${encrypted.iv},
1431
        ${encrypted.authTag}, ${contentHash}, ${input.delivery}
1432
      )
1433
      ON CONFLICT (thread_id, sender_agent_id, request_key) DO NOTHING
1434
      RETURNING *
1435
    `;
1436
    if (!inserted[0]) {
1437
      const existing = await this.sql`
1438
        SELECT * FROM openclasp_hosted_messages
1439
        WHERE thread_id = ${threadId} AND sender_agent_id = ${input.senderAgentId}
1440
          AND request_key = ${input.requestKey}
1441
        LIMIT 1
1442
      `;
1443
      return { message: this.hostedMessage(existing[0]!), deduplicated: true };
1444
    }
1445
    const sequenceRows = await this.sql`
1446
      SELECT COALESCE(MAX(sequence), -1) + 1 AS sequence
1447
      FROM openclasp_live_session_events
1448
      WHERE interaction_id = ${input.interactionId} AND agent_id = ${input.senderAgentId}
1449
    `;
1450
    const event = LiveSessionEventSchema.parse({
1451
      eventId: crypto.randomUUID(),
1452
      interactionId: input.interactionId,
1453
      agentId: input.senderAgentId,
1454
      sequence: Number(sequenceRows[0]?.sequence ?? 0),
1455
      type: 'message_sent',
1456
      occurredAt: now.toISOString(),
1457
      messageHash: contentHash,
1458
      evidenceReferences: [],
1459
      details: { labels: ['hosted_temporary'], metrics: {}, flags: { rawStoredEncrypted: true } },
1460
    });
1461
    const eventWithAttestation = JSON.stringify({
1462
      ...event,
1463
      attestation: attestSessionRecord(this.gatewaySecret(), event),
1464
    });
1465
    await this.sql`
1466
      INSERT INTO openclasp_live_session_events(interaction_id, event_id, agent_id, sequence, event)
1467
      VALUES (${event.interactionId}, ${event.eventId}, ${event.agentId}, ${event.sequence}, ${eventWithAttestation}::jsonb)
1468
      ON CONFLICT DO NOTHING
1469
    `;
1470
    return { message: this.hostedMessage(inserted[0]), deduplicated: false };
1471
  }
1472
1473
  async receiveTemporaryMessage(
1474
    token: string,
1475
    recipientAgentId: string,
1476
    requestKey: string,
1477
    content: string,
1478
  ) {
1479
    await this.ensureSchema();
1480
    const grant = verifySessionGrant(this.gatewaySecret(), token);
1481
    if (grant.recipientAgentId !== recipientAgentId)
1482
      throw new Error('Session credential is not valid for this temporary agent');
1483
    const recipient = await this.sessionParticipant(recipientAgentId);
1484
    if (recipient.mode !== 'temporary_chat')
1485
      throw new Error('Target is not a temporary chat agent');
1486
    const stored = await this.storeHostedMessage({
1487
      interactionId: grant.interactionId,
1488
      senderAgentId: grant.senderAgentId,
1489
      recipientAgentId,
1490
      requestKey,
1491
      content,
1492
      delivery: 'delivered',
1493
    });
1494
    return stored;
1495
  }
1496
1497
  async sendTemporaryMessage(
1498
    operatorId: string,
1499
    senderAgentId: string,
1500
    interactionId: string,
1501
    content: string,
1502
  ) {
1503
    await this.ensureSchema();
1504
    await this.ownedTemporaryAgent(operatorId, senderAgentId);
1505
    const session = await this.getLiveSession(operatorId, interactionId, senderAgentId);
1506
    const peer = await this.sessionParticipant(session.peer.agentId);
1507
    if (peer.mode !== 'persistent_runtime')
1508
      throw new Error('Temporary-to-temporary hosted conversations are not supported');
1509
    const requestKey = crypto.randomUUID();
1510
    const stored = await this.storeHostedMessage({
1511
      interactionId,
1512
      senderAgentId,
1513
      recipientAgentId: session.peer.agentId,
1514
      requestKey,
1515
      content,
1516
      delivery: 'accepted',
1517
    });
1518
    const response = await postRuntimeJson(
1519
      session.peer.endpoint,
1520
      {
1521
        jsonrpc: '2.0',
1522
        id: requestKey,
1523
        method: 'message/send',
1524
        params: {
1525
          message: {
1526
            role: 'user',
1527
            parts: [{ kind: 'text', text: content.trim() }],
1528
            metadata: {
1529
              [DEFAULT_EXTENSION_URI]: {
1530
                interactionId,
1531
                termsHash: session.contractHash,
1532
                initiatorAgentId:
1533
                  session.role === 'initiator' ? senderAgentId : session.peer.agentId,
1534
                responderAgentId:
1535
                  session.role === 'responder' ? senderAgentId : session.peer.agentId,
1536
              },
1537
            },
1538
          },
1539
        },
1540
      },
1541
      {
1542
        authorization: `Bearer ${session.peer.bearerToken}`,
1543
        'A2A-Extensions': DEFAULT_EXTENSION_URI,
1544
      },
1545
    );
1546
    if (response.status < 200 || response.status >= 300)
1547
      throw new Error(`Peer A2A endpoint returned HTTP ${response.status}`);
1548
    await this.sql`
1549
      UPDATE openclasp_hosted_messages SET delivery = 'delivered'
1550
      WHERE message_id = ${stored.message.messageId}
1551
    `;
1552
    return {
1553
      ...stored,
1554
      message: { ...stored.message, delivery: 'delivered' as const },
1555
      peerResponse: response.body,
1556
    };
1557
  }
1558
1559
  async listHostedThreads(operatorId: string, agentId: string): Promise<HostedThread[]> {
1560
    await this.ensureSchema();
1561
    await this.ownedTemporaryAgent(operatorId, agentId);
1562
    await this.sql`DELETE FROM openclasp_hosted_threads WHERE expires_at <= NOW()`;
1563
    const rows = await this.sql`
1564
      SELECT thread.*,
1565
        (SELECT COUNT(*) FROM openclasp_hosted_messages message
1566
          WHERE message.thread_id = thread.thread_id
1567
            AND message.recipient_agent_id = ${agentId} AND message.read_at IS NULL) AS unread_count
1568
      FROM openclasp_hosted_threads thread
1569
      WHERE ${agentId} IN (thread.participant_a_agent_id, thread.participant_b_agent_id)
1570
      ORDER BY thread.updated_at DESC
1571
    `;
1572
    return rows.map((row) =>
1573
      HostedThreadSchema.parse({
1574
        threadId: String(row.thread_id),
1575
        interactionId: String(row.interaction_id),
1576
        participantAgentIds: [
1577
          String(row.participant_a_agent_id),
1578
          String(row.participant_b_agent_id),
1579
        ],
1580
        status: row.status,
1581
        privacyMode: 'openclasp_hosted_temporary',
1582
        unreadCount: Number(row.unread_count ?? 0),
1583
        createdAt: new Date(String(row.created_at)).toISOString(),
1584
        updatedAt: new Date(String(row.updated_at)).toISOString(),
1585
        expiresAt: new Date(String(row.expires_at)).toISOString(),
1586
      }),
1587
    );
1588
  }
1589
1590
  async getHostedThread(operatorId: string, agentId: string, threadId: string) {
1591
    const threads = await this.listHostedThreads(operatorId, agentId);
1592
    const thread = threads.find((value) => value.threadId === threadId);
1593
    if (!thread) throw new Error('Hosted thread not found');
1594
    const rows = await this.sql`
1595
      SELECT * FROM openclasp_hosted_messages
1596
      WHERE thread_id = ${threadId} ORDER BY created_at ASC
1597
    `;
1598
    const peerAgentId = thread.participantAgentIds.find((value) => value !== agentId);
1599
    if (!peerAgentId) throw new Error('Hosted thread has invalid participants');
1600
    const peer = await this.sessionParticipant(peerAgentId);
1601
    const interactions = await this.sql`
1602
      SELECT payload FROM openclasp_federated_interactions
1603
      WHERE interaction_id = ${thread.interactionId} LIMIT 1
1604
    `;
1605
    const interaction = FederatedInteractionSchema.parse(interactions[0]?.payload);
1606
    const insights = await this.privateCounterpartyInsights(
1607
      operatorId,
1608
      peer,
1609
      interaction.contract.taskCategory,
1610
    );
1611
    return { thread, messages: rows.map((row) => this.hostedMessage(row)), insights };
1612
  }
1613
1614
  async markHostedThreadRead(operatorId: string, agentId: string, threadId: string) {
1615
    await this.getHostedThread(operatorId, agentId, threadId);
1616
    const rows = await this.sql`
1617
      UPDATE openclasp_hosted_messages
1618
      SET delivery = 'read', read_at = COALESCE(read_at, NOW())
1619
      WHERE thread_id = ${threadId} AND recipient_agent_id = ${agentId} AND read_at IS NULL
1620
      RETURNING message_id
1621
    `;
1622
    return { threadId, markedRead: rows.length };
1623
  }
1624
1625
  async closeHostedThread(operatorId: string, agentId: string, threadId: string) {
1626
    await this.getHostedThread(operatorId, agentId, threadId);
1627
    await this.sql`
1628
      UPDATE openclasp_hosted_threads SET status = 'closed', updated_at = NOW()
1629
      WHERE thread_id = ${threadId}
1630
    `;
1631
    return { threadId, status: 'closed' as const };
1632
  }
1633
1634
  async recordLiveSessionEvent(token: string, value: LiveSessionEvent) {
1635
    await this.ensureSchema();
1636
    const event = LiveSessionEventSchema.parse(value);
1637
    const grant = verifySessionGrant(this.gatewaySecret(), token);
1638
    if (grant.interactionId !== event.interactionId || grant.senderAgentId !== event.agentId)
1639
      throw new Error('Session credential does not match the event');
1640
    const sessions = await this.sql`
1641
      SELECT 1 FROM openclasp_live_sessions
1642
      WHERE interaction_id = ${event.interactionId}
1643
        AND status = 'active'
1644
        AND ${event.agentId} IN (initiator_agent_id, responder_agent_id)
1645
    `;
1646
    if (!sessions.length) throw new Error('Active live session not found');
1647
    const attestation = attestSessionRecord(this.gatewaySecret(), event);
1648
    const encoded = JSON.stringify({ ...event, attestation });
1649
    const rows = await this.sql`
1650
      INSERT INTO openclasp_live_session_events(
1651
        interaction_id, event_id, agent_id, sequence, event
1652
      ) SELECT ${event.interactionId}, ${event.eventId}, ${event.agentId}, ${event.sequence}, ${encoded}::jsonb
1653
      WHERE (
1654
        SELECT COUNT(*) FROM openclasp_live_session_events
1655
        WHERE interaction_id = ${event.interactionId}
1656
      ) < 1000
1657
      ON CONFLICT DO NOTHING
1658
      RETURNING event_id
1659
    `;
1660
    if (event.type === 'session_completed' || event.type === 'session_failed') {
1661
      const terminal = await this.sql`
1662
        SELECT COUNT(DISTINCT agent_id) AS count
1663
        FROM openclasp_live_session_events
1664
        WHERE interaction_id = ${event.interactionId}
1665
          AND event->>'type' IN ('session_completed', 'session_failed')
1666
      `;
1667
      if (Number(terminal[0]?.count ?? 0) >= 2) {
1668
        await this.sql`
1669
          UPDATE openclasp_live_sessions SET status = 'completed', completed_at = NOW()
1670
          WHERE interaction_id = ${event.interactionId} AND status = 'active'
1671
        `;
1672
        const completedAt = new Date().toISOString();
1673
        await this.sql`
1674
          UPDATE openclasp_federated_interactions
1675
          SET status = 'completed',
1676
            payload = jsonb_set(
1677
              jsonb_set(payload, '{status}', '"completed"'::jsonb),
1678
              '{updatedAt}', to_jsonb(${completedAt}::text)
1679
            ),
1680
            updated_at = NOW()
1681
          WHERE interaction_id = ${event.interactionId} AND status = 'active'
1682
        `;
1683
      }
1684
    }
1685
    return {
1686
      recorded: rows.length > 0,
1687
      deduplicated: rows.length === 0,
1688
      eventId: event.eventId,
1689
      attestation,
1690
    };
1691
  }
1692
1693
  async createFederatedInteraction(
1694
    operatorId: string,
1695
    value: FederatedInteraction,
1696
  ): Promise<FederatedInteraction> {
1697
    await this.ensureSchema();
1698
    const interaction = FederatedInteractionSchema.parse(value);
1699
    if (interaction.status !== 'pending') throw new Error('New interactions must be pending');
1700
    if (interaction.contract.interactionId !== interaction.interactionId)
1701
      throw new Error('Contract interaction ID does not match');
1702
    if (canonicalHash(interaction.contract) !== interaction.termsHash)
1703
      throw new Error('Contract hash does not match the immutable terms');
1704
    if (
1705
      interaction.contract.parties.length !== 2 ||
1706
      interaction.contract.parties[0] !== interaction.initiatorAgentId ||
1707
      interaction.contract.parties[1] !== interaction.responderAgentId
1708
    )
1709
      throw new Error('Contract parties do not match the interaction participants');
1710
    const acceptanceEntries = Object.entries(interaction.acceptances);
1711
    if (
1712
      acceptanceEntries.length !== 1 ||
1713
      acceptanceEntries[0]?.[0] !== interaction.initiatorAgentId ||
1714
      acceptanceEntries[0]?.[1].agentId !== interaction.initiatorAgentId ||
1715
      acceptanceEntries[0]?.[1].termsHash !== interaction.termsHash ||
1716
      !['oauth_installation', 'oauth_account'].includes(acceptanceEntries[0]?.[1].method ?? '')
1717
    )
1718
      throw new Error('A pending interaction requires only the initiator acceptance');
1719
    if (Date.parse(interaction.expiresAt) <= Date.now())
1720
      throw new Error('Interaction expiry must be in the future');
1721
    const owners = await this.sql`
1722
      SELECT agent_id, operator_id, card FROM openclasp_public_agents
1723
      WHERE agent_id IN (${interaction.initiatorAgentId}, ${interaction.responderAgentId})
1724
    `;
1725
    const initiator = owners.find((row) => row.agent_id === interaction.initiatorAgentId);
1726
    const responder = owners.find((row) => row.agent_id === interaction.responderAgentId);
1727
    if (!initiator || initiator.operator_id !== operatorId)
1728
      throw new Error('The initiating agent must be published and owned by this account');
1729
    if (!responder) throw new Error('Responder is not a published OpenClasp agent');
1730
    if (responder.operator_id === operatorId)
1731
      throw new Error('Federated interactions require agents from different accounts');
1732
    const responderCard = normalizePublicAgentCard(responder.card);
1733
    if (
1734
      !responderCard.transports.some(
1735
        (transport) =>
1736
          transport.endpoint === interaction.responderTransport.endpoint &&
1737
          transport.protocolBinding === interaction.responderTransport.protocolBinding,
1738
      )
1739
    )
1740
      throw new Error('Responder transport does not match its published Agent Card');
1741
    const encoded = JSON.stringify(interaction);
1742
    const rows = await this.sql`
1743
      INSERT INTO openclasp_federated_interactions(
1744
        interaction_id, initiator_operator_id, responder_operator_id,
1745
        initiator_agent_id, responder_agent_id, status, payload, expires_at
1746
      ) VALUES (
1747
        ${interaction.interactionId}, ${operatorId}, ${responder.operator_id},
1748
        ${interaction.initiatorAgentId}, ${interaction.responderAgentId},
1749
        ${interaction.status}, ${encoded}::jsonb, ${interaction.expiresAt}
1750
      )
1751
      RETURNING payload
1752
    `;
1753
    const stored = FederatedInteractionSchema.parse(rows[0]?.payload);
1754
    const profiles = await this.sql`
1755
      SELECT payload FROM openclasp_records
1756
      WHERE operator_id = ${responder.operator_id}
1757
        AND kind = 'agent_profile'
1758
        AND record_id = ${interaction.responderAgentId}
1759
      LIMIT 1
1760
    `;
1761
    const responderProfile = profiles[0]?.payload as AgentProfile | undefined;
1762
    if (responderProfile && canAutoAcceptInteraction(responderProfile, stored))
1763
      return this.respondToFederatedInteraction(
1764
        String(responder.operator_id),
1765
        stored.interactionId,
1766
        stored.responderAgentId,
1767
        'accept',
1768
        'policy_auto_accept',
1769
      );
1770
    return stored;
1771
  }
1772
1773
  async listFederatedInteractions(operatorId: string): Promise<FederatedInteraction[]> {
1774
    await this.ensureSchema();
1775
    await this.sql`
1776
      UPDATE openclasp_federated_interactions
1777
      SET status = 'expired', payload = jsonb_set(payload, '{status}', '"expired"'::jsonb), updated_at = NOW()
1778
      WHERE status = 'pending' AND expires_at <= NOW()
1779
    `;
1780
    const rows = await this.sql`
1781
      SELECT payload FROM openclasp_federated_interactions
1782
      WHERE initiator_operator_id = ${operatorId} OR responder_operator_id = ${operatorId}
1783
      ORDER BY updated_at DESC
1784
    `;
1785
    return rows.map((row) => FederatedInteractionSchema.parse(row.payload));
1786
  }
1787
1788
  async getFederatedInteraction(
1789
    operatorId: string,
1790
    interactionId: string,
1791
  ): Promise<FederatedInteraction | undefined> {
1792
    const values = await this.listFederatedInteractions(operatorId);
1793
    return values.find((value) => value.interactionId === interactionId);
1794
  }
1795
1796
  async respondToFederatedInteraction(
1797
    operatorId: string,
1798
    interactionId: string,
1799
    agentId: string,
1800
    decision: 'accept' | 'reject',
1801
    method: 'oauth_installation' | 'oauth_account' | 'policy_auto_accept' = 'oauth_account',
1802
  ): Promise<FederatedInteraction> {
1803
    await this.ensureSchema();
1804
    const rows = await this.sql`
1805
      SELECT payload, responder_operator_id, responder_agent_id
1806
      FROM openclasp_federated_interactions WHERE interaction_id = ${interactionId}
1807
    `;
1808
    const row = rows[0];
1809
    if (!row) throw new Error('Interaction invitation not found');
1810
    if (row.responder_operator_id !== operatorId || row.responder_agent_id !== agentId)
1811
      throw new Error('Only the invited agent may respond');
1812
    const current = FederatedInteractionSchema.parse(row.payload);
1813
    if (current.status !== 'pending') throw new Error('Invitation is no longer pending');
1814
    const now = new Date().toISOString();
1815
    if (Date.parse(current.expiresAt) <= Date.now()) {
1816
      const expired = { ...current, status: 'expired' as const, updatedAt: now };
1817
      await this.updateFederatedInteraction(interactionId, current.status, expired);
1818
      throw new Error('Invitation has expired');
1819
    }
1820
    const next: FederatedInteraction =
1821
      decision === 'reject'
1822
        ? { ...current, status: 'rejected', updatedAt: now }
1823
        : {
1824
            ...current,
1825
            status: 'active',
1826
            updatedAt: now,
1827
            acceptances: {
1828
              ...current.acceptances,
1829
              [agentId]: {
1830
                agentId,
1831
                method,
1832
                termsHash: current.termsHash,
1833
                acceptedAt: now,
1834
              },
1835
            },
1836
          };
1837
    if (decision === 'accept') {
1838
      try {
1839
        await this.brokerLiveSession(next);
1840
      } catch (error) {
1841
        const reason = error instanceof Error ? error.message.slice(0, 500) : 'Live session failed';
1842
        await this.sql`
1843
          UPDATE openclasp_agent_runtimes SET last_error = ${reason}, updated_at = NOW()
1844
          WHERE agent_id IN (${current.initiatorAgentId}, ${current.responderAgentId})
1845
        `;
1846
        throw error;
1847
      }
1848
    }
1849
    const updated = await this.updateFederatedInteraction(interactionId, current.status, next);
1850
    if (!updated) throw new Error('Invitation was already handled');
1851
    return next;
1852
  }
1853
1854
  private async updateFederatedInteraction(
1855
    interactionId: string,
1856
    expectedStatus: string,
1857
    value: FederatedInteraction,
1858
  ): Promise<boolean> {
1859
    const encoded = JSON.stringify(FederatedInteractionSchema.parse(value));
1860
    const rows = await this.sql`
1861
      UPDATE openclasp_federated_interactions
1862
      SET status = ${value.status}, payload = ${encoded}::jsonb, updated_at = NOW()
1863
      WHERE interaction_id = ${interactionId} AND status = ${expectedStatus}
1864
      RETURNING interaction_id
1865
    `;
1866
    return rows.length > 0;
1867
  }
1868
1869
  async getSettings(operatorId: string): Promise<AccountSettings> {
1870
    await this.ensureSchema();
1871
    const rows = await this.sql`
1872
      SELECT display_name, contribution_enabled, retention_days, evidence_sharing
1873
      FROM openclasp_account_settings
1874
      WHERE operator_id = ${operatorId}
1875
    `;
1876
    const row = rows[0] as
1877
      | {
1878
          display_name: string;
1879
          contribution_enabled: boolean;
1880
          retention_days: number;
1881
          evidence_sharing: AccountSettings['evidenceSharing'];
1882
        }
1883
      | undefined;
1884
    return row
1885
      ? {
1886
          displayName: row.display_name,
1887
          contributionEnabled: row.contribution_enabled,
1888
          retentionDays: row.retention_days,
1889
          evidenceSharing: row.evidence_sharing,
1890
          rawConversationsStored: false,
1891
        }
1892
      : defaults;
1893
  }
1894
1895
  async saveSettings(
1896
    operatorId: string,
1897
    settings: Omit<AccountSettings, 'rawConversationsStored'>,
1898
  ): Promise<AccountSettings> {
1899
    await this.ensureSchema();
1900
    await this.sql`
1901
      INSERT INTO openclasp_account_settings(
1902
        operator_id, display_name, contribution_enabled, retention_days, evidence_sharing
1903
      ) VALUES (
1904
        ${operatorId}, ${settings.displayName}, ${settings.contributionEnabled},
1905
        ${settings.retentionDays}, ${settings.evidenceSharing}
1906
      )
1907
      ON CONFLICT (operator_id) DO UPDATE SET
1908
        display_name = EXCLUDED.display_name,
1909
        contribution_enabled = EXCLUDED.contribution_enabled,
1910
        retention_days = EXCLUDED.retention_days,
1911
        evidence_sharing = EXCLUDED.evidence_sharing,
1912
        updated_at = NOW()
1913
    `;
1914
    return { ...settings, rawConversationsStored: false };
1915
  }
1916
}