forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-profiles.ts
More file actions
225 lines (209 loc) · 6.61 KB
/
Copy pathlocal-profiles.ts
File metadata and controls
225 lines (209 loc) · 6.61 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import path from 'node:path';
import {
isSandboxModeEnabled,
resolveSandboxRuntimeConfigFromEnv,
sandboxAgentProfilesConfigPath,
} from '../sandbox-mode.js';
import { DEFAULT_MODEL_OPTION, sanitizeCustomModel } from './models.js';
import type {
RuntimeAgentDef,
RuntimeBuildOptions,
RuntimeModelOption,
} from './types.js';
const RUNTIME_PROJECT_ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../..',
);
function isInsideDir(parent: string, child: string): boolean {
const relative = path.relative(parent, child);
return (
relative === '' ||
(!relative.startsWith('..') && !path.isAbsolute(relative))
);
}
function localAgentProfilesFile(): string | null {
const explicit = process.env.OD_AGENT_PROFILES_CONFIG;
const explicitPath =
typeof explicit === 'string' && explicit.trim()
? path.resolve(explicit.trim())
: null;
if (isSandboxModeEnabled(process.env)) {
if (!process.env.OD_DATA_DIR?.trim()) return null;
const sandboxRuntime = resolveSandboxRuntimeConfigFromEnv(
process.env,
RUNTIME_PROJECT_ROOT,
);
if (!sandboxRuntime?.enabled) return null;
if (
explicitPath &&
isInsideDir(sandboxRuntime.roots.agentHomeDir, explicitPath)
) {
return explicitPath;
}
return sandboxAgentProfilesConfigPath(sandboxRuntime);
}
if (explicitPath) {
return explicitPath;
}
return path.join(homedir(), '.open-design', 'agents.local.json');
}
function normalizeStringList(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.filter(
(item): item is string =>
typeof item === 'string' &&
item.length > 0 &&
!item.includes('\0'),
);
}
function normalizeEnvMap(value: unknown): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const out: Record<string, string> = {};
for (const [key, raw] of Object.entries(value)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
if (
typeof raw === 'string' ||
typeof raw === 'number' ||
typeof raw === 'boolean'
) {
out[key] = String(raw);
}
}
return out;
}
function normalizeModelOptions(value: unknown): RuntimeModelOption[] | null {
if (!Array.isArray(value)) return null;
const out = [DEFAULT_MODEL_OPTION];
const seen = new Set(['default']);
for (const item of value) {
const id =
typeof item === 'string'
? item.trim()
: item && typeof item === 'object' && typeof item.id === 'string'
? item.id.trim()
: '';
if (!sanitizeCustomModel(id) || seen.has(id)) continue;
seen.add(id);
const label =
item && typeof item === 'object' && typeof item.label === 'string'
? item.label.trim()
: '';
out.push({ id, label: label || id });
}
return out.length > 1 ? out : null;
}
function normalizeDefaultModel(value: unknown): string | null {
return typeof value === 'string' ? sanitizeCustomModel(value) : null;
}
function optionsWithDefaultModel(
options: RuntimeBuildOptions | undefined,
defaultModel: string | null,
): RuntimeBuildOptions | undefined {
if (
defaultModel == null ||
(options?.model != null && options.model !== 'default')
) {
return options;
}
return { ...options, model: defaultModel };
}
function createLocalAgentDef(
raw: unknown,
baseDefs: RuntimeAgentDef[],
): RuntimeAgentDef | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const profile = raw as Record<string, unknown>;
const id = typeof profile.id === 'string' ? profile.id.trim() : '';
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id)) return null;
if (baseDefs.some((def) => def.id === id)) return null;
const hasExplicitBaseAgent =
typeof profile.baseAgent === 'string' &&
profile.baseAgent.trim().length > 0;
const baseId = hasExplicitBaseAgent
? (profile.baseAgent as string).trim()
: 'claude';
const base = baseDefs.find((def) => def.id === baseId);
if (!base) {
if (hasExplicitBaseAgent) {
console.warn(
`[agents] skipping local profile "${id}": unknown baseAgent "${baseId}"`,
);
}
return null;
}
const bin =
typeof profile.bin === 'string' &&
profile.bin.trim() &&
!profile.bin.includes('\0')
? profile.bin.trim()
: base.bin;
const name =
typeof profile.name === 'string' && profile.name.trim()
? profile.name.trim()
: id;
const prefixArgs = normalizeStringList(profile.args ?? profile.prefixArgs);
const env = normalizeEnvMap(profile.env);
const fallbackModels =
normalizeModelOptions(profile.models ?? profile.fallbackModels) ??
base.fallbackModels;
const versionArgs = normalizeStringList(profile.versionArgs);
const helpArgs = normalizeStringList(profile.helpArgs);
const defaultModel = normalizeDefaultModel(profile.defaultModel);
const { authProbe: baseAuthProbe, ...baseWithoutAuthProbe } = base;
return {
...baseWithoutAuthProbe,
id,
name,
bin,
versionArgs: versionArgs.length > 0 ? versionArgs : base.versionArgs,
...(helpArgs.length > 0 ? { helpArgs } : {}),
fallbackModels,
env,
// Carry the base adapter's classifier identity so an inherited probe keeps
// its tailored auth parsing under the profile id (#4456).
...(prefixArgs.length === 0 && baseAuthProbe
? { authProbe: { ...baseAuthProbe, classifierAgentId: base.id } }
: {}),
buildArgs: (prompt, imagePaths, extraAllowedDirs, options, runtimeContext) => [
...prefixArgs,
...base.buildArgs(
prompt,
imagePaths,
extraAllowedDirs,
optionsWithDefaultModel(options, defaultModel),
runtimeContext,
),
],
};
}
export function readLocalAgentProfileDefs(
baseDefs: RuntimeAgentDef[],
): RuntimeAgentDef[] {
const profilesFile = localAgentProfilesFile();
if (profilesFile == null) return [];
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(profilesFile, 'utf8'));
} catch {
return [];
}
const profiles = Array.isArray(parsed)
? parsed
: parsed &&
typeof parsed === 'object' &&
Array.isArray((parsed as { agents?: unknown }).agents)
? (parsed as { agents: unknown[] }).agents
: [];
const defs: RuntimeAgentDef[] = [];
const seen = new Set(baseDefs.map((def) => def.id));
for (const profile of profiles) {
const def = createLocalAgentDef(profile, baseDefs);
if (!def || seen.has(def.id)) continue;
seen.add(def.id);
defs.push(def);
}
return defs;
}