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

Viewing files at commit 5239911501a5Commit detailsView latest

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