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

Viewing files at commit 3b628facecbcCommit detailsView latest

packages/persistence/src/hosted.ts 2090 lines · 80.7 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
    const scopes = ['mcp:access'];
558
    await this.sql`
559
      INSERT INTO openclasp_agent_access_tokens(
560
        token_id, operator_id, agent_id, name, token_hash, scopes, expires_at, created_at
561
      ) VALUES (
562
        ${tokenId}, ${operatorId}, ${agentId}, ${name}, ${tokenHash},
563
        ${JSON.stringify(scopes)}::jsonb, ${expiresAt.toISOString()}, ${createdAt.toISOString()}
564
      )
565
    `;
566
    const clientId = agentAccessTokenClientId(tokenId);
567
    await this.upsert(operatorId, 'installation', clientId, {
568
      installationId: `install_${tokenId}`,
569
      clientId,
570
      agentId,
571
      projectId: agent.projectId,
572
      connectedAt: createdAt.toISOString(),
573
      updatedAt: createdAt.toISOString(),
574
    } satisfies AgentInstallation);
575
    return {
576
      tokenId,
577
      token,
578
      agentId,
579
      name,
580
      scopes,
581
      createdAt: createdAt.toISOString(),
582
      expiresAt: expiresAt.toISOString(),
583
    };
584
  }
585
586
  async listAgentAccessTokens(
587
    operatorId: string,
588
    agentId?: string,
589
  ): Promise<AgentAccessTokenMetadata[]> {
590
    await this.ensureSchema();
591
    const rows = agentId
592
      ? await this.sql`
593
          SELECT token_id, agent_id, name, scopes, expires_at, last_used_at, revoked_at, created_at
594
          FROM openclasp_agent_access_tokens
595
          WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
596
          ORDER BY created_at DESC
597
        `
598
      : await this.sql`
599
          SELECT token_id, agent_id, name, scopes, expires_at, last_used_at, revoked_at, created_at
600
          FROM openclasp_agent_access_tokens
601
          WHERE operator_id = ${operatorId}
602
          ORDER BY created_at DESC
603
        `;
604
    return rows.map((row) => ({
605
      tokenId: String(row.token_id),
606
      agentId: String(row.agent_id),
607
      name: String(row.name),
608
      scopes: Array.isArray(row.scopes)
609
        ? row.scopes.filter((scope): scope is string => typeof scope === 'string')
610
        : [],
611
      createdAt: new Date(String(row.created_at)).toISOString(),
612
      expiresAt: new Date(String(row.expires_at)).toISOString(),
613
      ...(row.last_used_at ? { lastUsedAt: new Date(String(row.last_used_at)).toISOString() } : {}),
614
      ...(row.revoked_at ? { revokedAt: new Date(String(row.revoked_at)).toISOString() } : {}),
615
    }));
616
  }
617
618
  async revokeAgentAccessToken(operatorId: string, agentId: string, tokenId: string) {
619
    await this.ensureSchema();
620
    const rows = await this.sql`
621
      UPDATE openclasp_agent_access_tokens
622
      SET revoked_at = COALESCE(revoked_at, NOW())
623
      WHERE token_id = ${tokenId} AND operator_id = ${operatorId} AND agent_id = ${agentId}
624
      RETURNING revoked_at
625
    `;
626
    if (!rows.length) throw new Error('Agent access token not found');
627
    const clientId = agentAccessTokenClientId(tokenId);
628
    await this.sql`
629
      DELETE FROM openclasp_records
630
      WHERE operator_id = ${operatorId} AND kind = 'installation' AND record_id = ${clientId}
631
    `;
632
    return {
633
      tokenId,
634
      agentId,
635
      revokedAt: new Date(String(rows[0]?.revoked_at)).toISOString(),
636
    };
637
  }
638
639
  async verifyAgentAccessToken(token: string) {
640
    await this.ensureSchema();
641
    const tokenId = agentAccessTokenId(token);
642
    if (!tokenId) throw new Error('Invalid agent access token');
643
    const rows = await this.sql`
644
      SELECT tokens.operator_id, tokens.agent_id, tokens.token_hash, tokens.scopes,
645
        tokens.expires_at, profile.payload AS profile
646
      FROM openclasp_agent_access_tokens tokens
647
      INNER JOIN openclasp_records profile
648
        ON profile.operator_id = tokens.operator_id
649
        AND profile.kind = 'agent_profile'
650
        AND profile.record_id = tokens.agent_id
651
      WHERE tokens.token_id = ${tokenId} AND tokens.revoked_at IS NULL
652
      LIMIT 1
653
    `;
654
    const row = rows[0];
655
    if (!row || !matchesAgentAccessToken(token, String(row.token_hash)))
656
      throw new Error('Invalid agent access token');
657
    if (Date.parse(String(row.expires_at)) <= Date.now())
658
      throw new Error('Agent access token has expired');
659
    const profile = row.profile as Partial<AgentProfile>;
660
    if (profile.status !== 'active') throw new Error('Agent access token is disabled');
661
    await this.sql`
662
      UPDATE openclasp_agent_access_tokens
663
      SET last_used_at = NOW()
664
      WHERE token_id = ${tokenId}
665
        AND (last_used_at IS NULL OR last_used_at < NOW() - INTERVAL '5 minutes')
666
    `;
667
    return {
668
      tokenId,
669
      operatorId: String(row.operator_id),
670
      agentId: String(row.agent_id),
671
      clientId: agentAccessTokenClientId(tokenId),
672
      scopes: Array.isArray(row.scopes)
673
        ? row.scopes.filter((scope): scope is string => typeof scope === 'string')
674
        : [],
675
      expiresAt: new Date(String(row.expires_at)).toISOString(),
676
    };
677
  }
678
679
  async publishAgent(operatorId: string, card: PublicAgentCard): Promise<PublicAgentCard> {
680
    await this.ensureSchema();
681
    card = PublicAgentCardSchema.parse(card);
682
    const runtimes = await this.sql`
683
      SELECT a2a_endpoint, endpoint FROM openclasp_agent_runtimes
684
      WHERE operator_id = ${operatorId} AND agent_id = ${card.agentId} AND status = 'verified'
685
    `;
686
    if (runtimes[0]) {
687
      card = PublicAgentCardSchema.parse({
688
        ...card,
689
        agentMode: 'persistent_runtime',
690
        transports: [
691
          {
692
            protocol: 'A2A/1.0',
693
            protocolBinding: 'JSONRPC',
694
            endpoint: String(runtimes[0].a2a_endpoint ?? runtimes[0].endpoint),
695
            managedBy: 'agent',
696
          },
697
        ],
698
      });
699
    }
700
    const encoded = JSON.stringify(card);
701
    const rows = await this.sql`
702
      INSERT INTO openclasp_public_agents(agent_id, operator_id, card, published_at, updated_at)
703
      VALUES (${card.agentId}, ${operatorId}, ${encoded}::jsonb, NOW(), NOW())
704
      ON CONFLICT (agent_id) DO UPDATE SET
705
        card = EXCLUDED.card,
706
        updated_at = NOW()
707
      WHERE openclasp_public_agents.operator_id = ${operatorId}
708
      RETURNING card
709
    `;
710
    const published = rows[0]?.card as PublicAgentCard | undefined;
711
    if (!published) throw new Error('Agent ID is already owned by another operator');
712
    return published;
713
  }
714
715
  async unpublishAgent(operatorId: string, agentId: string): Promise<boolean> {
716
    await this.ensureSchema();
717
    const rows = await this.sql`
718
      DELETE FROM openclasp_public_agents
719
      WHERE agent_id = ${agentId} AND operator_id = ${operatorId}
720
      RETURNING agent_id
721
    `;
722
    return rows.length > 0;
723
  }
724
725
  async getPublishedAgent(agentId: string): Promise<PublicAgentCard | undefined> {
726
    await this.ensureSchema();
727
    const rows = await this.sql`
728
      SELECT agents.card, runtime.a2a_endpoint, runtime.endpoint, profile.payload AS profile
729
      FROM openclasp_public_agents agents
730
      LEFT JOIN openclasp_agent_runtimes runtime
731
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
732
      LEFT JOIN openclasp_records profile
733
        ON profile.operator_id = agents.operator_id AND profile.kind = 'agent_profile'
734
        AND profile.record_id = agents.agent_id
735
      WHERE agents.agent_id = ${agentId}
736
    `;
737
    if (!rows[0]?.card) return undefined;
738
    let card = normalizePublicAgentCard(rows[0].card);
739
    const profile = rows[0].profile as Partial<AgentProfile> | undefined;
740
    const mode =
741
      profile?.agentMode ??
742
      (rows[0].a2a_endpoint || rows[0].endpoint ? 'persistent_runtime' : 'temporary_chat');
743
    if (mode === 'temporary_chat') {
744
      const root = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
745
        /\/$/,
746
        '',
747
      );
748
      card = PublicAgentCardSchema.parse({
749
        ...card,
750
        agentMode: 'temporary_chat',
751
        transports: [
752
          {
753
            protocol: 'A2A/1.0',
754
            protocolBinding: 'JSONRPC',
755
            endpoint: `${root}/a2a/temporary/${encodeURIComponent(agentId)}`,
756
            managedBy: 'openclasp',
757
          },
758
        ],
759
      });
760
    } else if (rows[0].a2a_endpoint || rows[0].endpoint)
761
      card = PublicAgentCardSchema.parse({
762
        ...card,
763
        agentMode: 'persistent_runtime',
764
        transports: [
765
          {
766
            protocol: 'A2A/1.0',
767
            protocolBinding: 'JSONRPC',
768
            endpoint: String(rows[0].a2a_endpoint ?? rows[0].endpoint),
769
            managedBy: 'agent',
770
          },
771
        ],
772
      });
773
    return { ...card, presence: await this.getAgentPresence(agentId) };
774
  }
775
776
  async searchPublishedAgents(input: {
777
    query?: string | undefined;
778
    capability?: string | undefined;
779
    limit?: number | undefined;
780
  }): Promise<PublicAgentCard[]> {
781
    await this.ensureSchema();
782
    const rows = await this.sql`
783
      SELECT agents.card, runtime.a2a_endpoint, runtime.endpoint, profile.payload AS profile
784
      FROM openclasp_public_agents agents
785
      LEFT JOIN openclasp_agent_runtimes runtime
786
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
787
      LEFT JOIN openclasp_records profile
788
        ON profile.operator_id = agents.operator_id AND profile.kind = 'agent_profile'
789
        AND profile.record_id = agents.agent_id
790
      ORDER BY agents.updated_at DESC LIMIT 100
791
    `;
792
    const query = input.query?.trim().toLowerCase();
793
    const capability = input.capability?.trim().toLowerCase();
794
    const presenceRows = await this.sql`
795
      SELECT records.record_id, records.payload
796
      FROM openclasp_records records
797
      INNER JOIN openclasp_public_agents agents ON agents.agent_id = records.record_id
798
      WHERE records.kind = 'presence'
799
    `;
800
    const presence = new Map(
801
      presenceRows.map((row) => [String(row.record_id), String(row.payload.lastSeenAt)]),
802
    );
803
    return rows
804
      .map((row) => {
805
        let card = normalizePublicAgentCard(row.card);
806
        const profile = row.profile as Partial<AgentProfile> | undefined;
807
        const mode =
808
          profile?.agentMode ??
809
          (row.a2a_endpoint || row.endpoint ? 'persistent_runtime' : 'temporary_chat');
810
        if (mode === 'temporary_chat') {
811
          const root = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
812
            /\/$/,
813
            '',
814
          );
815
          card = PublicAgentCardSchema.parse({
816
            ...card,
817
            agentMode: 'temporary_chat',
818
            transports: [
819
              {
820
                protocol: 'A2A/1.0',
821
                protocolBinding: 'JSONRPC',
822
                endpoint: `${root}/a2a/temporary/${encodeURIComponent(card.agentId)}`,
823
                managedBy: 'openclasp',
824
              },
825
            ],
826
          });
827
        } else if (row.a2a_endpoint || row.endpoint)
828
          card = PublicAgentCardSchema.parse({
829
            ...card,
830
            agentMode: 'persistent_runtime',
831
            transports: [
832
              {
833
                protocol: 'A2A/1.0',
834
                protocolBinding: 'JSONRPC',
835
                endpoint: String(row.a2a_endpoint ?? row.endpoint),
836
                managedBy: 'agent',
837
              },
838
            ],
839
          });
840
        return { ...card, presence: resolveAgentPresence(presence.get(card.agentId)) };
841
      })
842
      .filter(
843
        (card) =>
844
          (!query ||
845
            card.name.toLowerCase().includes(query) ||
846
            card.framework.toLowerCase().includes(query)) &&
847
          (!capability ||
848
            card.capabilities.some((value) => value.toLowerCase().includes(capability))),
849
      )
850
      .slice(0, Math.min(Math.max(input.limit ?? 20, 1), 50));
851
  }
852
853
  async touchAgentPresence(operatorId: string, agentId: string): Promise<AgentPresence> {
854
    await this.ensureSchema();
855
    const owned = await this.sql`
856
      SELECT 1 FROM openclasp_records
857
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
858
    `;
859
    if (!owned.length) throw new Error('Agent is not owned by this account');
860
    const lastSeenAt = new Date().toISOString();
861
    await this.upsert(operatorId, 'presence', agentId, { lastSeenAt });
862
    await this.sql`
863
      UPDATE openclasp_agent_runtimes SET last_seen_at = ${lastSeenAt}, updated_at = NOW()
864
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId} AND status = 'verified'
865
    `;
866
    return resolveAgentPresence(lastSeenAt);
867
  }
868
869
  async getAgentPresence(agentId: string): Promise<AgentPresence> {
870
    await this.ensureSchema();
871
    const rows = await this.sql`
872
      SELECT records.payload
873
      FROM openclasp_public_agents agents
874
      LEFT JOIN openclasp_records records
875
        ON records.operator_id = agents.operator_id
876
        AND records.kind = 'presence'
877
        AND records.record_id = agents.agent_id
878
      WHERE agents.agent_id = ${agentId}
879
      LIMIT 1
880
    `;
881
    if (!rows.length) throw new Error('Published agent not found');
882
    const lastSeenAt = rows[0]?.payload?.lastSeenAt;
883
    return resolveAgentPresence(typeof lastSeenAt === 'string' ? lastSeenAt : undefined);
884
  }
885
886
  async listAgentRuntimes(operatorId: string) {
887
    await this.ensureSchema();
888
    const rows = await this.sql`
889
      SELECT agent_id, endpoint, a2a_endpoint, status, verified_at, last_seen_at, last_error, updated_at
890
      FROM openclasp_agent_runtimes
891
      WHERE operator_id = ${operatorId}
892
      ORDER BY updated_at DESC
893
    `;
894
    return rows.map((row) => ({
895
      agentId: String(row.agent_id),
896
      endpoint: String(row.endpoint),
897
      a2aEndpoint: String(row.a2a_endpoint ?? row.endpoint),
898
      status: row.status as 'verified' | 'disabled',
899
      verifiedAt: new Date(String(row.verified_at)).toISOString(),
900
      ...(row.last_seen_at ? { lastSeenAt: new Date(String(row.last_seen_at)).toISOString() } : {}),
901
      ...(row.last_error ? { lastError: String(row.last_error) } : {}),
902
      updatedAt: new Date(String(row.updated_at)).toISOString(),
903
    }));
904
  }
905
906
  async registerAgentRuntime(operatorId: string, agentId: string, endpoint: string) {
907
    await this.ensureSchema();
908
    const owned = await this.sql`
909
      SELECT 1 FROM openclasp_records
910
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
911
    `;
912
    if (!owned.length) throw new Error('Agent is not owned by this account');
913
    const challenge = crypto.randomUUID();
914
    const verification = await postRuntimeJson(endpoint, {
915
      type: 'openclasp.runtime.verify',
916
      version: '1',
917
      agentId,
918
      challenge,
919
    });
920
    if (
921
      verification.status < 200 ||
922
      verification.status >= 300 ||
923
      !verification.body ||
924
      typeof verification.body !== 'object' ||
925
      (verification.body as { type?: unknown }).type !== 'openclasp.runtime.verified' ||
926
      (verification.body as { version?: unknown }).version !== '1' ||
927
      (verification.body as { agentId?: unknown }).agentId !== agentId ||
928
      (verification.body as { challenge?: unknown }).challenge !== challenge
929
    )
930
      throw new Error('Runtime endpoint did not return the verification challenge');
931
    const a2aEndpointValue = (verification.body as { a2aEndpoint?: unknown }).a2aEndpoint;
932
    const a2aEndpoint =
933
      typeof a2aEndpointValue === 'string' && a2aEndpointValue ? a2aEndpointValue : endpoint;
934
    await resolvePublicRuntimeEndpoint(a2aEndpoint);
935
    const runtimeSecret = randomBytes(32).toString('base64url');
936
    const encrypted = encryptGatewayPayload(this.gatewaySecret(), runtimeSecret);
937
    const verifiedAt = new Date().toISOString();
938
    const saved = await this.sql`
939
      INSERT INTO openclasp_agent_runtimes(
940
        agent_id, operator_id, endpoint, a2a_endpoint, secret_ciphertext, secret_iv, secret_auth_tag,
941
        status, verified_at, last_seen_at, updated_at
942
      ) VALUES (
943
        ${agentId}, ${operatorId}, ${endpoint}, ${a2aEndpoint}, ${encrypted.ciphertext},
944
        ${encrypted.iv}, ${encrypted.authTag}, 'verified', ${verifiedAt}, ${verifiedAt}, NOW()
945
      )
946
      ON CONFLICT (agent_id) DO UPDATE SET
947
        operator_id = EXCLUDED.operator_id,
948
        endpoint = EXCLUDED.endpoint,
949
        a2a_endpoint = EXCLUDED.a2a_endpoint,
950
        secret_ciphertext = EXCLUDED.secret_ciphertext,
951
        secret_iv = EXCLUDED.secret_iv,
952
        secret_auth_tag = EXCLUDED.secret_auth_tag,
953
        status = 'verified',
954
        verified_at = EXCLUDED.verified_at,
955
        last_seen_at = EXCLUDED.last_seen_at,
956
        last_error = NULL,
957
        updated_at = NOW()
958
      WHERE openclasp_agent_runtimes.operator_id = ${operatorId}
959
      RETURNING agent_id
960
    `;
961
    if (!saved.length) throw new Error('Agent runtime is owned by another account');
962
    await this.sql`
963
      UPDATE openclasp_public_agents
964
      SET card = jsonb_set(
965
          jsonb_set(
966
            card,
967
            '{transports}',
968
            ${JSON.stringify([
969
              {
970
                protocol: 'A2A/1.0',
971
                protocolBinding: 'JSONRPC',
972
                endpoint: a2aEndpoint,
973
                managedBy: 'agent',
974
              },
975
            ])}::jsonb
976
          ),
977
          '{agentMode}', '"persistent_runtime"'::jsonb
978
        ), updated_at = NOW()
979
      WHERE agent_id = ${agentId} AND operator_id = ${operatorId}
980
    `;
981
    await this.sql`
982
      UPDATE openclasp_records
983
      SET payload = jsonb_set(
984
          jsonb_set(payload, '{a2aEndpoint}', to_jsonb(${a2aEndpoint}::text)),
985
          '{agentMode}', '"persistent_runtime"'::jsonb
986
        ),
987
        updated_at = NOW()
988
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
989
    `;
990
    await this.touchAgentPresence(operatorId, agentId);
991
    return {
992
      agentId,
993
      endpoint,
994
      a2aEndpoint,
995
      status: 'verified' as const,
996
      verifiedAt,
997
      verificationKey: getSessionVerificationKey(this.gatewaySecret()),
998
    };
999
  }
1000
1001
  async disableAgentRuntime(operatorId: string, agentId: string) {
1002
    await this.ensureSchema();
1003
    const rows = await this.sql`
1004
      UPDATE openclasp_agent_runtimes
1005
      SET status = 'disabled', updated_at = NOW()
1006
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
1007
      RETURNING agent_id
1008
    `;
1009
    if (!rows.length) throw new Error('Agent runtime not found');
1010
    return { agentId, status: 'disabled' as const };
1011
  }
1012
1013
  async deleteAgent(operatorId: string, agentId: string) {
1014
    await this.ensureSchema();
1015
    const owned = await this.sql`
1016
      SELECT 1 FROM openclasp_records
1017
      WHERE operator_id = ${operatorId}
1018
        AND kind = 'agent_profile'
1019
        AND record_id = ${agentId}
1020
      LIMIT 1
1021
    `;
1022
    if (!owned.length) throw new Error('Owned agent not found');
1023
    const openInteractions = await this.sql`
1024
      SELECT interaction_id FROM openclasp_federated_interactions
1025
      WHERE (initiator_agent_id = ${agentId} OR responder_agent_id = ${agentId})
1026
        AND status IN ('pending', 'active')
1027
      LIMIT 1
1028
    `;
1029
    if (openInteractions.length) {
1030
      const error = new Error('Finish or reject the agent’s open interactions before deleting it');
1031
      Object.assign(error, { statusCode: 409 });
1032
      throw error;
1033
    }
1034
    await this.sql`
1035
      DELETE FROM openclasp_hosted_threads
1036
      WHERE participant_a_agent_id = ${agentId} OR participant_b_agent_id = ${agentId}
1037
    `;
1038
    await this.sql`
1039
      DELETE FROM openclasp_public_agents
1040
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
1041
    `;
1042
    await this.sql`
1043
      DELETE FROM openclasp_agent_runtimes
1044
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
1045
    `;
1046
    await this.sql`
1047
      DELETE FROM openclasp_agent_access_tokens
1048
      WHERE operator_id = ${operatorId} AND agent_id = ${agentId}
1049
    `;
1050
    await this.sql`
1051
      DELETE FROM openclasp_records
1052
      WHERE operator_id = ${operatorId}
1053
        AND (
1054
          (record_id = ${agentId} AND kind IN ('agent', 'agent_profile', 'publication', 'presence'))
1055
          OR (kind = 'installation' AND payload->>'agentId' = ${agentId})
1056
          OR (kind = 'setup_request' AND payload->>'existingAgentId' = ${agentId})
1057
        )
1058
    `;
1059
    return {
1060
      agentId,
1061
      deleted: true as const,
1062
      historyRetained: true as const,
1063
    };
1064
  }
1065
1066
  private async sessionParticipant(agentId: string) {
1067
    const rows = await this.sql`
1068
      SELECT agents.operator_id, agents.card, profile.payload AS profile,
1069
        runtime.endpoint, runtime.a2a_endpoint
1070
      FROM openclasp_public_agents agents
1071
      LEFT JOIN openclasp_records profile
1072
        ON profile.operator_id = agents.operator_id
1073
        AND profile.kind = 'agent_profile'
1074
        AND profile.record_id = agents.agent_id
1075
      LEFT JOIN openclasp_agent_runtimes runtime
1076
        ON runtime.agent_id = agents.agent_id AND runtime.status = 'verified'
1077
      WHERE agents.agent_id = ${agentId}
1078
      LIMIT 1
1079
    `;
1080
    const row = rows[0];
1081
    if (!row) throw new Error(`Published agent ${agentId} was not found`);
1082
    const card = normalizePublicAgentCard(row.card);
1083
    const profile = row.profile as Partial<AgentProfile> | undefined;
1084
    const mode =
1085
      profile?.agentMode ??
1086
      (row.endpoint || row.a2a_endpoint ? 'persistent_runtime' : 'temporary_chat');
1087
    if (mode === 'persistent_runtime' && !row.endpoint)
1088
      throw new Error(`Agent ${agentId} does not have a verified live runtime`);
1089
    const baseUrl = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
1090
      /\/$/,
1091
      '',
1092
    );
1093
    return {
1094
      agentId,
1095
      operatorId: String(row.operator_id),
1096
      mode: mode as 'persistent_runtime' | 'temporary_chat',
1097
      ...(row.endpoint ? { callbackEndpoint: String(row.endpoint) } : {}),
1098
      a2aEndpoint:
1099
        mode === 'temporary_chat'
1100
          ? `${baseUrl}/a2a/temporary/${encodeURIComponent(agentId)}`
1101
          : String(row.a2a_endpoint ?? row.endpoint),
1102
      card: PublicAgentCardSchema.parse({ ...card, agentMode: mode }),
1103
    };
1104
  }
1105
1106
  private async signedRuntimeRequest(
1107
    runtime: { callbackEndpoint: string },
1108
    requestId: string,
1109
    value: unknown,
1110
  ) {
1111
    const body = JSON.stringify(value);
1112
    const timestamp = new Date().toISOString();
1113
    return postRuntimeJson(runtime.callbackEndpoint, value, {
1114
      'openclasp-request-id': requestId,
1115
      'openclasp-timestamp': timestamp,
1116
      'openclasp-signature': `v1=${signSessionControl(this.gatewaySecret(), requestId, timestamp, body)}`,
1117
    });
1118
  }
1119
1120
  private sessionGrant(
1121
    interaction: FederatedInteraction,
1122
    senderAgentId: string,
1123
    recipientAgentId: string,
1124
  ) {
1125
    return issueSessionGrant(this.gatewaySecret(), {
1126
      interactionId: interaction.interactionId,
1127
      senderAgentId,
1128
      recipientAgentId,
1129
      expiresAt: Math.min(Date.parse(interaction.expiresAt), Date.now() + 60 * 60_000),
1130
    });
1131
  }
1132
1133
  private async privateCounterpartyInsights(
1134
    viewerOperatorId: string,
1135
    counterparty: { agentId: string; card: PublicAgentCard },
1136
    taskCategory: string,
1137
  ): Promise<LiveSessionInsight[]> {
1138
    const rows = await this.sql`
1139
      SELECT record_id, payload
1140
      FROM openclasp_records
1141
      WHERE operator_id = ${viewerOperatorId}
1142
        AND kind = 'profile'
1143
        AND payload->>'agentId' = ${counterparty.agentId}
1144
        AND payload->>'taskCategory' = ${taskCategory}
1145
      ORDER BY (payload->>'sampleSize')::integer DESC, updated_at DESC
1146
    `;
1147
    const profiles: ContextualProfile[] = rows
1148
      .map<Record<string, unknown>>((row) => ({
1149
        recordId: String(row.record_id),
1150
        ...(row.payload as Record<string, unknown>),
1151
      }))
1152
      .filter(
1153
        (profile) =>
1154
          typeof profile.agentVersion === 'string' &&
1155
          typeof profile.sampleSize === 'number' &&
1156
          typeof profile.updatedAt === 'string' &&
1157
          typeof profile.completion === 'number' &&
1158
          typeof profile.acceptance === 'number' &&
1159
          typeof profile.specification === 'number' &&
1160
          typeof profile.deadline === 'number' &&
1161
          typeof profile.communication === 'number' &&
1162
          typeof profile.evidence === 'number' &&
1163
          typeof profile.scope === 'number' &&
1164
          typeof profile.disputes === 'number',
1165
      ) as ContextualProfile[];
1166
    const exact = profiles.find(
1167
      (profile) => profile.agentVersion === counterparty.card.agentVersion,
1168
    );
1169
    const current = exact ?? profiles[0];
1170
    const insights: LiveSessionInsight[] = [];
1171
    if (!current) {
1172
      insights.push({
1173
        code: 'limited_verified_history',
1174
        severity: 'caution',
1175
        message: `No eligible ${taskCategory} history is available for this agent version. Ask for task-relevant evidence.`,
1176
        evidenceReferences: [],
1177
      });
1178
    } else {
1179
      const ageDays = Math.max(
1180
        0,
1181
        (Date.now() - Date.parse(String(current.updatedAt))) / 86_400_000,
1182
      );
1183
      const freshness = Math.exp(-ageDays / 180);
1184
      const sampleSize = Number(current.sampleSize);
1185
      const confidence = Math.min(0.95, (sampleSize / (sampleSize + 5)) * freshness);
1186
      const versionChanged = current.agentVersion !== counterparty.card.agentVersion;
1187
      const reference = `openclasp:profile:${current.recordId}`;
1188
      insights.push({
1189
        code: versionChanged ? 'version_history_only' : 'contextual_history',
1190
        severity: versionChanged || confidence < 0.25 ? 'caution' : 'info',
1191
        message: versionChanged
1192
          ? `Only prior-version ${taskCategory} history is available (${sampleSize} eligible interaction${sampleSize === 1 ? '' : 's'}); confidence is reduced for version ${counterparty.card.agentVersion}.`
1193
          : `Based on ${sampleSize} eligible ${taskCategory} interaction${sampleSize === 1 ? '' : 's'}; confidence ${(confidence * 100).toFixed(0)}%.`,
1194
        evidenceReferences: [reference],
1195
      });
1196
      const weakDimensions = [
1197
        ['completion', Number(current.completion)],
1198
        ['output acceptance', Number(current.acceptance)],
1199
        ['specification adherence', Number(current.specification)],
1200
        ['deadline reliability', Number(current.deadline)],
1201
        ['communication quality', Number(current.communication)],
1202
        ['evidence quality', Number(current.evidence)],
1203
        ['scope adherence', Number(current.scope)],
1204
      ].filter(([, score]) => Number(score) < 0.7);
1205
      if (weakDimensions.length)
1206
        insights.push({
1207
          code: 'historical_weaknesses',
1208
          severity: weakDimensions.some(([, score]) => Number(score) < 0.5) ? 'high' : 'caution',
1209
          message: `Observed weaker areas: ${weakDimensions
1210
            .map(([name, score]) => `${String(name)} ${(Number(score) * 100).toFixed(0)}%`)
1211
            .join(', ')}.`,
1212
          evidenceReferences: [reference],
1213
        });
1214
      if (Number(current.disputes) > 0.25)
1215
        insights.push({
1216
          code: 'elevated_dispute_history',
1217
          severity: Number(current.disputes) >= 0.5 ? 'high' : 'caution',
1218
          message: `Eligible feedback shows a ${(Number(current.disputes) * 100).toFixed(0)}% dispute rate in this task category.`,
1219
          evidenceReferences: [reference],
1220
        });
1221
    }
1222
    if (counterparty.card.limitations.length)
1223
      insights.push({
1224
        code: 'declared_limitations',
1225
        severity: 'info',
1226
        message: `Counterparty declares: ${counterparty.card.limitations.join('; ')}`,
1227
        evidenceReferences: [counterparty.card.cardUrl],
1228
      });
1229
    return insights;
1230
  }
1231
1232
  async brokerLiveSession(interaction: FederatedInteraction) {
1233
    await this.ensureSchema();
1234
    const existing = await this.sql`
1235
      SELECT status FROM openclasp_live_sessions
1236
      WHERE interaction_id = ${interaction.interactionId}
1237
    `;
1238
    if (existing[0]?.status === 'active') return;
1239
    const [initiator, responder] = await Promise.all([
1240
      this.sessionParticipant(interaction.initiatorAgentId),
1241
      this.sessionParticipant(interaction.responderAgentId),
1242
    ]);
1243
    if (initiator.mode === 'temporary_chat' && responder.mode === 'temporary_chat')
1244
      throw new Error('Temporary-to-temporary hosted conversations are not supported in this MVP');
1245
    const [initiatorInsights, responderInsights] = await Promise.all([
1246
      this.privateCounterpartyInsights(
1247
        initiator.operatorId,
1248
        responder,
1249
        interaction.contract.taskCategory,
1250
      ),
1251
      this.privateCounterpartyInsights(
1252
        responder.operatorId,
1253
        initiator,
1254
        interaction.contract.taskCategory,
1255
      ),
1256
    ]);
1257
    const issuedAt = new Date().toISOString();
1258
    const makeOffer = (
1259
      runtime: typeof initiator,
1260
      counterparty: typeof responder,
1261
      role: 'initiator' | 'responder',
1262
      privateInsights: LiveSessionInsight[],
1263
    ) =>
1264
      LiveSessionOfferSchema.parse({
1265
        type: 'openclasp.session.offer',
1266
        version: '1',
1267
        offerId: crypto.randomUUID(),
1268
        interactionId: interaction.interactionId,
1269
        agentId: runtime.agentId,
1270
        role,
1271
        counterparty: {
1272
          agentId: counterparty.agentId,
1273
          name: counterparty.card.name,
1274
          agentVersion: counterparty.card.agentVersion,
1275
          capabilities: counterparty.card.capabilities,
1276
        },
1277
        contract: interaction.contract,
1278
        contractHash: interaction.termsHash,
1279
        privateInsights,
1280
        issuedAt,
1281
        expiresAt: interaction.expiresAt,
1282
      });
1283
    const initiatorOffer = makeOffer(initiator, responder, 'initiator', initiatorInsights);
1284
    const responderOffer = makeOffer(responder, initiator, 'responder', responderInsights);
1285
    const prepare = async (
1286
      participant: typeof initiator,
1287
      offer: typeof initiatorOffer,
1288
      label: 'Initiator' | 'Responder',
1289
    ) => {
1290
      if (participant.mode === 'temporary_chat')
1291
        return LiveSessionAcceptanceSchema.parse({
1292
          type: 'openclasp.session.accepted',
1293
          version: '1',
1294
          offerId: offer.offerId,
1295
          interactionId: interaction.interactionId,
1296
          agentId: participant.agentId,
1297
          sessionId: crypto.randomUUID(),
1298
          a2aEndpoint: participant.a2aEndpoint,
1299
          expiresAt: interaction.expiresAt,
1300
        });
1301
      if (!participant.callbackEndpoint) throw new Error(`${label} runtime is not configured`);
1302
      const response = await this.signedRuntimeRequest(
1303
        { callbackEndpoint: participant.callbackEndpoint },
1304
        offer.offerId,
1305
        offer,
1306
      );
1307
      if (response.status < 200 || response.status >= 300)
1308
        throw new Error(`${label} runtime is not live (HTTP ${response.status})`);
1309
      return LiveSessionAcceptanceSchema.parse(response.body);
1310
    };
1311
    const [initiatorAcceptance, responderAcceptance] = await Promise.all([
1312
      prepare(initiator, initiatorOffer, 'Initiator'),
1313
      prepare(responder, responderOffer, 'Responder'),
1314
    ]);
1315
    if (
1316
      initiatorAcceptance.offerId !== initiatorOffer.offerId ||
1317
      initiatorAcceptance.agentId !== initiator.agentId ||
1318
      responderAcceptance.offerId !== responderOffer.offerId ||
1319
      responderAcceptance.agentId !== responder.agentId
1320
    )
1321
      throw new Error('Runtime returned a mismatched live-session acceptance');
1322
    await Promise.all([
1323
      ...(initiator.mode === 'persistent_runtime'
1324
        ? [resolvePublicRuntimeEndpoint(initiatorAcceptance.a2aEndpoint)]
1325
        : []),
1326
      ...(responder.mode === 'persistent_runtime'
1327
        ? [resolvePublicRuntimeEndpoint(responderAcceptance.a2aEndpoint)]
1328
        : []),
1329
    ]);
1330
    await this.sql`
1331
      INSERT INTO openclasp_live_sessions(
1332
        interaction_id, initiator_agent_id, responder_agent_id,
1333
        initiator_session_id, responder_session_id,
1334
        initiator_endpoint, responder_endpoint, status, expires_at
1335
      ) VALUES (
1336
        ${interaction.interactionId}, ${interaction.initiatorAgentId}, ${interaction.responderAgentId},
1337
        ${initiatorAcceptance.sessionId}, ${responderAcceptance.sessionId},
1338
        ${initiatorAcceptance.a2aEndpoint}, ${responderAcceptance.a2aEndpoint},
1339
        'preparing', ${interaction.expiresAt}
1340
      )
1341
      ON CONFLICT (interaction_id) DO UPDATE SET
1342
        initiator_session_id = EXCLUDED.initiator_session_id,
1343
        responder_session_id = EXCLUDED.responder_session_id,
1344
        initiator_endpoint = EXCLUDED.initiator_endpoint,
1345
        responder_endpoint = EXCLUDED.responder_endpoint,
1346
        status = 'preparing', expires_at = EXCLUDED.expires_at, last_error = NULL
1347
    `;
1348
    const baseUrl = (process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(
1349
      /\/$/,
1350
      '',
1351
    );
1352
    const activatedAt = new Date().toISOString();
1353
    const verificationKey = getSessionVerificationKey(this.gatewaySecret());
1354
    const makeActivation = (
1355
      agentId: string,
1356
      sessionId: string,
1357
      role: 'initiator' | 'responder',
1358
      peerAgentId: string,
1359
      peerSessionId: string,
1360
      peerEndpoint: string,
1361
      privateInsights: LiveSessionInsight[],
1362
    ): LiveSessionActivation => {
1363
      const bearerToken = this.sessionGrant(interaction, agentId, peerAgentId);
1364
      return LiveSessionActivationSchema.parse({
1365
        type: 'openclasp.session.activation',
1366
        version: '1',
1367
        activationId: crypto.randomUUID(),
1368
        interactionId: interaction.interactionId,
1369
        agentId,
1370
        sessionId,
1371
        role,
1372
        peer: {
1373
          agentId: peerAgentId,
1374
          sessionId: peerSessionId,
1375
          endpoint: peerEndpoint,
1376
          bearerToken,
1377
          verificationKey,
1378
        },
1379
        reporting: {
1380
          endpoint: `${baseUrl}/sessions/${encodeURIComponent(interaction.interactionId)}/events`,
1381
          bearerToken,
1382
        },
1383
        privateInsights,
1384
        contractHash: interaction.termsHash,
1385
        activatedAt,
1386
        expiresAt: interaction.expiresAt,
1387
      });
1388
    };
1389
    const initiatorActivation = makeActivation(
1390
      initiator.agentId,
1391
      initiatorAcceptance.sessionId,
1392
      'initiator',
1393
      responder.agentId,
1394
      responderAcceptance.sessionId,
1395
      responderAcceptance.a2aEndpoint,
1396
      initiatorInsights,
1397
    );
1398
    const responderActivation = makeActivation(
1399
      responder.agentId,
1400
      responderAcceptance.sessionId,
1401
      'responder',
1402
      initiator.agentId,
1403
      initiatorAcceptance.sessionId,
1404
      initiatorAcceptance.a2aEndpoint,
1405
      responderInsights,
1406
    );
1407
    try {
1408
      const activate = async (
1409
        participant: typeof initiator,
1410
        activation: LiveSessionActivation,
1411
        label: 'Initiator' | 'Responder',
1412
      ) => {
1413
        if (participant.mode === 'temporary_chat') return;
1414
        if (!participant.callbackEndpoint) throw new Error(`${label} runtime is not configured`);
1415
        const response = await this.signedRuntimeRequest(
1416
          { callbackEndpoint: participant.callbackEndpoint },
1417
          activation.activationId,
1418
          activation,
1419
        );
1420
        if (response.status < 200 || response.status >= 300)
1421
          throw new Error(`${label} activation failed with HTTP ${response.status}`);
1422
      };
1423
      await activate(responder, responderActivation, 'Responder');
1424
      await activate(initiator, initiatorActivation, 'Initiator');
1425
      await this.sql`
1426
        UPDATE openclasp_live_sessions
1427
        SET status = 'active', activated_at = NOW(), last_error = NULL
1428
        WHERE interaction_id = ${interaction.interactionId}
1429
      `;
1430
      await this.sql`
1431
        UPDATE openclasp_agent_runtimes
1432
        SET last_seen_at = NOW(), last_error = NULL, updated_at = NOW()
1433
        WHERE agent_id IN (${initiator.agentId}, ${responder.agentId})
1434
      `;
1435
      await Promise.all([
1436
        this.touchAgentPresence(initiator.operatorId, initiator.agentId),
1437
        this.touchAgentPresence(responder.operatorId, responder.agentId),
1438
      ]);
1439
    } catch (error) {
1440
      const reason =
1441
        error instanceof Error ? error.message.slice(0, 500) : 'Session activation failed';
1442
      await this.sql`
1443
        UPDATE openclasp_live_sessions SET status = 'failed', last_error = ${reason}
1444
        WHERE interaction_id = ${interaction.interactionId}
1445
      `;
1446
      throw error;
1447
    }
1448
  }
1449
1450
  async getLiveSession(operatorId: string, interactionId: string, agentId: string) {
1451
    await this.ensureSchema();
1452
    const rows = await this.sql`
1453
      SELECT session.*, interaction.payload,
1454
        initiator.operator_id AS initiator_operator_id,
1455
        responder.operator_id AS responder_operator_id
1456
      FROM openclasp_live_sessions session
1457
      INNER JOIN openclasp_federated_interactions interaction
1458
        ON interaction.interaction_id = session.interaction_id
1459
      INNER JOIN openclasp_public_agents initiator
1460
        ON initiator.agent_id = session.initiator_agent_id
1461
      INNER JOIN openclasp_public_agents responder
1462
        ON responder.agent_id = session.responder_agent_id
1463
      WHERE session.interaction_id = ${interactionId} AND session.status = 'active'
1464
      LIMIT 1
1465
    `;
1466
    const row = rows[0];
1467
    if (!row) throw new Error('Active live session not found');
1468
    const isInitiator = row.initiator_agent_id === agentId;
1469
    const isResponder = row.responder_agent_id === agentId;
1470
    if (!isInitiator && !isResponder) throw new Error('Agent is not a session participant');
1471
    const owner = isInitiator ? row.initiator_operator_id : row.responder_operator_id;
1472
    if (owner !== operatorId) throw new Error('Agent is not owned by this account');
1473
    const interaction = FederatedInteractionSchema.parse(row.payload);
1474
    const peerAgentId = String(isInitiator ? row.responder_agent_id : row.initiator_agent_id);
1475
    const peer = await this.sessionParticipant(peerAgentId);
1476
    const privateInsights = await this.privateCounterpartyInsights(
1477
      String(owner),
1478
      peer,
1479
      interaction.contract.taskCategory,
1480
    );
1481
    const bearerToken = this.sessionGrant(interaction, agentId, peerAgentId);
1482
    return {
1483
      type: 'openclasp.session.activation' as const,
1484
      version: '1' as const,
1485
      activationId: crypto.randomUUID(),
1486
      interactionId,
1487
      agentId,
1488
      sessionId: String(isInitiator ? row.initiator_session_id : row.responder_session_id),
1489
      role: isInitiator ? ('initiator' as const) : ('responder' as const),
1490
      peer: {
1491
        agentId: peerAgentId,
1492
        sessionId: String(isInitiator ? row.responder_session_id : row.initiator_session_id),
1493
        endpoint: String(isInitiator ? row.responder_endpoint : row.initiator_endpoint),
1494
        bearerToken,
1495
        verificationKey: getSessionVerificationKey(this.gatewaySecret()),
1496
      },
1497
      reporting: {
1498
        endpoint: `${(process.env.OPENCLASP_PUBLIC_URL ?? 'https://openclasp.vercel.app').replace(/\/$/, '')}/sessions/${encodeURIComponent(interactionId)}/events`,
1499
        bearerToken,
1500
      },
1501
      privateInsights,
1502
      contractHash: interaction.termsHash,
1503
      activatedAt: row.activated_at
1504
        ? new Date(String(row.activated_at)).toISOString()
1505
        : new Date().toISOString(),
1506
      expiresAt: new Date(String(row.expires_at)).toISOString(),
1507
    };
1508
  }
1509
1510
  private async ownedTemporaryAgent(operatorId: string, agentId: string) {
1511
    const rows = await this.sql`
1512
      SELECT payload FROM openclasp_records
1513
      WHERE operator_id = ${operatorId} AND kind = 'agent_profile' AND record_id = ${agentId}
1514
      LIMIT 1
1515
    `;
1516
    const profile = rows[0]?.payload as Partial<AgentProfile> | undefined;
1517
    if (!profile) throw new Error('Agent is not owned by this account');
1518
    const mode =
1519
      profile.agentMode ?? (profile.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat');
1520
    if (mode !== 'temporary_chat')
1521
      throw new Error('Hosted conversations are available only to temporary chat agents');
1522
    return profile;
1523
  }
1524
1525
  private hostedMessage(row: Record<string, any>): HostedMessage {
1526
    const decrypted = decryptGatewayPayload(this.gatewaySecret(), {
1527
      ciphertext: String(row.content_ciphertext),
1528
      iv: String(row.content_iv),
1529
      authTag: String(row.content_auth_tag),
1530
    }) as { content?: unknown };
1531
    return HostedMessageSchema.parse({
1532
      messageId: String(row.message_id),
1533
      threadId: String(row.thread_id),
1534
      interactionId: String(row.interaction_id),
1535
      senderAgentId: String(row.sender_agent_id),
1536
      recipientAgentId: String(row.recipient_agent_id),
1537
      contentType: 'text/plain',
1538
      content: decrypted.content,
1539
      contentHash: String(row.content_hash),
1540
      delivery: row.delivery,
1541
      createdAt: new Date(String(row.created_at)).toISOString(),
1542
      ...(row.read_at ? { readAt: new Date(String(row.read_at)).toISOString() } : {}),
1543
    });
1544
  }
1545
1546
  private async storeHostedMessage(input: {
1547
    interactionId: string;
1548
    senderAgentId: string;
1549
    recipientAgentId: string;
1550
    requestKey: string;
1551
    content: string;
1552
    delivery: 'accepted' | 'delivered';
1553
  }) {
1554
    const content = input.content.trim();
1555
    if (!content || content.length > 20_000)
1556
      throw new Error('Message must contain 1-20000 characters');
1557
    const sessions = await this.sql`
1558
      SELECT session.status, interaction.status AS interaction_status,
1559
        session.initiator_agent_id, session.responder_agent_id
1560
      FROM openclasp_live_sessions session
1561
      INNER JOIN openclasp_federated_interactions interaction
1562
        ON interaction.interaction_id = session.interaction_id
1563
      WHERE session.interaction_id = ${input.interactionId}
1564
      LIMIT 1
1565
    `;
1566
    const session = sessions[0];
1567
    if (!session || session.status !== 'active' || session.interaction_status !== 'active')
1568
      throw new Error('Active interaction not found');
1569
    const participants = new Set([
1570
      String(session.initiator_agent_id),
1571
      String(session.responder_agent_id),
1572
    ]);
1573
    if (!participants.has(input.senderAgentId) || !participants.has(input.recipientAgentId))
1574
      throw new Error('Message participants do not match the active interaction');
1575
    const now = new Date();
1576
    const threadId = input.interactionId;
1577
    const expiresAt = new Date(now.getTime() + 30 * 86_400_000).toISOString();
1578
    await this.sql`
1579
      INSERT INTO openclasp_hosted_threads(
1580
        thread_id, interaction_id, participant_a_agent_id, participant_b_agent_id,
1581
        status, expires_at
1582
      ) VALUES (
1583
        ${threadId}, ${input.interactionId}, ${String(session.initiator_agent_id)},
1584
        ${String(session.responder_agent_id)}, 'open', ${expiresAt}
1585
      )
1586
      ON CONFLICT (thread_id) DO UPDATE SET updated_at = NOW()
1587
      WHERE openclasp_hosted_threads.status = 'open'
1588
    `;
1589
    const thread = await this.sql`
1590
      SELECT status, expires_at FROM openclasp_hosted_threads WHERE thread_id = ${threadId}
1591
    `;
1592
    if (thread[0]?.status !== 'open') throw new Error('Hosted thread is closed');
1593
    if (Date.parse(String(thread[0].expires_at)) <= Date.now())
1594
      throw new Error('Hosted thread has expired');
1595
    const encrypted = encryptGatewayPayload(this.gatewaySecret(), { content });
1596
    const messageId = crypto.randomUUID();
1597
    const contentHash = canonicalHash(content);
1598
    const inserted = await this.sql`
1599
      INSERT INTO openclasp_hosted_messages(
1600
        message_id, thread_id, interaction_id, sender_agent_id, recipient_agent_id,
1601
        request_key, content_ciphertext, content_iv, content_auth_tag, content_hash, delivery
1602
      ) VALUES (
1603
        ${messageId}, ${threadId}, ${input.interactionId}, ${input.senderAgentId},
1604
        ${input.recipientAgentId}, ${input.requestKey}, ${encrypted.ciphertext}, ${encrypted.iv},
1605
        ${encrypted.authTag}, ${contentHash}, ${input.delivery}
1606
      )
1607
      ON CONFLICT (thread_id, sender_agent_id, request_key) DO NOTHING
1608
      RETURNING *
1609
    `;
1610
    if (!inserted[0]) {
1611
      const existing = await this.sql`
1612
        SELECT * FROM openclasp_hosted_messages
1613
        WHERE thread_id = ${threadId} AND sender_agent_id = ${input.senderAgentId}
1614
          AND request_key = ${input.requestKey}
1615
        LIMIT 1
1616
      `;
1617
      return { message: this.hostedMessage(existing[0]!), deduplicated: true };
1618
    }
1619
    const sequenceRows = await this.sql`
1620
      SELECT COALESCE(MAX(sequence), -1) + 1 AS sequence
1621
      FROM openclasp_live_session_events
1622
      WHERE interaction_id = ${input.interactionId} AND agent_id = ${input.senderAgentId}
1623
    `;
1624
    const event = LiveSessionEventSchema.parse({
1625
      eventId: crypto.randomUUID(),
1626
      interactionId: input.interactionId,
1627
      agentId: input.senderAgentId,
1628
      sequence: Number(sequenceRows[0]?.sequence ?? 0),
1629
      type: 'message_sent',
1630
      occurredAt: now.toISOString(),
1631
      messageHash: contentHash,
1632
      evidenceReferences: [],
1633
      details: { labels: ['hosted_temporary'], metrics: {}, flags: { rawStoredEncrypted: true } },
1634
    });
1635
    const eventWithAttestation = JSON.stringify({
1636
      ...event,
1637
      attestation: attestSessionRecord(this.gatewaySecret(), event),
1638
    });
1639
    await this.sql`
1640
      INSERT INTO openclasp_live_session_events(interaction_id, event_id, agent_id, sequence, event)
1641
      VALUES (${event.interactionId}, ${event.eventId}, ${event.agentId}, ${event.sequence}, ${eventWithAttestation}::jsonb)
1642
      ON CONFLICT DO NOTHING
1643
    `;
1644
    return { message: this.hostedMessage(inserted[0]), deduplicated: false };
1645
  }
1646
1647
  async receiveTemporaryMessage(
1648
    token: string,
1649
    recipientAgentId: string,
1650
    requestKey: string,
1651
    content: string,
1652
  ) {
1653
    await this.ensureSchema();
1654
    const grant = verifySessionGrant(this.gatewaySecret(), token);
1655
    if (grant.recipientAgentId !== recipientAgentId)
1656
      throw new Error('Session credential is not valid for this temporary agent');
1657
    const recipient = await this.sessionParticipant(recipientAgentId);
1658
    if (recipient.mode !== 'temporary_chat')
1659
      throw new Error('Target is not a temporary chat agent');
1660
    const stored = await this.storeHostedMessage({
1661
      interactionId: grant.interactionId,
1662
      senderAgentId: grant.senderAgentId,
1663
      recipientAgentId,
1664
      requestKey,
1665
      content,
1666
      delivery: 'delivered',
1667
    });
1668
    return stored;
1669
  }
1670
1671
  async sendTemporaryMessage(
1672
    operatorId: string,
1673
    senderAgentId: string,
1674
    interactionId: string,
1675
    content: string,
1676
  ) {
1677
    await this.ensureSchema();
1678
    await this.ownedTemporaryAgent(operatorId, senderAgentId);
1679
    const session = await this.getLiveSession(operatorId, interactionId, senderAgentId);
1680
    const peer = await this.sessionParticipant(session.peer.agentId);
1681
    if (peer.mode !== 'persistent_runtime')
1682
      throw new Error('Temporary-to-temporary hosted conversations are not supported');
1683
    const requestKey = crypto.randomUUID();
1684
    const stored = await this.storeHostedMessage({
1685
      interactionId,
1686
      senderAgentId,
1687
      recipientAgentId: session.peer.agentId,
1688
      requestKey,
1689
      content,
1690
      delivery: 'accepted',
1691
    });
1692
    const response = await postRuntimeJson(
1693
      session.peer.endpoint,
1694
      {
1695
        jsonrpc: '2.0',
1696
        id: requestKey,
1697
        method: 'message/send',
1698
        params: {
1699
          message: {
1700
            role: 'user',
1701
            parts: [{ kind: 'text', text: content.trim() }],
1702
            metadata: {
1703
              [DEFAULT_EXTENSION_URI]: {
1704
                interactionId,
1705
                termsHash: session.contractHash,
1706
                initiatorAgentId:
1707
                  session.role === 'initiator' ? senderAgentId : session.peer.agentId,
1708
                responderAgentId:
1709
                  session.role === 'responder' ? senderAgentId : session.peer.agentId,
1710
              },
1711
            },
1712
          },
1713
        },
1714
      },
1715
      {
1716
        authorization: `Bearer ${session.peer.bearerToken}`,
1717
        'A2A-Extensions': DEFAULT_EXTENSION_URI,
1718
      },
1719
    );
1720
    if (response.status < 200 || response.status >= 300)
1721
      throw new Error(`Peer A2A endpoint returned HTTP ${response.status}`);
1722
    await this.sql`
1723
      UPDATE openclasp_hosted_messages SET delivery = 'delivered'
1724
      WHERE message_id = ${stored.message.messageId}
1725
    `;
1726
    return {
1727
      ...stored,
1728
      message: { ...stored.message, delivery: 'delivered' as const },
1729
      peerResponse: response.body,
1730
    };
1731
  }
1732
1733
  async listHostedThreads(operatorId: string, agentId: string): Promise<HostedThread[]> {
1734
    await this.ensureSchema();
1735
    await this.ownedTemporaryAgent(operatorId, agentId);
1736
    await this.sql`DELETE FROM openclasp_hosted_threads WHERE expires_at <= NOW()`;
1737
    const rows = await this.sql`
1738
      SELECT thread.*,
1739
        (SELECT COUNT(*) FROM openclasp_hosted_messages message
1740
          WHERE message.thread_id = thread.thread_id
1741
            AND message.recipient_agent_id = ${agentId} AND message.read_at IS NULL) AS unread_count
1742
      FROM openclasp_hosted_threads thread
1743
      WHERE ${agentId} IN (thread.participant_a_agent_id, thread.participant_b_agent_id)
1744
      ORDER BY thread.updated_at DESC
1745
    `;
1746
    return rows.map((row) =>
1747
      HostedThreadSchema.parse({
1748
        threadId: String(row.thread_id),
1749
        interactionId: String(row.interaction_id),
1750
        participantAgentIds: [
1751
          String(row.participant_a_agent_id),
1752
          String(row.participant_b_agent_id),
1753
        ],
1754
        status: row.status,
1755
        privacyMode: 'openclasp_hosted_temporary',
1756
        unreadCount: Number(row.unread_count ?? 0),
1757
        createdAt: new Date(String(row.created_at)).toISOString(),
1758
        updatedAt: new Date(String(row.updated_at)).toISOString(),
1759
        expiresAt: new Date(String(row.expires_at)).toISOString(),
1760
      }),
1761
    );
1762
  }
1763
1764
  async getHostedThread(operatorId: string, agentId: string, threadId: string) {
1765
    const threads = await this.listHostedThreads(operatorId, agentId);
1766
    const thread = threads.find((value) => value.threadId === threadId);
1767
    if (!thread) throw new Error('Hosted thread not found');
1768
    const rows = await this.sql`
1769
      SELECT * FROM openclasp_hosted_messages
1770
      WHERE thread_id = ${threadId} ORDER BY created_at ASC
1771
    `;
1772
    const peerAgentId = thread.participantAgentIds.find((value) => value !== agentId);
1773
    if (!peerAgentId) throw new Error('Hosted thread has invalid participants');
1774
    const peer = await this.sessionParticipant(peerAgentId);
1775
    const interactions = await this.sql`
1776
      SELECT payload FROM openclasp_federated_interactions
1777
      WHERE interaction_id = ${thread.interactionId} LIMIT 1
1778
    `;
1779
    const interaction = FederatedInteractionSchema.parse(interactions[0]?.payload);
1780
    const insights = await this.privateCounterpartyInsights(
1781
      operatorId,
1782
      peer,
1783
      interaction.contract.taskCategory,
1784
    );
1785
    return { thread, messages: rows.map((row) => this.hostedMessage(row)), insights };
1786
  }
1787
1788
  async markHostedThreadRead(operatorId: string, agentId: string, threadId: string) {
1789
    await this.getHostedThread(operatorId, agentId, threadId);
1790
    const rows = await this.sql`
1791
      UPDATE openclasp_hosted_messages
1792
      SET delivery = 'read', read_at = COALESCE(read_at, NOW())
1793
      WHERE thread_id = ${threadId} AND recipient_agent_id = ${agentId} AND read_at IS NULL
1794
      RETURNING message_id
1795
    `;
1796
    return { threadId, markedRead: rows.length };
1797
  }
1798
1799
  async closeHostedThread(operatorId: string, agentId: string, threadId: string) {
1800
    await this.getHostedThread(operatorId, agentId, threadId);
1801
    await this.sql`
1802
      UPDATE openclasp_hosted_threads SET status = 'closed', updated_at = NOW()
1803
      WHERE thread_id = ${threadId}
1804
    `;
1805
    return { threadId, status: 'closed' as const };
1806
  }
1807
1808
  async recordLiveSessionEvent(token: string, value: LiveSessionEvent) {
1809
    await this.ensureSchema();
1810
    const event = LiveSessionEventSchema.parse(value);
1811
    const grant = verifySessionGrant(this.gatewaySecret(), token);
1812
    if (grant.interactionId !== event.interactionId || grant.senderAgentId !== event.agentId)
1813
      throw new Error('Session credential does not match the event');
1814
    const sessions = await this.sql`
1815
      SELECT 1 FROM openclasp_live_sessions
1816
      WHERE interaction_id = ${event.interactionId}
1817
        AND status = 'active'
1818
        AND ${event.agentId} IN (initiator_agent_id, responder_agent_id)
1819
    `;
1820
    if (!sessions.length) throw new Error('Active live session not found');
1821
    const attestation = attestSessionRecord(this.gatewaySecret(), event);
1822
    const encoded = JSON.stringify({ ...event, attestation });
1823
    const rows = await this.sql`
1824
      INSERT INTO openclasp_live_session_events(
1825
        interaction_id, event_id, agent_id, sequence, event
1826
      ) SELECT ${event.interactionId}, ${event.eventId}, ${event.agentId}, ${event.sequence}, ${encoded}::jsonb
1827
      WHERE (
1828
        SELECT COUNT(*) FROM openclasp_live_session_events
1829
        WHERE interaction_id = ${event.interactionId}
1830
      ) < 1000
1831
      ON CONFLICT DO NOTHING
1832
      RETURNING event_id
1833
    `;
1834
    if (event.type === 'session_completed' || event.type === 'session_failed') {
1835
      const terminal = await this.sql`
1836
        SELECT COUNT(DISTINCT agent_id) AS count
1837
        FROM openclasp_live_session_events
1838
        WHERE interaction_id = ${event.interactionId}
1839
          AND event->>'type' IN ('session_completed', 'session_failed')
1840
      `;
1841
      if (Number(terminal[0]?.count ?? 0) >= 2) {
1842
        await this.sql`
1843
          UPDATE openclasp_live_sessions SET status = 'completed', completed_at = NOW()
1844
          WHERE interaction_id = ${event.interactionId} AND status = 'active'
1845
        `;
1846
        const completedAt = new Date().toISOString();
1847
        await this.sql`
1848
          UPDATE openclasp_federated_interactions
1849
          SET status = 'completed',
1850
            payload = jsonb_set(
1851
              jsonb_set(payload, '{status}', '"completed"'::jsonb),
1852
              '{updatedAt}', to_jsonb(${completedAt}::text)
1853
            ),
1854
            updated_at = NOW()
1855
          WHERE interaction_id = ${event.interactionId} AND status = 'active'
1856
        `;
1857
      }
1858
    }
1859
    return {
1860
      recorded: rows.length > 0,
1861
      deduplicated: rows.length === 0,
1862
      eventId: event.eventId,
1863
      attestation,
1864
    };
1865
  }
1866
1867
  async createFederatedInteraction(
1868
    operatorId: string,
1869
    value: FederatedInteraction,
1870
  ): Promise<FederatedInteraction> {
1871
    await this.ensureSchema();
1872
    const interaction = FederatedInteractionSchema.parse(value);
1873
    if (interaction.status !== 'pending') throw new Error('New interactions must be pending');
1874
    if (interaction.contract.interactionId !== interaction.interactionId)
1875
      throw new Error('Contract interaction ID does not match');
1876
    if (canonicalHash(interaction.contract) !== interaction.termsHash)
1877
      throw new Error('Contract hash does not match the immutable terms');
1878
    if (
1879
      interaction.contract.parties.length !== 2 ||
1880
      interaction.contract.parties[0] !== interaction.initiatorAgentId ||
1881
      interaction.contract.parties[1] !== interaction.responderAgentId
1882
    )
1883
      throw new Error('Contract parties do not match the interaction participants');
1884
    const acceptanceEntries = Object.entries(interaction.acceptances);
1885
    if (
1886
      acceptanceEntries.length !== 1 ||
1887
      acceptanceEntries[0]?.[0] !== interaction.initiatorAgentId ||
1888
      acceptanceEntries[0]?.[1].agentId !== interaction.initiatorAgentId ||
1889
      acceptanceEntries[0]?.[1].termsHash !== interaction.termsHash ||
1890
      !['oauth_installation', 'oauth_account'].includes(acceptanceEntries[0]?.[1].method ?? '')
1891
    )
1892
      throw new Error('A pending interaction requires only the initiator acceptance');
1893
    if (Date.parse(interaction.expiresAt) <= Date.now())
1894
      throw new Error('Interaction expiry must be in the future');
1895
    const owners = await this.sql`
1896
      SELECT agent_id, operator_id, card FROM openclasp_public_agents
1897
      WHERE agent_id IN (${interaction.initiatorAgentId}, ${interaction.responderAgentId})
1898
    `;
1899
    const initiator = owners.find((row) => row.agent_id === interaction.initiatorAgentId);
1900
    const responder = owners.find((row) => row.agent_id === interaction.responderAgentId);
1901
    if (!initiator || initiator.operator_id !== operatorId)
1902
      throw new Error('The initiating agent must be published and owned by this account');
1903
    if (!responder) throw new Error('Responder is not a published OpenClasp agent');
1904
    if (responder.operator_id === operatorId)
1905
      throw new Error('Federated interactions require agents from different accounts');
1906
    const responderCard = normalizePublicAgentCard(responder.card);
1907
    if (
1908
      !responderCard.transports.some(
1909
        (transport) =>
1910
          transport.endpoint === interaction.responderTransport.endpoint &&
1911
          transport.protocolBinding === interaction.responderTransport.protocolBinding,
1912
      )
1913
    )
1914
      throw new Error('Responder transport does not match its published Agent Card');
1915
    const encoded = JSON.stringify(interaction);
1916
    const rows = await this.sql`
1917
      INSERT INTO openclasp_federated_interactions(
1918
        interaction_id, initiator_operator_id, responder_operator_id,
1919
        initiator_agent_id, responder_agent_id, status, payload, expires_at
1920
      ) VALUES (
1921
        ${interaction.interactionId}, ${operatorId}, ${responder.operator_id},
1922
        ${interaction.initiatorAgentId}, ${interaction.responderAgentId},
1923
        ${interaction.status}, ${encoded}::jsonb, ${interaction.expiresAt}
1924
      )
1925
      RETURNING payload
1926
    `;
1927
    const stored = FederatedInteractionSchema.parse(rows[0]?.payload);
1928
    const profiles = await this.sql`
1929
      SELECT payload FROM openclasp_records
1930
      WHERE operator_id = ${responder.operator_id}
1931
        AND kind = 'agent_profile'
1932
        AND record_id = ${interaction.responderAgentId}
1933
      LIMIT 1
1934
    `;
1935
    const responderProfile = profiles[0]?.payload as AgentProfile | undefined;
1936
    if (responderProfile && canAutoAcceptInteraction(responderProfile, stored))
1937
      return this.respondToFederatedInteraction(
1938
        String(responder.operator_id),
1939
        stored.interactionId,
1940
        stored.responderAgentId,
1941
        'accept',
1942
        'policy_auto_accept',
1943
      );
1944
    return stored;
1945
  }
1946
1947
  async listFederatedInteractions(operatorId: string): Promise<FederatedInteraction[]> {
1948
    await this.ensureSchema();
1949
    await this.sql`
1950
      UPDATE openclasp_federated_interactions
1951
      SET status = 'expired', payload = jsonb_set(payload, '{status}', '"expired"'::jsonb), updated_at = NOW()
1952
      WHERE status = 'pending' AND expires_at <= NOW()
1953
    `;
1954
    const rows = await this.sql`
1955
      SELECT payload FROM openclasp_federated_interactions
1956
      WHERE initiator_operator_id = ${operatorId} OR responder_operator_id = ${operatorId}
1957
      ORDER BY updated_at DESC
1958
    `;
1959
    return rows.map((row) => FederatedInteractionSchema.parse(row.payload));
1960
  }
1961
1962
  async getFederatedInteraction(
1963
    operatorId: string,
1964
    interactionId: string,
1965
  ): Promise<FederatedInteraction | undefined> {
1966
    const values = await this.listFederatedInteractions(operatorId);
1967
    return values.find((value) => value.interactionId === interactionId);
1968
  }
1969
1970
  async respondToFederatedInteraction(
1971
    operatorId: string,
1972
    interactionId: string,
1973
    agentId: string,
1974
    decision: 'accept' | 'reject',
1975
    method: 'oauth_installation' | 'oauth_account' | 'policy_auto_accept' = 'oauth_account',
1976
  ): Promise<FederatedInteraction> {
1977
    await this.ensureSchema();
1978
    const rows = await this.sql`
1979
      SELECT payload, responder_operator_id, responder_agent_id
1980
      FROM openclasp_federated_interactions WHERE interaction_id = ${interactionId}
1981
    `;
1982
    const row = rows[0];
1983
    if (!row) throw new Error('Interaction invitation not found');
1984
    if (row.responder_operator_id !== operatorId || row.responder_agent_id !== agentId)
1985
      throw new Error('Only the invited agent may respond');
1986
    const current = FederatedInteractionSchema.parse(row.payload);
1987
    if (current.status !== 'pending') throw new Error('Invitation is no longer pending');
1988
    const now = new Date().toISOString();
1989
    if (Date.parse(current.expiresAt) <= Date.now()) {
1990
      const expired = { ...current, status: 'expired' as const, updatedAt: now };
1991
      await this.updateFederatedInteraction(interactionId, current.status, expired);
1992
      throw new Error('Invitation has expired');
1993
    }
1994
    const next: FederatedInteraction =
1995
      decision === 'reject'
1996
        ? { ...current, status: 'rejected', updatedAt: now }
1997
        : {
1998
            ...current,
1999
            status: 'active',
2000
            updatedAt: now,
2001
            acceptances: {
2002
              ...current.acceptances,
2003
              [agentId]: {
2004
                agentId,
2005
                method,
2006
                termsHash: current.termsHash,
2007
                acceptedAt: now,
2008
              },
2009
            },
2010
          };
2011
    if (decision === 'accept') {
2012
      try {
2013
        await this.brokerLiveSession(next);
2014
      } catch (error) {
2015
        const reason = error instanceof Error ? error.message.slice(0, 500) : 'Live session failed';
2016
        await this.sql`
2017
          UPDATE openclasp_agent_runtimes SET last_error = ${reason}, updated_at = NOW()
2018
          WHERE agent_id IN (${current.initiatorAgentId}, ${current.responderAgentId})
2019
        `;
2020
        throw error;
2021
      }
2022
    }
2023
    const updated = await this.updateFederatedInteraction(interactionId, current.status, next);
2024
    if (!updated) throw new Error('Invitation was already handled');
2025
    return next;
2026
  }
2027
2028
  private async updateFederatedInteraction(
2029
    interactionId: string,
2030
    expectedStatus: string,
2031
    value: FederatedInteraction,
2032
  ): Promise<boolean> {
2033
    const encoded = JSON.stringify(FederatedInteractionSchema.parse(value));
2034
    const rows = await this.sql`
2035
      UPDATE openclasp_federated_interactions
2036
      SET status = ${value.status}, payload = ${encoded}::jsonb, updated_at = NOW()
2037
      WHERE interaction_id = ${interactionId} AND status = ${expectedStatus}
2038
      RETURNING interaction_id
2039
    `;
2040
    return rows.length > 0;
2041
  }
2042
2043
  async getSettings(operatorId: string): Promise<AccountSettings> {
2044
    await this.ensureSchema();
2045
    const rows = await this.sql`
2046
      SELECT display_name, contribution_enabled, retention_days, evidence_sharing
2047
      FROM openclasp_account_settings
2048
      WHERE operator_id = ${operatorId}
2049
    `;
2050
    const row = rows[0] as
2051
      | {
2052
          display_name: string;
2053
          contribution_enabled: boolean;
2054
          retention_days: number;
2055
          evidence_sharing: AccountSettings['evidenceSharing'];
2056
        }
2057
      | undefined;
2058
    return row
2059
      ? {
2060
          displayName: row.display_name,
2061
          contributionEnabled: row.contribution_enabled,
2062
          retentionDays: row.retention_days,
2063
          evidenceSharing: row.evidence_sharing,
2064
          rawConversationsStored: false,
2065
        }
2066
      : defaults;
2067
  }
2068
2069
  async saveSettings(
2070
    operatorId: string,
2071
    settings: Omit<AccountSettings, 'rawConversationsStored'>,
2072
  ): Promise<AccountSettings> {
2073
    await this.ensureSchema();
2074
    await this.sql`
2075
      INSERT INTO openclasp_account_settings(
2076
        operator_id, display_name, contribution_enabled, retention_days, evidence_sharing
2077
      ) VALUES (
2078
        ${operatorId}, ${settings.displayName}, ${settings.contributionEnabled},
2079
        ${settings.retentionDays}, ${settings.evidenceSharing}
2080
      )
2081
      ON CONFLICT (operator_id) DO UPDATE SET
2082
        display_name = EXCLUDED.display_name,
2083
        contribution_enabled = EXCLUDED.contribution_enabled,
2084
        retention_days = EXCLUDED.retention_days,
2085
        evidence_sharing = EXCLUDED.evidence_sharing,
2086
        updated_at = NOW()
2087
    `;
2088
    return { ...settings, rawConversationsStored: false };
2089
  }
2090
}