File size: 5,447 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import type { Dirent } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { resolveStateDir } from "../../config/paths.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { resolvePathViaExistingAncestorSync } from "../../infra/boundary-path.js";
import { isErrno } from "../../infra/errno.js";
import { normalizeAgentId } from "../../routing/session-key.js";
import { listOpenClawRegisteredAgentDatabases } from "../../state/openclaw-agent-db-registry-listing.js";
import { runOpenClawAgentWriteTransaction } from "../../state/openclaw-agent-db.js";
import { listAgentEntries, resolveAgentDir } from "../agent-scope.js";
import { AUTH_STORE_VERSION } from "./constants.js";
import {
  loadPersistedAuthProfileStore,
  loadPersistedAuthProfileStoreAtDatabasePath,
} from "./persisted.js";
import { resolveAuthProfileDatabasePath } from "./sqlite.js";
import { saveAuthProfileStore } from "./store-runtime.js";
import type { AuthProfileStore } from "./types.js";

export type CandidateAuthProfileStore = {
  agentId: string;
  agentDir: string;
  databasePath: string;
  env: NodeJS.ProcessEnv;
};

type CandidateSource = {
  agentId: string;
  agentDir?: string;
  databasePath: string;
};

function canonicalizeDatabasePath(databasePath: string): string {
  return resolvePathViaExistingAncestorSync(path.resolve(databasePath));
}

async function collectStateRootCandidates(env: NodeJS.ProcessEnv): Promise<CandidateSource[]> {
  const agentsRoot = path.join(resolveStateDir(env), "agents");
  let entries: Dirent[];
  try {
    entries = await fs.readdir(agentsRoot, { withFileTypes: true });
  } catch (error) {
    if (isErrno(error) && error.code === "ENOENT") {
      return [];
    }
    throw error;
  }
  return entries
    .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
    .map((entry) => {
      const agentId = normalizeAgentId(entry.name);
      const agentDir = path.join(agentsRoot, entry.name, "agent");
      return {
        agentId,
        agentDir,
        databasePath: resolveAuthProfileDatabasePath(agentDir),
      };
    });
}

/**
 * Discover every auth-capable agent database once by canonical filesystem
 * identity. Registered paths cover custom database locations that cannot be
 * reconstructed from an agent directory.
 */
export async function listCandidateAuthProfileStores(params: {
  cfg: OpenClawConfig;
  env?: NodeJS.ProcessEnv;
}): Promise<CandidateAuthProfileStore[]> {
  const env = params.env ?? process.env;
  const sources: CandidateSource[] = [];
  for (const entry of listAgentEntries(params.cfg)) {
    const id = entry.id?.trim();
    if (!id) {
      continue;
    }
    const agentId = normalizeAgentId(id);
    const agentDir = path.resolve(resolveAgentDir(params.cfg, agentId, env));
    sources.push({
      agentId,
      agentDir,
      databasePath: resolveAuthProfileDatabasePath(agentDir),
    });
  }
  sources.push(...(await collectStateRootCandidates(env)));
  for (const registered of listOpenClawRegisteredAgentDatabases({ env })) {
    sources.push({
      agentId: normalizeAgentId(registered.agentId),
      databasePath: registered.path,
    });
  }

  const candidates = new Map<string, CandidateAuthProfileStore>();
  for (const source of sources) {
    const databasePath = canonicalizeDatabasePath(source.databasePath);
    const agentDir = source.agentDir ?? path.dirname(databasePath);
    if (!candidates.has(databasePath)) {
      candidates.set(databasePath, {
        agentId: source.agentId,
        agentDir,
        databasePath,
        env,
      });
    }
  }
  return [...candidates.values()].toSorted((left, right) =>
    left.databasePath.localeCompare(right.databasePath),
  );
}

/** Read an already-discovered candidate without creating a missing database. */
export function loadCandidateAuthProfileStore(
  candidate: CandidateAuthProfileStore,
): AuthProfileStore | null {
  return loadPersistedAuthProfileStoreAtDatabasePath(candidate.databasePath, "agent");
}

/**
 * Update one exact candidate database in a single synchronous SQLite
 * transaction. Callers serialize candidates externally; this never holds two
 * database transactions at once.
 */
export function updateCandidateAuthProfileStore(params: {
  candidate: CandidateAuthProfileStore;
  preserveProfileState?: boolean;
  profileId: string;
  updater: (store: AuthProfileStore) => boolean;
}): { changed: boolean; store: AuthProfileStore } {
  return runOpenClawAgentWriteTransaction(
    (database) => {
      const store = loadPersistedAuthProfileStore(params.candidate.agentDir, { database }) ?? {
        version: AUTH_STORE_VERSION,
        profiles: {},
      };
      const changed = params.updater(store);
      if (changed) {
        const profileIds = [params.profileId];
        saveAuthProfileStore(
          store,
          params.candidate.agentDir,
          {
            filterExternalAuthProfiles: false,
            syncExternalCli: false,
            ...(params.preserveProfileState
              ? {
                  preserveOrderProfileIds: profileIds,
                  preserveStateProfileIds: profileIds,
                }
              : {}),
          },
          database,
        );
      }
      return { changed, store };
    },
    {
      agentId: params.candidate.agentId,
      env: params.candidate.env,
      path: params.candidate.databasePath,
    },
  );
}