@codemem/server 0.47.5 → 0.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/application/sync-health.d.ts +5 -0
  2. package/dist/application/sync-health.d.ts.map +1 -1
  3. package/dist/index.d.ts +23 -27
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1045 -171
  6. package/dist/index.js.map +1 -1
  7. package/dist/relay-reachability-test-fixtures.d.ts +19 -0
  8. package/dist/relay-reachability-test-fixtures.d.ts.map +1 -0
  9. package/dist/relay-reachability.d.ts +37 -0
  10. package/dist/relay-reachability.d.ts.map +1 -0
  11. package/dist/relay-sync-test-fixtures.d.ts +109 -0
  12. package/dist/relay-sync-test-fixtures.d.ts.map +1 -0
  13. package/dist/routes/memory-tool-call.d.ts +47 -0
  14. package/dist/routes/memory-tool-call.d.ts.map +1 -0
  15. package/dist/routes/pack.d.ts +3 -1
  16. package/dist/routes/pack.d.ts.map +1 -1
  17. package/dist/routes/sync.d.ts +3 -0
  18. package/dist/routes/sync.d.ts.map +1 -1
  19. package/dist/shared-store.d.ts +8 -0
  20. package/dist/shared-store.d.ts.map +1 -0
  21. package/dist/sync-app.d.ts +17 -0
  22. package/dist/sync-app.d.ts.map +1 -0
  23. package/dist/sync-channel-dispatch-test-fixtures.d.ts +43 -0
  24. package/dist/sync-channel-dispatch-test-fixtures.d.ts.map +1 -0
  25. package/dist/sync-channel-dispatch.d.ts +19 -0
  26. package/dist/sync-channel-dispatch.d.ts.map +1 -0
  27. package/dist/sync-channel-pass-test-fixtures.d.ts +81 -0
  28. package/dist/sync-channel-pass-test-fixtures.d.ts.map +1 -0
  29. package/dist/viewer-authority.d.ts +17 -0
  30. package/dist/viewer-authority.d.ts.map +1 -0
  31. package/package.json +2 -2
  32. package/static/app.js +38 -38
  33. package/static/app.js.br +0 -0
  34. package/static/app.js.gz +0 -0
  35. package/static/index.html +87 -13
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3
- import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
3
+ import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
4
4
  import { serveStatic } from "@hono/node-server/serve-static";
5
5
  import { Hono } from "hono";
6
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
6
+ import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { createMiddleware } from "hono/factory";
8
8
  import { RateLimiter } from "limiter";
9
9
  import { and, count, desc, eq, inArray, max, ne, sql } from "drizzle-orm";
@@ -11,9 +11,11 @@ import { drizzle } from "drizzle-orm/better-sqlite3";
11
11
  import { homedir, hostname, networkInterfaces } from "node:os";
12
12
  import * as z from "zod";
13
13
  import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
14
+ import { BlockList, isIP } from "node:net";
14
15
  import "better-sqlite3";
15
16
  import "sqlite-vec";
16
17
  import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
18
+ import { RELAY_LOGICAL_ORIGIN, createRelayCoordinatorClient, createRelayPeerClient, createRelayPeerReachability, readRelayClientSettings, readRelayServicePin, relayCoordinatorEndpoint, resolveRelayGroup } from "@codemem/core/internal/relay-runtime";
17
19
  //#region src/routes/account.ts
18
20
  /** Mounted only alongside the account request middleware. */
19
21
  function accountRoutes(getSession) {
@@ -225,49 +227,6 @@ function preflightHandler() {
225
227
  });
226
228
  }
227
229
  //#endregion
228
- //#region src/request-rate-limit.ts
229
- function createInMemoryRequestRateLimiter(windowMs = 6e4) {
230
- const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
231
- const buckets = /* @__PURE__ */ new Map();
232
- let checks = 0;
233
- function estimatedRetryAfterS(limit) {
234
- return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
235
- }
236
- function cleanupExpiredBuckets(currentNow) {
237
- if (buckets.size < 64 || checks % 64 !== 0) return;
238
- const staleBefore = currentNow - safeWindowMs * 10;
239
- for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
240
- }
241
- return { check(key, limit) {
242
- checks += 1;
243
- const currentNow = Date.now();
244
- cleanupExpiredBuckets(currentNow);
245
- const safeLimit = Math.max(1, Math.trunc(limit));
246
- const bucketKey = `${safeLimit}:${key}`;
247
- let bucket = buckets.get(bucketKey);
248
- if (!bucket) {
249
- bucket = {
250
- limiter: new RateLimiter({
251
- tokensPerInterval: safeLimit,
252
- interval: safeWindowMs,
253
- fireImmediately: true
254
- }),
255
- lastUsedAt: currentNow
256
- };
257
- buckets.set(bucketKey, bucket);
258
- }
259
- bucket.lastUsedAt = currentNow;
260
- if (bucket.limiter.tryRemoveTokens(1)) return {
261
- allowed: true,
262
- retryAfterS: 0
263
- };
264
- return {
265
- allowed: false,
266
- retryAfterS: estimatedRetryAfterS(safeLimit)
267
- };
268
- } };
269
- }
270
- //#endregion
271
230
  //#region src/account/link-registry.ts
272
231
  var DEADLINE_MS = 6e5;
273
232
  var RETENTION_MS = 9e5;
@@ -1624,6 +1583,49 @@ function accountStatusRoutes(options) {
1624
1583
  return app;
1625
1584
  }
1626
1585
  //#endregion
1586
+ //#region src/request-rate-limit.ts
1587
+ function createInMemoryRequestRateLimiter(windowMs = 6e4) {
1588
+ const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
1589
+ const buckets = /* @__PURE__ */ new Map();
1590
+ let checks = 0;
1591
+ function estimatedRetryAfterS(limit) {
1592
+ return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
1593
+ }
1594
+ function cleanupExpiredBuckets(currentNow) {
1595
+ if (buckets.size < 64 || checks % 64 !== 0) return;
1596
+ const staleBefore = currentNow - safeWindowMs * 10;
1597
+ for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
1598
+ }
1599
+ return { check(key, limit) {
1600
+ checks += 1;
1601
+ const currentNow = Date.now();
1602
+ cleanupExpiredBuckets(currentNow);
1603
+ const safeLimit = Math.max(1, Math.trunc(limit));
1604
+ const bucketKey = `${safeLimit}:${key}`;
1605
+ let bucket = buckets.get(bucketKey);
1606
+ if (!bucket) {
1607
+ bucket = {
1608
+ limiter: new RateLimiter({
1609
+ tokensPerInterval: safeLimit,
1610
+ interval: safeWindowMs,
1611
+ fireImmediately: true
1612
+ }),
1613
+ lastUsedAt: currentNow
1614
+ };
1615
+ buckets.set(bucketKey, bucket);
1616
+ }
1617
+ bucket.lastUsedAt = currentNow;
1618
+ if (bucket.limiter.tryRemoveTokens(1)) return {
1619
+ allowed: true,
1620
+ retryAfterS: 0
1621
+ };
1622
+ return {
1623
+ allowed: false,
1624
+ retryAfterS: estimatedRetryAfterS(safeLimit)
1625
+ };
1626
+ } };
1627
+ }
1628
+ //#endregion
1627
1629
  //#region src/routes/config.ts
1628
1630
  /**
1629
1631
  * Config routes — GET /api/config, POST /api/config.
@@ -2591,7 +2593,7 @@ var BOOLEAN_IDENTITY_TARGET_KEYS = /* @__PURE__ */ new Set([
2591
2593
  "embedding_disabled",
2592
2594
  "embedding_offline"
2593
2595
  ]);
2594
- function invalidRequest$1(message) {
2596
+ function invalidRequest$2(message) {
2595
2597
  return {
2596
2598
  ok: false,
2597
2599
  status: 400,
@@ -2611,7 +2613,7 @@ function conflict(code, message) {
2611
2613
  } }
2612
2614
  };
2613
2615
  }
2614
- function isRecord$1(value) {
2616
+ function isRecord$2(value) {
2615
2617
  return value != null && typeof value === "object" && !Array.isArray(value);
2616
2618
  }
2617
2619
  function currentIdentityTarget() {
@@ -2636,7 +2638,7 @@ function identityFieldMatches(key, requested, expected) {
2636
2638
  }
2637
2639
  function requestedIdentityMatches(value) {
2638
2640
  if (value == null) return true;
2639
- if (!isRecord$1(value)) return null;
2641
+ if (!isRecord$2(value)) return null;
2640
2642
  if (Object.keys(value).length !== IDENTITY_TARGET_KEYS.size || Object.keys(value).some((key) => !IDENTITY_TARGET_KEYS.has(key))) return "unsupported";
2641
2643
  const expected = currentIdentityTarget();
2642
2644
  for (const key of VIEWER_IDENTITY_TARGET_KEYS) {
@@ -2651,15 +2653,15 @@ function requestedIdentityMatches(value) {
2651
2653
  function validateViewerTarget(store, payload, options = {}) {
2652
2654
  if (options.requirePairedTargets) {
2653
2655
  const hasDbPath = Object.hasOwn(payload, "db_path");
2654
- if (hasDbPath !== Object.hasOwn(payload, "identity_target")) return invalidRequest$1("db_path and identity_target must be provided together");
2655
- if (hasDbPath && (payload.db_path == null || payload.identity_target == null)) return invalidRequest$1("db_path and identity_target must be valid when provided");
2656
+ if (hasDbPath !== Object.hasOwn(payload, "identity_target")) return invalidRequest$2("db_path and identity_target must be provided together");
2657
+ if (hasDbPath && (payload.db_path == null || payload.identity_target == null)) return invalidRequest$2("db_path and identity_target must be valid when provided");
2656
2658
  }
2657
2659
  const dbMatches = requestedDbMatches(store, payload.db_path);
2658
- if (dbMatches == null) return invalidRequest$1("db_path must be a non-empty string");
2660
+ if (dbMatches == null) return invalidRequest$2("db_path must be a non-empty string");
2659
2661
  if (!dbMatches) return conflict("viewer_db_mismatch", "viewer database does not match request");
2660
2662
  const identityMatches = requestedIdentityMatches(payload.identity_target);
2661
2663
  if (identityMatches === "unsupported") return conflict("viewer_contract_unsupported", "viewer request contract is incompatible");
2662
- if (identityMatches == null) return invalidRequest$1("identity_target is invalid");
2664
+ if (identityMatches == null) return invalidRequest$2("identity_target is invalid");
2663
2665
  if (!identityMatches) return conflict("viewer_identity_mismatch", "viewer identity does not match request");
2664
2666
  if ((options.requireCurrentIdentity || payload.identity_target != null) && !store.hasCurrentIdentity()) return conflict("viewer_identity_mismatch", "viewer identity does not match request");
2665
2667
  return { ok: true };
@@ -3336,6 +3338,151 @@ function forgetMemoryForViewer(store, memoryId) {
3336
3338
  if (!store.forgetForUser(memoryId)) throw new Error("memory not found");
3337
3339
  }
3338
3340
  //#endregion
3341
+ //#region src/routes/memory-tool-call.ts
3342
+ /**
3343
+ * POST /api/memory-tools/:name — run one codemem memory tool on behalf of a
3344
+ * thin host (the OpenCode plugin) in another directory.
3345
+ *
3346
+ * The viewer serves every OpenCode project on the machine from one process,
3347
+ * so the caller sends its own directory and CODEMEM_PROJECT and the tool runs
3348
+ * with those instead of the viewer's working directory and environment. The
3349
+ * tool itself is executed by an injected function: `codemem serve` supplies
3350
+ * `callCodememToolLocally` from @codemem/mcp, which this package must not
3351
+ * import. Results, input validation, and retrieval-ledger capture are
3352
+ * therefore identical to stdio MCP and to the `codemem memory-tool` fallback.
3353
+ *
3354
+ * Request body:
3355
+ * { arguments: {...},
3356
+ * caller: { directory: "/abs/path", env_project: string|null,
3357
+ * session_id?: string, request_id?: string },
3358
+ * db_path, identity_target }
3359
+ *
3360
+ * The target pair is required (not optional as on read routes) because this
3361
+ * route can write. Responses: 200 `{ok:true,result}` or `{ok:false,error,result?}`
3362
+ * when the tool ran; 400/409 when the request or target is invalid.
3363
+ */
3364
+ var MEMORY_TOOL_CALL_CAPABILITY = "memory_tool_call";
3365
+ var MEMORY_TOOL_NAME = /^memory_[a-z_]+$/;
3366
+ var MEMORY_TOOL_CALL_MAX_BODY_BYTES = 1048576;
3367
+ var MAX_ID_CHARS = 200;
3368
+ function isRecord$1(value) {
3369
+ return value != null && typeof value === "object" && !Array.isArray(value);
3370
+ }
3371
+ function invalidRequest$1(message) {
3372
+ return { error: {
3373
+ code: "invalid_request",
3374
+ message
3375
+ } };
3376
+ }
3377
+ function parseEnvProject(value) {
3378
+ if (value == null) return null;
3379
+ if (typeof value !== "string") return void 0;
3380
+ return value.trim() || null;
3381
+ }
3382
+ /** Optional short identifier: null when absent or blank, undefined when invalid. */
3383
+ function parseOptionalId(value) {
3384
+ if (value == null) return null;
3385
+ if (typeof value !== "string" || value.length > MAX_ID_CHARS) return void 0;
3386
+ return value.trim() || null;
3387
+ }
3388
+ /** Validate the body shape; caller context is mandatory so nothing defaults to the viewer's cwd. */
3389
+ function parseMemoryToolCall(body) {
3390
+ const args = body.arguments ?? {};
3391
+ if (!isRecord$1(args)) return {
3392
+ ok: false,
3393
+ message: "arguments must be an object"
3394
+ };
3395
+ const caller = body.caller;
3396
+ if (!isRecord$1(caller)) return {
3397
+ ok: false,
3398
+ message: "caller is required"
3399
+ };
3400
+ if (typeof caller.directory !== "string" || !isAbsolute(caller.directory)) return {
3401
+ ok: false,
3402
+ message: "caller.directory must be an absolute path"
3403
+ };
3404
+ const envProject = parseEnvProject(caller.env_project);
3405
+ if (envProject === void 0) return {
3406
+ ok: false,
3407
+ message: "caller.env_project must be a string"
3408
+ };
3409
+ const sessionId = parseOptionalId(caller.session_id);
3410
+ if (sessionId === void 0) return {
3411
+ ok: false,
3412
+ message: "caller.session_id is invalid"
3413
+ };
3414
+ const requestId = parseOptionalId(caller.request_id);
3415
+ if (requestId === void 0) return {
3416
+ ok: false,
3417
+ message: "caller.request_id is invalid"
3418
+ };
3419
+ if (requestId && !sessionId) return {
3420
+ ok: false,
3421
+ message: "caller.request_id requires caller.session_id"
3422
+ };
3423
+ return {
3424
+ ok: true,
3425
+ args,
3426
+ caller: {
3427
+ cwd: caller.directory,
3428
+ envProject,
3429
+ ...sessionId ? { sessionId } : {},
3430
+ ...requestId ? { requestId } : {},
3431
+ statelessLedger: true
3432
+ }
3433
+ };
3434
+ }
3435
+ /** Body shape, then target: a write-capable route must name the database it expects. */
3436
+ function checkRequest(store, body) {
3437
+ if (!Object.hasOwn(body, "db_path") || !Object.hasOwn(body, "identity_target")) return {
3438
+ ok: false,
3439
+ status: 400,
3440
+ body: invalidRequest$1("db_path and identity_target are required")
3441
+ };
3442
+ const parsed = parseMemoryToolCall(body);
3443
+ if (!parsed.ok) return {
3444
+ ok: false,
3445
+ status: 400,
3446
+ body: invalidRequest$1(parsed.message)
3447
+ };
3448
+ const target = validateViewerTarget(store, body, {
3449
+ requireCurrentIdentity: true,
3450
+ requirePairedTargets: true
3451
+ });
3452
+ if (!target.ok) return {
3453
+ ok: false,
3454
+ status: target.status,
3455
+ body: target.body
3456
+ };
3457
+ return {
3458
+ ok: true,
3459
+ parsed
3460
+ };
3461
+ }
3462
+ function memoryToolCallRoutes(getStore, call) {
3463
+ const app = new Hono();
3464
+ app.post("/api/memory-tools/:name", async (c) => {
3465
+ const name = c.req.param("name");
3466
+ if (!MEMORY_TOOL_NAME.test(name)) return c.json(invalidRequest$1(`not a memory tool: ${name}`), 400);
3467
+ const body = await parseJsonObjectBody(c, MEMORY_TOOL_CALL_MAX_BODY_BYTES);
3468
+ if (body instanceof Response) return body;
3469
+ const store = getStore();
3470
+ const check = checkRequest(store, body);
3471
+ if (!check.ok) return c.json(check.body, check.status);
3472
+ const { parsed } = check;
3473
+ try {
3474
+ return c.json(await call(store, name, parsed.args, parsed.caller));
3475
+ } catch (err) {
3476
+ const message = err instanceof Error ? err.message : String(err);
3477
+ return c.json({ error: {
3478
+ code: "tool_call_failed",
3479
+ message
3480
+ } }, 500);
3481
+ }
3482
+ });
3483
+ return app;
3484
+ }
3485
+ //#endregion
3339
3486
  //#region src/routes/memory-tools.ts
3340
3487
  /**
3341
3488
  * Memory tool-support routes — HTTP twins of MCP tools that the viewer
@@ -4255,7 +4402,7 @@ async function handleLedgerRequest(c, getStore) {
4255
4402
  } }, 500);
4256
4403
  }
4257
4404
  }
4258
- function handleProfileRequest(c, getStore) {
4405
+ function handleProfileRequest(c, getStore, capabilities) {
4259
4406
  try {
4260
4407
  const store = getStore();
4261
4408
  if (!store.hasCurrentIdentity()) return c.json(viewerIdentityMismatch(), 409);
@@ -4264,7 +4411,8 @@ function handleProfileRequest(c, getStore) {
4264
4411
  protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.protocolVersion,
4265
4412
  min_supported_protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.minSupportedProtocolVersion,
4266
4413
  db_path: resolve(store.dbPath),
4267
- identity_target: currentIdentityTarget()
4414
+ identity_target: currentIdentityTarget(),
4415
+ capabilities: [...capabilities]
4268
4416
  });
4269
4417
  } catch {
4270
4418
  return c.json({ error: {
@@ -4273,9 +4421,10 @@ function handleProfileRequest(c, getStore) {
4273
4421
  } }, 500);
4274
4422
  }
4275
4423
  }
4276
- function packTransportRoutes(getStore) {
4424
+ function packTransportRoutes(getStore, options = {}) {
4277
4425
  const app = new Hono();
4278
- app.get("/api/prompt-pack-profile", (c) => handleProfileRequest(c, getStore));
4426
+ const capabilities = options.capabilities ?? [];
4427
+ app.get("/api/prompt-pack-profile", (c) => handleProfileRequest(c, getStore, capabilities));
4279
4428
  app.post("/api/pack", async (c) => {
4280
4429
  const parsed = await c.req.json().catch(() => INVALID_JSON);
4281
4430
  if (parsed === INVALID_JSON) return c.json(invalidRequest("invalid json body"), 400);
@@ -5784,6 +5933,15 @@ async function reconcileRecipientPolicyProjectsOperation(store, options) {
5784
5933
  //#endregion
5785
5934
  //#region src/application/sync-health.ts
5786
5935
  var STALE_AFTER_MS = 6e5;
5936
+ function readLastSuccessfulConnections(store) {
5937
+ const rows = store.db.prepare(`
5938
+ SELECT p.peer_device_id, a.transport, a.finished_at FROM sync_peers p
5939
+ JOIN sync_attempts a ON a.id = (
5940
+ SELECT id FROM sync_attempts WHERE peer_device_id = p.peer_device_id AND ok <> 0
5941
+ ORDER BY started_at DESC, id DESC LIMIT 1
5942
+ )`);
5943
+ return new Map(rows.all().map((row) => [row.peer_device_id, row]));
5944
+ }
5787
5945
  function timestamp(value) {
5788
5946
  if (!value) return null;
5789
5947
  const parsed = Date.parse(value);
@@ -5848,11 +6006,22 @@ function readPeerSyncHealth(store, peerIds) {
5848
6006
  )`);
5849
6007
  const failed = /* @__PURE__ */ new Map();
5850
6008
  for (const row of latest.all()) if (!row.ok && row.finished_at) failed.set(row.peer_device_id, row.finished_at);
5851
- return new Map(peerIds.map((id) => [id, peerSyncHealth(activity.get(id), {
5852
- now,
5853
- staleAfterMs,
5854
- failedAt: failed.get(id)
5855
- })]));
6009
+ const connections = readLastSuccessfulConnections(store);
6010
+ return new Map(peerIds.map((id) => {
6011
+ const connection = connections.get(id);
6012
+ const transport = connection?.transport;
6013
+ return [id, {
6014
+ ...peerSyncHealth(activity.get(id), {
6015
+ now,
6016
+ staleAfterMs,
6017
+ failedAt: failed.get(id)
6018
+ }),
6019
+ last_successful_connection: {
6020
+ transport: transport === "direct" || transport === "relay" ? transport : null,
6021
+ at: connection?.finished_at ?? null
6022
+ }
6023
+ }];
6024
+ }));
5856
6025
  }
5857
6026
  function overallSyncHealth(peers, options) {
5858
6027
  const paired = peers.filter((peer) => peer.pinned);
@@ -6698,7 +6867,7 @@ function remainingCoordinatorTimeoutS(configuredTimeoutS, deadlineMs, nowMs = Da
6698
6867
  const remainingMs = deadlineMs - nowMs;
6699
6868
  return remainingMs <= 0 ? null : Math.max(.1, Math.min(configuredTimeoutS, remainingMs / 1e3));
6700
6869
  }
6701
- function configuredGroupIds(groups) {
6870
+ function configuredGroupIds$1(groups) {
6702
6871
  const unique = [...new Set(groups.map((group) => group.trim()).filter(Boolean))];
6703
6872
  if (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();
6704
6873
  return unique;
@@ -6716,7 +6885,7 @@ function normalizedCoordinatorId(value) {
6716
6885
  }
6717
6886
  }
6718
6887
  function legacyTeamCandidateGroupDescriptors(store, coordinatorUrl, groups) {
6719
- const configuredIds = configuredGroupIds(groups);
6888
+ const configuredIds = configuredGroupIds$1(groups);
6720
6889
  const configuredCoordinatorId = buildBaseUrl(coordinatorUrl);
6721
6890
  const normalizedConfiguredCoordinatorId = normalizedCoordinatorId(configuredCoordinatorId);
6722
6891
  if (!configuredCoordinatorId || !normalizedConfiguredCoordinatorId) throw safeCoordinatorError();
@@ -7606,7 +7775,7 @@ function teamSetupRoutes(options) {
7606
7775
  if (!configuredCoordinatorId) return null;
7607
7776
  let currentGroupIds;
7608
7777
  try {
7609
- currentGroupIds = new Set(configuredGroupIds(config.syncCoordinatorGroups));
7778
+ currentGroupIds = new Set(configuredGroupIds$1(config.syncCoordinatorGroups));
7610
7779
  } catch {
7611
7780
  return null;
7612
7781
  }
@@ -8392,6 +8561,29 @@ function teamSetupRoutes(options) {
8392
8561
  /**
8393
8562
  * Sync routes — status, peers, actors, attempts, pairing, mutations.
8394
8563
  */
8564
+ function manualSyncReachability(resolver, store, peerId) {
8565
+ let route;
8566
+ try {
8567
+ route = resolver?.forPeer(store.db, peerId);
8568
+ } catch {
8569
+ return;
8570
+ }
8571
+ if (!route) return void 0;
8572
+ const signals = [resolver?.signal, route.signal].filter((signal) => signal !== void 0);
8573
+ return {
8574
+ ...route,
8575
+ signal: signals.length > 0 ? AbortSignal.any(signals) : void 0,
8576
+ deadlineMs: void 0
8577
+ };
8578
+ }
8579
+ function runManualSyncPass(store, peerId, resolver) {
8580
+ return runSyncPass(store.db, peerId, {
8581
+ keysDir: syncKeysDir(),
8582
+ dbPath: store.dbPath,
8583
+ scanner: store.scanner,
8584
+ reachability: manualSyncReachability(resolver, store, peerId)
8585
+ });
8586
+ }
8395
8587
  function safeSkippedSyncDetail(detail) {
8396
8588
  if (!detail) return null;
8397
8589
  return {
@@ -9888,7 +10080,7 @@ function verifyDirectPeerRequestSignature(request, body, options) {
9888
10080
  signature: directSignatureHeader,
9889
10081
  publicKey: options.publicKey
9890
10082
  });
9891
- if (hasDirectMaterial && direct.status === "absent") return {
10083
+ if ((hasDirectMaterial || options.requireDirectSignature) && direct.status === "absent") return {
9892
10084
  ok: false,
9893
10085
  reason: "invalid_direct_signature"
9894
10086
  };
@@ -9940,16 +10132,17 @@ function recordDirectPeerSignatureVersion(store, deviceId, version) {
9940
10132
  throw err;
9941
10133
  }
9942
10134
  }
9943
- function authorizeSyncRequest(store, request, body) {
9944
- const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
9945
- const signature = request.header("X-Opencode-Signature") ?? "";
9946
- const timestamp = request.header("X-Opencode-Timestamp") ?? "";
9947
- const nonce = request.header("X-Opencode-Nonce") ?? "";
9948
- if (!deviceId || !signature || !timestamp || !nonce) return {
9949
- ok: false,
9950
- reason: "missing_headers",
9951
- deviceId
9952
- };
10135
+ function matchesSyncChannelPeer(request, publicKey, readPin) {
10136
+ if (!request || request.signal.aborted) return false;
10137
+ try {
10138
+ const [algorithm, blob] = publicKey.split(/\s+/);
10139
+ const pin = readPin(request);
10140
+ return algorithm === "ssh-ed25519" && !!blob && !!pin && pin === `${algorithm} ${blob}`;
10141
+ } catch {
10142
+ return false;
10143
+ }
10144
+ }
10145
+ function checkedCurrentPeerKey(store, deviceId) {
9953
10146
  const peerRow = store.db.prepare(`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,
9954
10147
  sync_peer_signature_state.highest_observed_direct_signature_version
9955
10148
  FROM sync_peers
@@ -9972,6 +10165,30 @@ function authorizeSyncRequest(store, request, body) {
9972
10165
  reason: "fingerprint_mismatch",
9973
10166
  deviceId
9974
10167
  };
10168
+ return {
10169
+ ok: true,
10170
+ publicKey,
10171
+ highestObservedVersion: peerRow.highest_observed_direct_signature_version
10172
+ };
10173
+ }
10174
+ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
10175
+ const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
10176
+ const signature = request.header("X-Opencode-Signature") ?? "";
10177
+ const timestamp = request.header("X-Opencode-Timestamp") ?? "";
10178
+ const nonce = request.header("X-Opencode-Nonce") ?? "";
10179
+ if (!deviceId || !signature || !timestamp || !nonce) return {
10180
+ ok: false,
10181
+ reason: "missing_headers",
10182
+ deviceId
10183
+ };
10184
+ const peer = checkedCurrentPeerKey(store, deviceId);
10185
+ if (!peer.ok) return peer;
10186
+ const { publicKey } = peer;
10187
+ if (syncChannelPeerPin !== void 0 && !matchesSyncChannelPeer(request.raw, publicKey, syncChannelPeerPin)) return {
10188
+ ok: false,
10189
+ reason: "channel_binding_mismatch",
10190
+ deviceId
10191
+ };
9975
10192
  let verification;
9976
10193
  try {
9977
10194
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
@@ -9979,7 +10196,8 @@ function authorizeSyncRequest(store, request, body) {
9979
10196
  deviceId,
9980
10197
  publicKey,
9981
10198
  expectedRecipientId: localDeviceId,
9982
- highestObservedVersion: peerRow.highest_observed_direct_signature_version
10199
+ highestObservedVersion: peer.highestObservedVersion,
10200
+ requireDirectSignature: syncChannelPeerPin !== void 0
9983
10201
  });
9984
10202
  } catch {
9985
10203
  return {
@@ -11304,20 +11522,22 @@ function recordInboundScopeFailure(context) {
11304
11522
  source: "inbound"
11305
11523
  });
11306
11524
  }
11307
- function inboundScopeResetResponse(c, store, reason, context) {
11308
- recordInboundScopeFailure(context);
11309
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
11525
+ function parseInboundScopeRequest(body, context, options) {
11526
+ return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.syncChannelPeerPin), {
11527
+ ...context,
11528
+ negotiatedCapability: options.negotiated
11529
+ });
11310
11530
  }
11311
- function serveAuthorizedSnapshot(c, store, auth) {
11531
+ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
11312
11532
  const peerDeviceId = auth.deviceId;
11313
11533
  try {
11314
11534
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
11315
11535
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11316
- const scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== void 0, {
11536
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.syncChannelPeerPin), {
11317
11537
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
11318
11538
  negotiatedCapability: negotiatedSyncCapability(c)
11319
11539
  });
11320
- if (!scopeRequest.ok) return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), scopeRequest.reason, LOCAL_SYNC_CAPABILITY, null), 409);
11540
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, options.syncChannelPeerPin);
11321
11541
  const pageRequest = snapshotPageRequest((name) => c.req.query(name), localDeviceId);
11322
11542
  const result = loadMemorySnapshotPageForPeer(store.db, {
11323
11543
  ...pageRequest,
@@ -11343,9 +11563,83 @@ function serveAuthorizedSnapshot(c, store, auth) {
11343
11563
  return c.json({ error: "internal_error" }, 500);
11344
11564
  }
11345
11565
  }
11566
+ function registerSyncChannelRestriction(app, options) {
11567
+ const { syncChannelPeerPin } = options;
11568
+ if (syncChannelPeerPin !== void 0) app.use("*", async (c, next) => {
11569
+ const isOps = c.req.path === "/v1/ops" && ["GET", "POST"].includes(c.req.method);
11570
+ const isRead = c.req.method === "GET" && ["/v1/status", "/v1/snapshot"].includes(c.req.path);
11571
+ if (!isOps && !isRead) return c.json({ error: "not found" }, 404);
11572
+ if (c.req.raw.signal.aborted) return c.json(unauthorizedPayload(), 401);
11573
+ if (isRead) return serveChannelRead(c, options);
11574
+ await next();
11575
+ });
11576
+ }
11577
+ function serveChannelRead(c, options) {
11578
+ const { syncChannelPeerPin, rateLimitedResponse } = options;
11579
+ const store = options.getStore();
11580
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
11581
+ if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11582
+ if (!auth.ok) {
11583
+ logDirectPeerAuthDiagnostic(auth.reason);
11584
+ return rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);
11585
+ }
11586
+ const limited = rateLimitedResponse(c, auth.deviceId, true);
11587
+ if (limited) return limited;
11588
+ if (c.req.path === "/v1/status") return serveChannelStatus(c, store, auth, syncChannelPeerPin);
11589
+ return serveAuthorizedSnapshot(c, store, auth, { syncChannelPeerPin });
11590
+ }
11591
+ function syncScopeProvided(provided, syncChannelPeerPin) {
11592
+ return syncChannelPeerPin !== void 0 || provided;
11593
+ }
11594
+ function syncScopeResetResponse(c, store, reason, syncChannelPeerPin) {
11595
+ if (syncChannelPeerPin !== void 0) return c.json({
11596
+ error: "reset_required",
11597
+ reset_required: true,
11598
+ sync_capability: LOCAL_SYNC_CAPABILITY,
11599
+ reason,
11600
+ scope_id: null
11601
+ }, 409);
11602
+ return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
11603
+ }
11604
+ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
11605
+ try {
11606
+ const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11607
+ const authorization = syncScopeAuthorizationContext(store, auth, deviceId);
11608
+ const scopeRequest = parseSyncScopeRequest(c.req.query(SYNC_SCOPE_QUERY_PARAM), true, {
11609
+ ...authorization,
11610
+ negotiatedCapability: negotiatedSyncCapability(c)
11611
+ });
11612
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11613
+ if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
11614
+ const scopes = listAuthorizedScopesForPeer(store.db, {
11615
+ ...authorization,
11616
+ scopeId: scopeRequest.scope_id
11617
+ });
11618
+ const selectedScope = scopes[0];
11619
+ if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
11620
+ return c.json({
11621
+ device_id: deviceId,
11622
+ protocol_version: SYNC_PROTOCOL_VERSION,
11623
+ fingerprint,
11624
+ runtime_version: VERSION$1,
11625
+ sync_reset: selectedScope.sync_reset,
11626
+ sync_capability: LOCAL_SYNC_CAPABILITY,
11627
+ sync_features: LOCAL_SYNC_FEATURES,
11628
+ authorized_scopes: scopes
11629
+ });
11630
+ } catch {
11631
+ return c.json({ error: "internal_error" }, 500);
11632
+ }
11633
+ }
11346
11634
  function syncProtocolRoutes(getStore, opts = {}) {
11347
11635
  const app = new Hono();
11348
11636
  const routeRateLimit = opts.routeRateLimit ?? null;
11637
+ const syncChannelPeerPin = opts.syncChannelPeerPin;
11638
+ registerSyncChannelRestriction(app, {
11639
+ syncChannelPeerPin,
11640
+ getStore,
11641
+ rateLimitedResponse
11642
+ });
11349
11643
  function rateLimitedResponse(c, key, authenticated) {
11350
11644
  if (!routeRateLimit) return null;
11351
11645
  const isRead = c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS";
@@ -11415,7 +11709,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11415
11709
  });
11416
11710
  app.get("/v1/ops", (c) => {
11417
11711
  const store = getStore();
11418
- const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));
11712
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
11419
11713
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11420
11714
  if (!auth.ok) {
11421
11715
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -11428,11 +11722,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
11428
11722
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
11429
11723
  const negotiated = negotiatedSyncCapability(c);
11430
11724
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11431
- const scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== void 0, {
11725
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, syncChannelPeerPin), {
11432
11726
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
11433
11727
  negotiatedCapability: negotiated
11434
11728
  });
11435
- if (!scopeRequest.ok) return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), scopeRequest.reason, LOCAL_SYNC_CAPABILITY, null), 409);
11729
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11436
11730
  const since = c.req.query("since") ?? null;
11437
11731
  const rawLimit = Number.parseInt(c.req.query("limit") ?? "200", 10);
11438
11732
  const rawGeneration = c.req.query("generation");
@@ -11511,7 +11805,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11511
11805
  const store = getStore();
11512
11806
  const raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);
11513
11807
  if (raw == null) return c.json({ error: "payload_too_large" }, 413);
11514
- const auth = authorizeSyncRequest(store, c.req, raw);
11808
+ const auth = authorizeSyncRequest(store, c.req, raw, syncChannelPeerPin);
11515
11809
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
11516
11810
  if (!auth.ok) {
11517
11811
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -11531,11 +11825,14 @@ function syncProtocolRoutes(getStore, opts = {}) {
11531
11825
  const negotiated = negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, normalizeSyncCapability(body.sync_capability));
11532
11826
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
11533
11827
  const scopeContext = syncScopeAuthorizationContext(store, auth, localDeviceId);
11534
- const scopeRequest = parseSyncScopeRequest(body.scope_id, Object.hasOwn(body, "scope_id"), {
11535
- ...scopeContext,
11536
- negotiatedCapability: negotiated
11828
+ const scopeRequest = parseInboundScopeRequest(body, scopeContext, {
11829
+ negotiated,
11830
+ syncChannelPeerPin
11537
11831
  });
11538
- if (!scopeRequest.ok) return inboundScopeResetResponse(c, store, scopeRequest.reason, scopeContext);
11832
+ if (!scopeRequest.ok) {
11833
+ recordInboundScopeFailure(scopeContext);
11834
+ return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
11835
+ }
11539
11836
  if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
11540
11837
  if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
11541
11838
  const normalizedOps = extractReplicationOps(body);
@@ -11708,11 +12005,14 @@ async function deleteProjectScopeMappingRoute(c, store) {
11708
12005
  releasePublicationMutation?.();
11709
12006
  }
11710
12007
  }
11711
- function projectSharingByRepository(store, operations) {
12008
+ function projectSharingByRepository(store, operations, repositoryIdentitySnapshot) {
11712
12009
  const operationById = new Map(operations.map((operation) => [operation.operation_id, operation]));
11713
12010
  const sharingByProject = /* @__PURE__ */ new Map();
11714
12011
  const mappings = store.db.prepare("SELECT workspace_identity, project_pattern FROM project_scope_mappings").all();
11715
- const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db, { knownRepositoryIdentities: mappings.flatMap((mapping) => [mapping.workspace_identity, mapping.project_pattern]) });
12012
+ const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db, {
12013
+ repositoryIdentitySnapshot,
12014
+ knownRepositoryIdentities: mappings.flatMap((mapping) => [mapping.workspace_identity, mapping.project_pattern])
12015
+ });
11716
12016
  const seenOperationProjects = /* @__PURE__ */ new Set();
11717
12017
  const reviewed = store.db.prepare(`SELECT p.operation_id, p.canonical_project_identity
11718
12018
  FROM share_operation_projects p
@@ -11923,6 +12223,22 @@ function createActorMutationPreflightRoutes(getStore) {
11923
12223
  app.post("/api/sync/actors/merge", preflight);
11924
12224
  return app;
11925
12225
  }
12226
+ async function projectScopeInventoryRoute(c, store) {
12227
+ const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
12228
+ const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
12229
+ const repositoryIdentitySnapshot = readRepositoryIdentitySnapshot(store.db);
12230
+ const inventory = listProjectScopeInventory(store.db, {
12231
+ repositoryIdentitySnapshot,
12232
+ identitySource: c.req.query("identity_source"),
12233
+ limit,
12234
+ offset,
12235
+ query: c.req.query("q"),
12236
+ scopeId: c.req.query("scope_id"),
12237
+ status: c.req.query("status")
12238
+ });
12239
+ const sharingByProject = projectSharingByRepository(store, await shareOperationReadModels(store, void 0, false), repositoryIdentitySnapshot);
12240
+ return c.json(serializeProjectScopeInventory(store, inventory, sharingByProject));
12241
+ }
11926
12242
  function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
11927
12243
  const app = createActorMutationPreflightRoutes(getStore);
11928
12244
  app.post("/api/sync/invites/inspect", inspectPairingInvite);
@@ -12266,11 +12582,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
12266
12582
  else peerIds = store.db.prepare("SELECT peer_device_id FROM sync_peers").all().map((row) => String(row.peer_device_id ?? "").trim()).filter(Boolean);
12267
12583
  const items = [];
12268
12584
  for (const peerId of peerIds) {
12269
- const result = await runSyncPass(store.db, peerId, {
12270
- keysDir: syncKeysDir(),
12271
- dbPath: store.dbPath,
12272
- scanner: store.scanner
12273
- });
12585
+ const result = await runManualSyncPass(store, peerId, options.syncReachability);
12274
12586
  items.push({
12275
12587
  peer_device_id: peerId,
12276
12588
  ...result,
@@ -12534,21 +12846,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
12534
12846
  }, requests);
12535
12847
  return c.json(result, result.results.some((item) => item.status !== "applied") ? 207 : 200);
12536
12848
  });
12537
- app.get("/api/sync/projects", async (c) => {
12538
- const store = getStore();
12539
- const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
12540
- const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
12541
- const inventory = listProjectScopeInventory(store.db, {
12542
- identitySource: c.req.query("identity_source"),
12543
- limit,
12544
- offset,
12545
- query: c.req.query("q"),
12546
- scopeId: c.req.query("scope_id"),
12547
- status: c.req.query("status")
12548
- });
12549
- const sharingByProject = projectSharingByRepository(store, await shareOperationReadModels(store, void 0, false));
12550
- return c.json(serializeProjectScopeInventory(store, inventory, sharingByProject));
12551
- });
12849
+ app.get("/api/sync/projects", (c) => projectScopeInventoryRoute(c, getStore()));
12552
12850
  app.post("/api/sync/projects/reassign-project", async (c) => {
12553
12851
  const store = getStore();
12554
12852
  const body = await parseViewerJsonBody(c);
@@ -14598,6 +14896,164 @@ function updateStatusRoutes(options = {}) {
14598
14896
  return app;
14599
14897
  }
14600
14898
  //#endregion
14899
+ //#region src/shared-store.ts
14900
+ var sharedStore = null;
14901
+ var sharedStoreClosePromise = null;
14902
+ /** Share the default connection across viewer and sync listeners. */
14903
+ function getStore() {
14904
+ if (!sharedStore) sharedStore = new MemoryStore(resolveDbPath());
14905
+ return sharedStore;
14906
+ }
14907
+ /** Close a synchronous-only shared store. Async pack owners use closeStoreAsync(). */
14908
+ function closeStore() {
14909
+ sharedStore?.close();
14910
+ sharedStore = null;
14911
+ }
14912
+ /** Drain semantic work before closing SQLite and releasing the shared store. */
14913
+ function closeStoreAsync() {
14914
+ if (sharedStoreClosePromise) return sharedStoreClosePromise;
14915
+ if (!sharedStore) return Promise.resolve();
14916
+ const store = sharedStore;
14917
+ sharedStoreClosePromise = store.closeAsync().then(() => {
14918
+ if (sharedStore === store) sharedStore = null;
14919
+ sharedStoreClosePromise = null;
14920
+ });
14921
+ return sharedStoreClosePromise;
14922
+ }
14923
+ //#endregion
14924
+ //#region src/sync-app.ts
14925
+ /** Keep the network listener limited to signature-authenticated peer protocol routes. */
14926
+ function createSyncApp$1(opts) {
14927
+ const storeFactory = opts?.storeFactory ?? getStore;
14928
+ const requestRateLimit = opts?.syncRequestRateLimit ?? {};
14929
+ const rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();
14930
+ const readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));
14931
+ const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
14932
+ const app = new Hono();
14933
+ app.route("/", syncProtocolRoutes(storeFactory, {
14934
+ syncChannelPeerPin: opts?.syncChannelPeerPin,
14935
+ routeRateLimit: {
14936
+ limiter: rateLimiter,
14937
+ readLimit,
14938
+ mutationLimit,
14939
+ unauthenticatedReadLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit))),
14940
+ unauthenticatedMutationLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)))
14941
+ }
14942
+ }));
14943
+ app.all("*", (c) => c.json({ error: "not found" }, 404));
14944
+ return app;
14945
+ }
14946
+ //#endregion
14947
+ //#region src/viewer-authority.ts
14948
+ var LOOPBACK_ADDRESSES = new BlockList();
14949
+ LOOPBACK_ADDRESSES.addSubnet("127.0.0.0", 8, "ipv4");
14950
+ LOOPBACK_ADDRESSES.addAddress("::1", "ipv6");
14951
+ function listenerHostname(host) {
14952
+ if (typeof host !== "string" || !host) return null;
14953
+ if (/[\s/@\\?#%]/u.test(host)) return null;
14954
+ if ([...host].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) return null;
14955
+ const authority = isIP(host) === 6 ? `[${host}]` : host;
14956
+ if (authority.includes(":") && !/^\[[0-9a-fA-F:.]+\]$/.test(authority)) return null;
14957
+ try {
14958
+ const hostname = new URL(`http://${authority}`).hostname;
14959
+ if (hostname.startsWith("[")) return hostname.slice(1, -1);
14960
+ return hostname.replace(/\.$/, "");
14961
+ } catch {
14962
+ return null;
14963
+ }
14964
+ }
14965
+ function loopbackAliases(hostname) {
14966
+ if (hostname === "localhost") return [
14967
+ "localhost",
14968
+ "127.0.0.1",
14969
+ "[::1]"
14970
+ ];
14971
+ if (isIP(hostname) === 6) {
14972
+ if (LOOPBACK_ADDRESSES.check(hostname, "ipv6")) return [`[${hostname}]`, "localhost"];
14973
+ return null;
14974
+ }
14975
+ if (isIP(hostname) === 4 && LOOPBACK_ADDRESSES.check(hostname, "ipv4")) return [hostname, "localhost"];
14976
+ return null;
14977
+ }
14978
+ function listenerPolicy(options) {
14979
+ try {
14980
+ const address = options.getListenerAddress();
14981
+ if (!address || !Number.isInteger(address.port) || address.port < 1 || address.port > 65535) return null;
14982
+ const hostname = listenerHostname(address.host);
14983
+ if (!hostname) return null;
14984
+ if (address.address === void 0) return {
14985
+ aliases: loopbackAliases(hostname),
14986
+ port: address.port
14987
+ };
14988
+ if (typeof address.address !== "string" || !isIP(address.address)) return null;
14989
+ const boundHostname = listenerHostname(address.address);
14990
+ if (!boundHostname) return null;
14991
+ const aliases = loopbackAliases(boundHostname);
14992
+ if (!aliases) return {
14993
+ aliases: null,
14994
+ port: address.port
14995
+ };
14996
+ const configuredAlias = isIP(hostname) === 6 ? `[${hostname}]` : hostname;
14997
+ const configuredAliases = hostname === "localhost" ? loopbackAliases(hostname) : null;
14998
+ return {
14999
+ aliases: [.../* @__PURE__ */ new Set([
15000
+ ...aliases,
15001
+ configuredAlias,
15002
+ ...configuredAliases ?? []
15003
+ ])],
15004
+ port: address.port
15005
+ };
15006
+ } catch {
15007
+ return null;
15008
+ }
15009
+ }
15010
+ function parseHost(host, protocol) {
15011
+ const match = /^(\[[0-9a-fA-F:.]+\]|[a-zA-Z0-9.-]+)(?::([0-9]+))?$/.exec(host);
15012
+ if (!match?.[1]) return null;
15013
+ if (match[2] !== void 0) {
15014
+ const port = Number(match[2]);
15015
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
15016
+ }
15017
+ try {
15018
+ const parsed = new URL(`${protocol}//${host}`);
15019
+ const hostname = match[1].toLowerCase();
15020
+ if (!hostname.startsWith("[") && parsed.hostname !== hostname) return null;
15021
+ return parsed;
15022
+ } catch {
15023
+ return null;
15024
+ }
15025
+ }
15026
+ function validLoopbackAuthority(requestUrl, host, policy) {
15027
+ if (!host) return false;
15028
+ try {
15029
+ const url = new URL(requestUrl);
15030
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
15031
+ if (url.username || url.password) return false;
15032
+ const authority = parseHost(host, url.protocol);
15033
+ if (!authority || authority.host !== url.host) return false;
15034
+ return Number(authority.port || (url.protocol === "https:" ? 443 : 80)) === policy.port && policy.aliases.includes(authority.hostname);
15035
+ } catch {
15036
+ return false;
15037
+ }
15038
+ }
15039
+ /**
15040
+ * Protect every loopback viewer request before preflight and route dispatch.
15041
+ * Explicit external listeners retain their existing external-auth requirements.
15042
+ * Proxy forwarding headers never supply trusted listener or request authority.
15043
+ */
15044
+ function viewerAuthorityGuard(options) {
15045
+ return createMiddleware(async (c, next) => {
15046
+ if (!options) return next();
15047
+ const policy = listenerPolicy(options);
15048
+ if (!policy) return c.json({ error: "forbidden" }, 403);
15049
+ if (policy.aliases && !validLoopbackAuthority(c.req.url, c.req.header("Host"), {
15050
+ ...policy,
15051
+ aliases: policy.aliases
15052
+ })) return c.json({ error: "forbidden" }, 403);
15053
+ await next();
15054
+ });
15055
+ }
15056
+ //#endregion
14601
15057
  //#region src/account/context.ts
14602
15058
  function validId(value) {
14603
15059
  return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value && !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(value);
@@ -15428,6 +15884,7 @@ sqliteTable("raw_event_flush_batches", {
15428
15884
  observer_error_code: text("observer_error_code"),
15429
15885
  observer_error_message: text("observer_error_message"),
15430
15886
  attempt_count: integer("attempt_count").notNull().default(0),
15887
+ claim_generation: integer("claim_generation").notNull().default(0),
15431
15888
  created_at: text("created_at").notNull(),
15432
15889
  updated_at: text("updated_at").notNull()
15433
15890
  }, (table) => [
@@ -15522,6 +15979,10 @@ sqliteTable("sync_peers", {
15522
15979
  last_error: text("last_error"),
15523
15980
  runtime_version: text("runtime_version"),
15524
15981
  runtime_version_observed_at: text("runtime_version_observed_at"),
15982
+ sync_features_json: text("sync_features_json"),
15983
+ sync_features_observed_at: text("sync_features_observed_at"),
15984
+ relay_retry_after: text("relay_retry_after"),
15985
+ relay_rejections: integer("relay_rejections").notNull().default(0),
15525
15986
  highest_observed_direct_signature_version: integer("highest_observed_direct_signature_version"),
15526
15987
  discovered_via_coordinator_id: text("discovered_via_coordinator_id"),
15527
15988
  discovered_via_group_id: text("discovered_via_group_id"),
@@ -15555,7 +16016,8 @@ sqliteTable("sync_attempts", {
15555
16016
  local_sync_capability: text("local_sync_capability"),
15556
16017
  peer_sync_capability: text("peer_sync_capability"),
15557
16018
  negotiated_sync_capability: text("negotiated_sync_capability"),
15558
- failure_category: text("failure_category")
16019
+ failure_category: text("failure_category"),
16020
+ transport: text("transport")
15559
16021
  }, (table) => [
15560
16022
  index("idx_sync_attempts_peer_started").on(table.peer_device_id, table.started_at),
15561
16023
  index("idx_sync_attempts_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id),
@@ -16104,7 +16566,8 @@ var COORDINATOR_AUTH_STYLE = `
16104
16566
  .brand{display:flex;align-items:center;gap:.6rem;margin:0 0 1.5rem;color:var(--accent);font-size:.875rem;font-weight:700;letter-spacing:.02em}.brand::before{content:"";width:.65rem;height:.65rem;border-radius:3px;background:var(--accent)}
16105
16567
  h1,h2{font-family:inherit;font-weight:600;line-height:1.25;letter-spacing:-.025em}h1{font-size:1.6rem;margin:0 0 1rem}h2{font-size:1.05rem;margin:0 0 .5rem}p{margin:.5rem 0}section{padding:1.25rem 0;border-bottom:1px solid var(--border)}.eyebrow{font-size:.75rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-secondary)}
16106
16568
  .profile{display:flex;align-items:center;gap:1rem}.profile-text{min-width:0;overflow-wrap:anywhere}.avatar{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 3rem;width:3rem;height:3rem;border-radius:50%;background:var(--surface-2);color:var(--accent);overflow:hidden}.initials{font-weight:700}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.note{font-size:.875rem;color:var(--text-secondary)}
16107
- dl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}
16569
+ dl{margin:0}dt{font-size:.8rem;font-weight:600;color:var(--text-secondary);margin-top:1rem}dd{margin:.25rem 0 0}code{font-family:var(--font-mono);font-size:.8rem;overflow-wrap:anywhere;white-space:pre-wrap}code.command{white-space:nowrap;overflow-wrap:normal}
16570
+ label{display:block;font-weight:600;margin:1rem 0 .35rem}input[type=text]{font:inherit;font-family:var(--font-mono);font-size:1.1rem;letter-spacing:.12em;text-transform:uppercase;width:100%;min-height:44px;padding:.6rem .8rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--surface-2);color:var(--text-primary)}
16108
16571
  .actions{display:flex;flex-wrap:wrap;gap:.75rem;margin:1.5rem 0 0}form{margin:0}button,.link{font:inherit;font-size:.875rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:.65rem 1rem;border:1px solid var(--border-strong);border-radius:10px;background:var(--accent);color:var(--surface-0);cursor:pointer;text-decoration:none}button.secondary{background:transparent;color:var(--accent)}a{color:var(--accent)}button:hover,.link:hover{background:var(--accent-hover);color:var(--surface-0)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}
16109
16572
  @media(prefers-color-scheme:light){:root{color-scheme:light;--surface-0:#f7faf8;--surface-1:#fff;--surface-2:#eef5f1;--text-primary:#0b1016;--text-secondary:#3f4d5c;--accent:#0f8a68;--accent-hover:#0a6f53;--border:rgba(15,138,104,.16);--border-strong:rgba(15,138,104,.3)}button,.link,button:hover,.link:hover{color:#fff}button.secondary{color:var(--accent)}button.secondary:hover{color:#fff}}
16110
16573
  @media(max-width:30rem){body{padding:1rem}.actions{flex-direction:column}.actions form,.actions button,.actions .link{width:100%}h1{font-size:1.4rem}}
@@ -17048,6 +17511,452 @@ async function resumeAccountRebind(store, paths) {
17048
17511
  return { kind: "pending" };
17049
17512
  }
17050
17513
  //#endregion
17514
+ //#region src/sync-channel-dispatch.ts
17515
+ var MAX_REQUEST_BYTES = 1048576;
17516
+ var MAX_RESPONSE_BYTES = 16777216;
17517
+ function errorResponse(status, error) {
17518
+ return {
17519
+ status,
17520
+ headers: { "content-type": "application/json" },
17521
+ bodyBytes: new TextEncoder().encode(JSON.stringify({ error }))
17522
+ };
17523
+ }
17524
+ function hasForbiddenUrlCharacters(value) {
17525
+ return Array.from(value).some((char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127 || char === "\\" || char === "#");
17526
+ }
17527
+ function validLogicalUrl(url, target) {
17528
+ if (!target.startsWith("/") || target.startsWith("//") || hasForbiddenUrlCharacters(target)) return null;
17529
+ if (hasForbiddenUrlCharacters(url) || !/^https?:\/\//.test(url)) return null;
17530
+ try {
17531
+ const parsed = new URL(url);
17532
+ if (parsed.username || parsed.password || parsed.hash) return null;
17533
+ if (parsed.pathname + parsed.search !== target) return null;
17534
+ const authorityEnd = url.indexOf("/", url.indexOf("://") + 3);
17535
+ return authorityEnd >= 0 && url.slice(authorityEnd) === target ? parsed : null;
17536
+ } catch {
17537
+ return null;
17538
+ }
17539
+ }
17540
+ function checkCancellation(signal) {
17541
+ if (signal.aborted) throw new Error("Sync channel dispatch cancelled");
17542
+ }
17543
+ function invalidGetBody(method, body) {
17544
+ return method === "GET" && body.byteLength > 0;
17545
+ }
17546
+ async function collectResponse(response, signal) {
17547
+ const reader = response.body?.getReader();
17548
+ if (!reader) {
17549
+ checkCancellation(signal);
17550
+ return /* @__PURE__ */ new Uint8Array(0);
17551
+ }
17552
+ let cancelled = false;
17553
+ const cancel = () => {
17554
+ if (cancelled) return;
17555
+ cancelled = true;
17556
+ reader.cancel().catch(() => {});
17557
+ };
17558
+ signal.addEventListener("abort", cancel, { once: true });
17559
+ try {
17560
+ const chunks = [];
17561
+ let size = 0;
17562
+ while (true) {
17563
+ checkCancellation(signal);
17564
+ const chunk = await reader.read();
17565
+ checkCancellation(signal);
17566
+ if (chunk.done) break;
17567
+ size += chunk.value.byteLength;
17568
+ if (size > MAX_RESPONSE_BYTES) throw new Error("Sync channel response too large");
17569
+ chunks.push(chunk.value.slice());
17570
+ }
17571
+ const bytes = new Uint8Array(size);
17572
+ let offset = 0;
17573
+ for (const chunk of chunks) {
17574
+ bytes.set(chunk, offset);
17575
+ offset += chunk.byteLength;
17576
+ }
17577
+ return bytes;
17578
+ } catch {
17579
+ cancel();
17580
+ throw new Error("Sync channel response collection failed");
17581
+ } finally {
17582
+ signal.removeEventListener("abort", cancel);
17583
+ reader.releaseLock();
17584
+ }
17585
+ }
17586
+ function prepareChannelRequest(input) {
17587
+ const { method, target, url, peerPin, signal } = input;
17588
+ checkCancellation(signal);
17589
+ if (method !== "GET" && method !== "POST") return errorResponse(404, "not found");
17590
+ const parsed = validLogicalUrl(url, target);
17591
+ if (!parsed) return errorResponse(400, "invalid_request");
17592
+ const isOps = parsed.pathname === "/v1/ops";
17593
+ const isRead = method === "GET" && ["/v1/status", "/v1/snapshot"].includes(parsed.pathname);
17594
+ if (!isOps && !isRead) return errorResponse(404, "not found");
17595
+ const source = input.bodyBytes;
17596
+ if (source.byteLength > MAX_REQUEST_BYTES) return errorResponse(413, "payload_too_large");
17597
+ if (invalidGetBody(method, source)) return errorResponse(400, "invalid_request");
17598
+ const body = new Uint8Array(source);
17599
+ const headers = new Headers(input.headers);
17600
+ for (const name of [
17601
+ "host",
17602
+ "content-length",
17603
+ "connection"
17604
+ ]) headers.delete(name);
17605
+ return {
17606
+ request: new Request(url, {
17607
+ method,
17608
+ headers,
17609
+ signal,
17610
+ body: method === "POST" ? body : void 0
17611
+ }),
17612
+ peerPin
17613
+ };
17614
+ }
17615
+ function createSyncChannelDispatcher(options) {
17616
+ const storeFactory = options.storeFactory.bind(options);
17617
+ const pins = /* @__PURE__ */ new WeakMap();
17618
+ const app = createSyncApp$1({
17619
+ storeFactory,
17620
+ syncChannelPeerPin: (request) => pins.get(request) ?? null
17621
+ });
17622
+ return async (input) => {
17623
+ const prepared = prepareChannelRequest(input);
17624
+ if (!("request" in prepared)) return prepared;
17625
+ const { request, peerPin } = prepared;
17626
+ const signal = request.signal;
17627
+ pins.set(request, peerPin);
17628
+ try {
17629
+ checkCancellation(signal);
17630
+ const response = await app.fetch(request);
17631
+ const bodyBytes = await collectResponse(response, signal);
17632
+ return {
17633
+ status: response.status,
17634
+ headers: Object.fromEntries(response.headers),
17635
+ bodyBytes
17636
+ };
17637
+ } finally {
17638
+ pins.delete(request);
17639
+ }
17640
+ };
17641
+ }
17642
+ //#endregion
17643
+ //#region src/relay-reachability.ts
17644
+ /** Same rule as the sync daemon: an explicit directory, then `CODEMEM_KEYS_DIR`. */
17645
+ function resolveKeysDir(keysDir) {
17646
+ return keysDir?.trim() || process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
17647
+ }
17648
+ function sameDevice(a, b) {
17649
+ return a?.deviceId === b?.deviceId && a?.publicKey === b?.publicKey;
17650
+ }
17651
+ function readLocalDevice(db) {
17652
+ const row = db.prepare("SELECT device_id, public_key FROM sync_device LIMIT 1").get();
17653
+ if (!row?.device_id || !row.public_key) return null;
17654
+ return {
17655
+ deviceId: row.device_id,
17656
+ publicKey: row.public_key.trim()
17657
+ };
17658
+ }
17659
+ /** The peer's stored key, only while it still matches the pinned fingerprint. */
17660
+ function pinnedPeerKey(db, peerDeviceId) {
17661
+ const row = db.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(peerDeviceId);
17662
+ const publicKey = row?.public_key?.trim();
17663
+ if (!publicKey || !row?.pinned_fingerprint) return null;
17664
+ return fingerprintPublicKey(publicKey) === row.pinned_fingerprint ? publicKey : null;
17665
+ }
17666
+ function clientKey(config) {
17667
+ return `${config.url}\n${config.admissionUrl}\n${config.servicePublicKey}`;
17668
+ }
17669
+ function describe(resolution) {
17670
+ if (resolution.status === "ready") return "ready";
17671
+ if (resolution.status === "paused") return "paused: the relay service key changed; approve it with `codemem sync approve-relay-key`";
17672
+ return `disabled: ${resolution.reason}`;
17673
+ }
17674
+ /**
17675
+ * A coordinator without relay is the normal case, so plain disabled states
17676
+ * stay at info until the group has relayed once. A changed key, an invalid
17677
+ * reply, or losing a group that worked are warnings.
17678
+ */
17679
+ function levelFor(resolution, everReady) {
17680
+ if (resolution.status === "ready") return "info";
17681
+ if (resolution.status === "paused" || resolution.reason === "info_invalid") return "warn";
17682
+ return everReady ? "warn" : "info";
17683
+ }
17684
+ function buildClient(deps, config) {
17685
+ const { options, device } = deps;
17686
+ const db = options.store.db;
17687
+ return createRelayPeerClient({
17688
+ enabled: true,
17689
+ url: config.url,
17690
+ allowLoopbackWs: options.allowLoopback,
17691
+ servicePublicKey: config.servicePublicKey,
17692
+ deviceId: device.deviceId,
17693
+ localIdentity: {
17694
+ key: deps.key,
17695
+ expectedPin: device.publicKey
17696
+ },
17697
+ authorityId: config.authorityId,
17698
+ groupId: config.groupId,
17699
+ relayAudienceId: config.relayAudienceId,
17700
+ externalPathname: config.externalPathname,
17701
+ coordinator: createRelayCoordinatorClient({
17702
+ url: config.admissionUrl,
17703
+ allowLoopbackHttp: options.allowLoopback
17704
+ }),
17705
+ resolvePeerPin: (peerDeviceId) => pinnedPeerKey(db, peerDeviceId),
17706
+ validateLocal: () => sameDevice(readLocalDevice(db), device),
17707
+ onInboundFailure: (failure) => {
17708
+ const http = failure.httpCode ? ` http=${failure.httpCode}` : "";
17709
+ const diagnostic = `relay_target_failure stage=${failure.stage} reason=${failure.reason}${http}`;
17710
+ try {
17711
+ recordSyncAttempt(db, "", {
17712
+ ok: false,
17713
+ error: diagnostic,
17714
+ failureCategory: "connectivity"
17715
+ });
17716
+ } catch {
17717
+ options.log?.("[codemem] relay target diagnostic could not be persisted", "warn");
17718
+ }
17719
+ options.log?.(`[codemem] ${diagnostic}`, "warn");
17720
+ },
17721
+ onInbound: (_connection, context) => context.serve({
17722
+ origin: RELAY_LOGICAL_ORIGIN,
17723
+ dispatch: deps.dispatch
17724
+ })
17725
+ });
17726
+ }
17727
+ function loadDeps(options) {
17728
+ const device = readLocalDevice(options.store.db);
17729
+ if (!device) throw new Error("device identity missing");
17730
+ const bytes = loadPrivateKey(options.keysDir, options.store.dbPath, device.deviceId);
17731
+ if (!bytes) throw new Error("device private key unavailable");
17732
+ const dispatch = createSyncChannelDispatcher({ storeFactory: () => options.store });
17733
+ return {
17734
+ options,
17735
+ device,
17736
+ key: createPrivateKey(bytes),
17737
+ dispatch
17738
+ };
17739
+ }
17740
+ function defaultResolver(options, coordinatorUrl, timeoutS) {
17741
+ const settings = readRelayClientSettings(options.config);
17742
+ return (db, groupId) => resolveRelayGroup(db, {
17743
+ coordinatorUrl,
17744
+ groupId,
17745
+ settings,
17746
+ deviceId: readLocalDevice(db)?.deviceId ?? "",
17747
+ dbPath: options.store.dbPath,
17748
+ keysDir: options.keysDir,
17749
+ timeoutS,
17750
+ signal: options.signal,
17751
+ request: options.request
17752
+ });
17753
+ }
17754
+ function relayTargets(options) {
17755
+ if (!readRelayClientSettings(options.config).enabled) return null;
17756
+ const sync = readCoordinatorSyncConfig(options.config);
17757
+ const coordinatorUrl = sync.syncCoordinatorUrl.trim();
17758
+ if (!coordinatorUrl) return null;
17759
+ return {
17760
+ coordinatorUrl,
17761
+ timeoutS: sync.syncCoordinatorTimeoutS
17762
+ };
17763
+ }
17764
+ /**
17765
+ * The groups configured right now. Joining a group updates the config while
17766
+ * the viewer runs, so this is reread on every refresh. A different coordinator
17767
+ * yields no groups, because the resolver and pins belong to the startup one.
17768
+ */
17769
+ function configuredGroupIds(options, coordinatorUrl) {
17770
+ const sync = readCoordinatorSyncConfig(options.config);
17771
+ if (sync.syncCoordinatorUrl.trim() !== coordinatorUrl) return {
17772
+ groupIds: [],
17773
+ coordinatorChanged: true
17774
+ };
17775
+ return {
17776
+ groupIds: [...new Set(sync.syncCoordinatorGroups)],
17777
+ coordinatorChanged: false
17778
+ };
17779
+ }
17780
+ /** Owns one optional relay client per configured coordinator group. */
17781
+ var RelayGroupClients = class {
17782
+ options;
17783
+ coordinatorId;
17784
+ coordinatorUrl;
17785
+ resolve;
17786
+ log;
17787
+ groups = /* @__PURE__ */ new Map();
17788
+ deps;
17789
+ closed = false;
17790
+ refreshing;
17791
+ coordinatorChangeLogged = false;
17792
+ constructor(options, coordinatorId, coordinatorUrl, resolve, log) {
17793
+ this.options = options;
17794
+ this.coordinatorId = coordinatorId;
17795
+ this.coordinatorUrl = coordinatorUrl;
17796
+ this.resolve = resolve;
17797
+ this.log = log;
17798
+ this.reconcileGroups();
17799
+ }
17800
+ clientForGroup(groupId) {
17801
+ return this.groups.get(groupId)?.client;
17802
+ }
17803
+ clients() {
17804
+ return [...this.groups.values()].flatMap((state) => state.client ? [state.client] : []);
17805
+ }
17806
+ status() {
17807
+ return new Map([...this.groups].map(([groupId, state]) => [groupId, state.status]));
17808
+ }
17809
+ refresh() {
17810
+ if (this.closed) return Promise.resolve();
17811
+ this.refreshing ??= this.runRefresh().catch((error) => this.log(`[codemem] relay refresh failed: ${String(error)}`, "warn")).finally(() => {
17812
+ this.refreshing = void 0;
17813
+ });
17814
+ return this.refreshing;
17815
+ }
17816
+ async close() {
17817
+ this.closed = true;
17818
+ await this.refreshing;
17819
+ await this.dropAll();
17820
+ }
17821
+ async runRefresh() {
17822
+ await this.checkDeviceIdentity();
17823
+ await Promise.all(this.reconcileGroups().map((state) => this.dropClient(state)));
17824
+ const ids = [...this.groups.keys()];
17825
+ const results = await Promise.all(ids.map((groupId) => this.resolveSafely(groupId)));
17826
+ for (const [index, groupId] of ids.entries()) {
17827
+ const resolution = results[index];
17828
+ if (resolution) await this.apply(groupId, resolution);
17829
+ }
17830
+ }
17831
+ /** Adds newly configured groups and removes dropped ones. Returns the removed states to close. */
17832
+ reconcileGroups() {
17833
+ let current;
17834
+ try {
17835
+ current = configuredGroupIds(this.options, this.coordinatorUrl);
17836
+ } catch (error) {
17837
+ this.log(`[codemem] relay could not read the group list: ${String(error)}`, "warn");
17838
+ return [];
17839
+ }
17840
+ if (current.coordinatorChanged && !this.coordinatorChangeLogged) {
17841
+ this.coordinatorChangeLogged = true;
17842
+ this.log("[codemem] sync coordinator changed; restart codemem serve to relay through it", "warn");
17843
+ }
17844
+ const wanted = new Set(current.groupIds);
17845
+ const removed = [];
17846
+ for (const [groupId, state] of this.groups) {
17847
+ if (wanted.has(groupId)) continue;
17848
+ this.groups.delete(groupId);
17849
+ removed.push(state);
17850
+ }
17851
+ for (const groupId of wanted) if (!this.groups.has(groupId)) this.groups.set(groupId, { status: "disabled" });
17852
+ return removed;
17853
+ }
17854
+ /** A changed local identity invalidates the cached key and every client built from it. */
17855
+ async checkDeviceIdentity() {
17856
+ if (!this.deps || sameDevice(readLocalDevice(this.options.store.db), this.deps.device)) return;
17857
+ this.deps = void 0;
17858
+ await this.dropAll();
17859
+ this.log("[codemem] device identity changed; rebuilding relay clients", "warn");
17860
+ }
17861
+ async resolveSafely(groupId) {
17862
+ try {
17863
+ return await this.resolve(this.options.store.db, groupId);
17864
+ } catch {
17865
+ return {
17866
+ status: "disabled",
17867
+ groupId,
17868
+ reason: "info_unavailable"
17869
+ };
17870
+ }
17871
+ }
17872
+ /** A transient info failure keeps a client whose key is still the stored pin. */
17873
+ keepsClient(groupId, state, resolution) {
17874
+ if (resolution.status !== "disabled" || resolution.reason !== "info_unavailable") return false;
17875
+ if (!state.client) return false;
17876
+ const pin = readRelayServicePin(this.options.store.db, this.coordinatorId, groupId);
17877
+ return pin?.state === "pinned" && pin.pinnedKey === state.servicePublicKey;
17878
+ }
17879
+ async apply(groupId, resolution) {
17880
+ const state = this.groups.get(groupId);
17881
+ if (!state || this.closed) return;
17882
+ if (this.keepsClient(groupId, state, resolution)) {
17883
+ state.client?.revalidate();
17884
+ return;
17885
+ }
17886
+ state.status = resolution.status;
17887
+ if (resolution.status !== "ready") {
17888
+ await this.dropClient(state);
17889
+ this.report(groupId, state, describe(resolution), levelFor(resolution, !!state.everReady));
17890
+ return;
17891
+ }
17892
+ if (state.client && state.clientKey === clientKey(resolution.config)) {
17893
+ state.client.revalidate();
17894
+ return;
17895
+ }
17896
+ await this.dropClient(state);
17897
+ if (!this.closed) this.startClient(groupId, state, resolution.config);
17898
+ }
17899
+ startClient(groupId, state, config) {
17900
+ try {
17901
+ this.deps ??= loadDeps(this.options);
17902
+ state.client = buildClient(this.deps, config);
17903
+ state.clientKey = clientKey(config);
17904
+ state.servicePublicKey = config.servicePublicKey;
17905
+ state.everReady = true;
17906
+ this.report(groupId, state, "ready", "info");
17907
+ } catch (error) {
17908
+ state.status = "disabled";
17909
+ const reason = error instanceof Error ? error.message : String(error);
17910
+ this.report(groupId, state, `disabled: ${reason}`, state.everReady ? "warn" : "info");
17911
+ }
17912
+ }
17913
+ async dropAll() {
17914
+ await Promise.all([...this.groups.values()].map((state) => this.dropClient(state)));
17915
+ }
17916
+ async dropClient(state) {
17917
+ const client = state.client;
17918
+ state.client = void 0;
17919
+ state.clientKey = void 0;
17920
+ state.servicePublicKey = void 0;
17921
+ await client?.close().catch(() => {});
17922
+ }
17923
+ /** Logs each group's state once per change, so a persistent failure is not repeated every refresh. */
17924
+ report(groupId, state, message, level) {
17925
+ if (state.logged === message) return;
17926
+ state.logged = message;
17927
+ this.log(`[codemem] relay for group ${groupId}: ${message}`, level);
17928
+ }
17929
+ };
17930
+ /**
17931
+ * Device relay clients for `codemem serve`, one per configured coordinator
17932
+ * group that the coordinator advertises and whose service key is pinned.
17933
+ * Returns null when relay is off or coordinator sync is not configured, so
17934
+ * callers keep plain direct sync. Failures leave only that group direct-only.
17935
+ */
17936
+ function createViewerRelayReachability(options) {
17937
+ const targets = relayTargets(options);
17938
+ setLocalSyncFeature("relay", targets !== null);
17939
+ if (!targets) return null;
17940
+ const resolved = {
17941
+ ...options,
17942
+ keysDir: resolveKeysDir(options.keysDir)
17943
+ };
17944
+ const resolve = options.resolveGroup ?? defaultResolver(resolved, targets.coordinatorUrl, targets.timeoutS);
17945
+ const coordinatorId = relayCoordinatorEndpoint(targets.coordinatorUrl)?.coordinatorId ?? targets.coordinatorUrl;
17946
+ const groups = new RelayGroupClients(resolved, coordinatorId, targets.coordinatorUrl, resolve, options.log ?? (() => {}));
17947
+ return {
17948
+ reachability: createRelayPeerReachability({
17949
+ coordinatorId,
17950
+ clientForGroup: (groupId) => groups.clientForGroup(groupId),
17951
+ clients: () => groups.clients(),
17952
+ signal: options.signal
17953
+ }),
17954
+ refresh: () => groups.refresh(),
17955
+ close: () => groups.close(),
17956
+ status: () => groups.status()
17957
+ };
17958
+ }
17959
+ //#endregion
17051
17960
  //#region src/index.ts
17052
17961
  /**
17053
17962
  * @codemem/server — HTTP server (viewer, sync, API).
@@ -17058,29 +17967,15 @@ async function resumeAccountRebind(store, paths) {
17058
17967
  *
17059
17968
  * Entry: `codemem serve`
17060
17969
  */
17061
- /** Shared store instance — SQLite WAL mode handles concurrent reads safely. */
17062
- var sharedStore = null;
17063
- var sharedStoreClosePromise = null;
17064
- /** Get (or create) the shared store instance. Exported so the sweeper can share it. */
17065
- function getStore() {
17066
- if (!sharedStore) sharedStore = new MemoryStore(resolveDbPath());
17067
- return sharedStore;
17068
- }
17069
- /** Close a synchronous-only shared store. Async pack owners use closeStoreAsync(). */
17070
- function closeStore() {
17071
- sharedStore?.close();
17072
- sharedStore = null;
17073
- }
17074
- /** Drain semantic work before closing SQLite and releasing the shared store. */
17075
- function closeStoreAsync() {
17076
- if (sharedStoreClosePromise) return sharedStoreClosePromise;
17077
- if (!sharedStore) return Promise.resolve();
17078
- const store = sharedStore;
17079
- sharedStoreClosePromise = store.closeAsync().then(() => {
17080
- if (sharedStore === store) sharedStore = null;
17081
- sharedStoreClosePromise = null;
17082
- });
17083
- return sharedStoreClosePromise;
17970
+ /**
17971
+ * Prompt-pack transport plus, when `codemem serve` supplies a handler, the
17972
+ * thin-host memory-tool route. The profile advertises the route only when it
17973
+ * is mounted, so older clients and test apps see no capability.
17974
+ */
17975
+ function registerThinHostRoutes(app, storeFactory, call) {
17976
+ if (call) app.route("/", memoryToolCallRoutes(storeFactory, call));
17977
+ const capabilities = call ? [MEMORY_TOOL_CALL_CAPABILITY] : [];
17978
+ app.route("/", packTransportRoutes(storeFactory, { capabilities }));
17084
17979
  }
17085
17980
  function registerStaticRoutes(app) {
17086
17981
  const staticRoot = process.env.CODEMEM_VIEWER_STATIC_DIR ?? join(import.meta.dirname ?? ".", "../static");
@@ -17109,10 +18004,12 @@ function registerConfigRoutes(app, opts, sweeper) {
17109
18004
  getObserverApplyStatus: opts?.getObserverApplyStatus
17110
18005
  }));
17111
18006
  }
17112
- function registerAccountRoutes(app, options) {
17113
- if (!options) return;
17114
- const account = createAccountGuard(options);
17115
- app.use("*", account.middleware);
18007
+ function registerViewerBoundary(app, opts) {
18008
+ const options = opts?.accountLink;
18009
+ const account = options ? createAccountGuard(options) : null;
18010
+ if (account) app.use("*", account.middleware);
18011
+ app.use("*", viewerAuthorityGuard(opts?.viewerAuthority ?? options));
18012
+ if (!options || !account) return;
17116
18013
  app.route("/", account.routes);
17117
18014
  if (options.ownerRecovery) app.route("/", accountOwnerRecoveryRoutes(options.ownerRecovery));
17118
18015
  if (options.readContext) app.route("/", accountStatusRoutes({
@@ -17129,10 +18026,9 @@ function createApp(opts) {
17129
18026
  const storeFactory = opts?.storeFactory ?? getStore;
17130
18027
  const sweeper = opts?.sweeper ?? null;
17131
18028
  const getObserver = opts?.getObserver ?? (() => opts?.observer ?? null);
17132
- const getSyncRuntimeStatus = opts?.getSyncRuntimeStatus ?? (() => null);
17133
18029
  let invalidateTeamSetupSummary = () => {};
17134
18030
  const app = new Hono();
17135
- registerAccountRoutes(app, opts?.accountLink);
18031
+ registerViewerBoundary(app, opts);
17136
18032
  app.use("*", preflightHandler());
17137
18033
  app.use("*", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));
17138
18034
  const viewerTargetGuard = viewerTargetQueryGuard(storeFactory);
@@ -17144,7 +18040,7 @@ function createApp(opts) {
17144
18040
  app.route("/", statsRoutes(storeFactory));
17145
18041
  app.route("/", memoryRoutes(storeFactory));
17146
18042
  app.route("/", memoryToolRoutes(storeFactory));
17147
- app.route("/", packTransportRoutes(storeFactory));
18043
+ registerThinHostRoutes(app, storeFactory, opts?.memoryToolCall);
17148
18044
  app.route("/", fileContextRoutes(storeFactory));
17149
18045
  app.route("/", observerStatusRoutes({
17150
18046
  getStore: storeFactory,
@@ -17153,7 +18049,8 @@ function createApp(opts) {
17153
18049
  }));
17154
18050
  registerConfigRoutes(app, opts, sweeper);
17155
18051
  app.route("/", rawEventsRoutes(storeFactory, sweeper, opts?.rawEventInbox, opts?.rawEventTarget));
17156
- app.route("/", syncRoutes(storeFactory, getSyncRuntimeStatus, {
18052
+ app.route("/", syncRoutes(storeFactory, opts?.getSyncRuntimeStatus, {
18053
+ syncReachability: opts?.syncReachability,
17157
18054
  loadDeviceIdentityCoordinatorEvidence: opts?.loadDeviceIdentityCoordinatorEvidence,
17158
18055
  onRecipientPolicyTeamRenamed: () => invalidateTeamSetupSummary(),
17159
18056
  readCoordinatorConfig: opts?.readCoordinatorConfig,
@@ -17172,34 +18069,11 @@ function createApp(opts) {
17172
18069
  registerStaticRoutes(app);
17173
18070
  return app;
17174
18071
  }
17175
- /**
17176
- * Create the Hono app for peer-to-peer sync protocol routes only.
17177
- *
17178
- * This app is bound to a separate network-accessible listener
17179
- * (default 0.0.0.0:7337) so remote peers can reach the sync
17180
- * endpoints without exposing the viewer UI or local API routes.
17181
- *
17182
- * No CORS/origin guard is applied — sync requests are authenticated
17183
- * via cryptographic signature verification instead.
17184
- */
18072
+ /** Preserve the public server options while transport adapters use the narrower factory. */
17185
18073
  function createSyncApp(opts) {
17186
- const storeFactory = opts?.storeFactory ?? getStore;
17187
- const requestRateLimit = opts?.syncRequestRateLimit ?? {};
17188
- const rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();
17189
- const readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));
17190
- const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
17191
- const app = new Hono();
17192
- app.route("/", syncProtocolRoutes(storeFactory, { routeRateLimit: {
17193
- limiter: rateLimiter,
17194
- readLimit,
17195
- mutationLimit,
17196
- unauthenticatedReadLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit))),
17197
- unauthenticatedMutationLimit: Math.max(1, Math.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)))
17198
- } }));
17199
- app.all("*", (c) => c.json({ error: "not found" }, 404));
17200
- return app;
18074
+ return createSyncApp$1(opts);
17201
18075
  }
17202
18076
  //#endregion
17203
- export { FileRawEventInbox, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, getStore, listRecipientPolicyReconciliationStatus, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
18077
+ export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
17204
18078
 
17205
18079
  //# sourceMappingURL=index.js.map