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

Viewing files at commit f87848a4fcb8Commit detailsView latest

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