@leavewhite9088/harness-bus 0.2.0 → 0.2.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.
- package/ARCHITECTURE.md +81 -81
- package/LICENSE +21 -21
- package/README.md +86 -86
- package/SETUP_FOR_AI.md +79 -79
- package/package.json +4 -2
- package/packages/agentd/agentd.config.json +3 -1
- package/packages/agentd/cli/commands.mjs +854 -810
- package/packages/agentd/cli/format.mjs +294 -238
- package/packages/agentd/cli/hbus.mjs +14 -14
- package/packages/agentd/cli/index.mjs +4 -4
- package/packages/agentd/cli/skill/SKILL.md +66 -61
- package/packages/agentd/cli/skill/references/custom.md +12 -0
- package/packages/agentd/cli/skill/references/playbooks.md +89 -86
- package/packages/agentd/cli/skill/references/routing.md +43 -35
- package/packages/agentd/cli/skill-install.mjs +157 -140
- package/packages/agentd/cli/update.mjs +221 -221
- package/packages/agentd/client/index.mjs +3 -3
- package/packages/agentd/contexts/executor.md +13 -12
- package/packages/agentd/contexts/templates/architect.md +12 -12
- package/packages/agentd/contexts/templates/coder.md +12 -12
- package/packages/agentd/contexts/templates/debugger.md +12 -12
- package/packages/agentd/contexts/templates/researcher.md +12 -12
- package/packages/agentd/contexts/templates/reviewer.md +12 -12
- package/packages/agentd/contexts/templates/tester.md +12 -12
- package/packages/agentd/core/base/data-dir.mjs +39 -39
- package/packages/agentd/core/base/index.mjs +5 -5
- package/packages/agentd/core/base/protocol.mjs +13 -13
- package/packages/agentd/core/env/config.mjs +52 -1
- package/packages/agentd/core/env/index.mjs +6 -1
- package/packages/agentd/core/env/install.mjs +82 -4
- package/packages/agentd/core/pi/index.mjs +1 -1
- package/packages/agentd/core/pi/rpc.mjs +206 -206
- package/packages/agentd/core/pool/acp/client.mjs +7 -9
- package/packages/agentd/core/pool/acp/process.mjs +27 -18
- package/packages/agentd/core/pool/acp/run-tracker.mjs +293 -293
- package/packages/agentd/core/pool/acp/sessions.mjs +465 -465
- package/packages/agentd/core/pool/acp/turn-runner.mjs +5 -3
- package/packages/agentd/core/pool/index.mjs +2 -2
- package/packages/agentd/core/pool/instances.mjs +3 -5
- package/packages/agentd/core/pool/probe.mjs +91 -85
- package/packages/agentd/core/pool/registry.mjs +45 -1
- package/packages/agentd/core/pool/support/compaction.mjs +2 -43
- package/packages/agentd/core/pool/support/index.mjs +1 -1
- package/packages/agentd/core/prompts/index.mjs +12 -12
- package/packages/agentd/core/prompts/rules.mjs +22 -22
- package/packages/agentd/core/prompts/templates.mjs +172 -172
- package/packages/agentd/core/providers/index.mjs +14 -14
- package/packages/agentd/core/providers/store.mjs +206 -206
- package/packages/agentd/core/records/cleanup.mjs +51 -51
- package/packages/agentd/core/records/index.mjs +8 -8
- package/packages/agentd/core/records/metrics.mjs +73 -73
- package/packages/agentd/core/records/recovery.mjs +39 -39
- package/packages/agentd/core/records/transcripts.mjs +122 -122
- package/packages/agentd/core/threads/index.mjs +18 -17
- package/packages/agentd/core/threads/manager.mjs +498 -476
- package/packages/agentd/core/threads/paths.mjs +78 -78
- package/packages/agentd/core/threads/store.mjs +146 -125
- package/packages/agentd/daemon/agentd.mjs +58 -58
- package/packages/agentd/daemon/events.mjs +126 -126
- package/packages/agentd/daemon/guard.mjs +127 -127
- package/packages/agentd/daemon/lifecycle.mjs +61 -61
- package/packages/agentd/daemon/ops/index.mjs +15 -15
- package/packages/agentd/daemon/ops/providers.mjs +46 -46
- package/packages/agentd/daemon/ops/run.mjs +413 -400
- package/packages/agentd/daemon/ops/system.mjs +76 -69
- package/packages/agentd/daemon/ops/threads.mjs +156 -153
- package/packages/agentd/daemon/server.mjs +130 -130
- package/packages/agentd/package.json +1 -1
- package/packages/agentd/pi-adapter/acp-adapter.mjs +501 -501
- package/packages/agentd/scripts/restart-daemon.mjs +74 -74
- package/packages/agentd/scripts/run-isolated.mjs +42 -42
- package/packages/agentd/scripts/run-unit.mjs +28 -28
- package/packages/backend/src/daemon.mjs +69 -69
- package/packages/backend/src/server.mjs +270 -270
- package/packages/drivers/{agy.mjs → agy/index.mjs} +2 -1
- package/packages/drivers/{claude.mjs → claude/index.mjs} +23 -1
- package/packages/drivers/{codex.mjs → codex/index.mjs} +2 -1
- package/packages/drivers/{dsh.mjs → dsh/index.mjs} +3 -2
- package/packages/drivers/grok/index.mjs +96 -0
- package/packages/drivers/index.mjs +25 -12
- package/packages/drivers/{kimi.mjs → kimi/index.mjs} +2 -1
- package/packages/drivers/{mcode.mjs → mcode/index.mjs} +2 -1
- package/packages/drivers/{opencode.mjs → opencode/index.mjs} +2 -1
- package/packages/drivers/{pi.mjs → pi/index.mjs} +3 -2
- package/packages/drivers/probes/acp.mjs +109 -109
- package/packages/drivers/probes/index.mjs +131 -129
- package/packages/drivers/probes/provider.mjs +222 -222
- package/packages/drivers/qoder/index.mjs +32 -0
- package/packages/drivers/{bin.mjs → shared/bin.mjs} +2 -0
- package/packages/drivers/shared/index.mjs +2 -0
- package/packages/preflight/bin/preflight.mjs +116 -116
- package/packages/preflight/src/index.mjs +5 -5
- package/packages/preflight/src/report.mjs +18 -1
- package/packages/web/dist/apple-touch-icon.png +0 -0
- package/packages/web/dist/assets/index-CT8dIwav.css +2 -0
- package/packages/web/dist/assets/index-CypTUMFB.js +79 -0
- package/packages/web/dist/favicon-32.png +0 -0
- package/packages/web/dist/favicon.svg +19 -15
- package/packages/web/dist/index.html +5 -5
- package/packages/web/dist/assets/index-B2kdkHNw.js +0 -79
- package/packages/web/dist/assets/index-DQTyjC4x.css +0 -2
- /package/packages/drivers/{dsh-sessions.mjs → dsh/sessions.mjs} +0 -0
- /package/packages/drivers/{pi-catalog.mjs → pi/catalog.mjs} +0 -0
- /package/packages/drivers/{lib.mjs → shared/lib.mjs} +0 -0
|
@@ -1,206 +1,206 @@
|
|
|
1
|
-
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
-
import { tmpdir } from 'node:os';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import {
|
|
5
|
-
applyProvider,
|
|
6
|
-
checkEndpoint,
|
|
7
|
-
discoverModels,
|
|
8
|
-
drivers,
|
|
9
|
-
getDriver,
|
|
10
|
-
providerProtocolOf,
|
|
11
|
-
removeGlobalProvider,
|
|
12
|
-
scrub,
|
|
13
|
-
syncGlobalProvider,
|
|
14
|
-
testProvider,
|
|
15
|
-
} from '../../../drivers/index.mjs';
|
|
16
|
-
import { GLOBAL_DIR, atomicWriteJson, instanceIdOf, projectPath } from '../base/index.mjs';
|
|
17
|
-
import { PI_ADAPTER_PATH, currentInstall, piPaths } from '../env/index.mjs';
|
|
18
|
-
|
|
19
|
-
export { checkEndpoint };
|
|
20
|
-
|
|
21
|
-
export const PROVIDERS_FILE = process.env.AGENTD_PROVIDERS_FILE || join(GLOBAL_DIR, 'providers.json');
|
|
22
|
-
const ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
23
|
-
const PROTOCOLS = ['anthropic', 'openai'];
|
|
24
|
-
|
|
25
|
-
function load() {
|
|
26
|
-
try {
|
|
27
|
-
const data = JSON.parse(readFileSync(PROVIDERS_FILE, 'utf8'));
|
|
28
|
-
return data && typeof data === 'object' && data.providers ? data : { schema: 1, providers: {} };
|
|
29
|
-
} catch {
|
|
30
|
-
return { schema: 1, providers: {} };
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function persist(data) {
|
|
35
|
-
atomicWriteJson(PROVIDERS_FILE, data, { mode: 0o600 });
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function view(p) {
|
|
39
|
-
return { id: p.id, name: p.name, keyHint: p.apiKey ? `…${p.apiKey.slice(-4)}` : '', endpoints: p.endpoints, models: p.models, contexts: p.contexts ?? {}, types: p.types, updatedAt: p.updatedAt };
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export const providerClis = () =>
|
|
43
|
-
Object.values(drivers)
|
|
44
|
-
.filter((d) => d.provider)
|
|
45
|
-
.map((d) => ({ type: d.type, label: d.label, protocol: d.provider.protocol, scope: d.provider.scope }));
|
|
46
|
-
|
|
47
|
-
const defaultTypes = () => providerClis().map((c) => c.type);
|
|
48
|
-
|
|
49
|
-
const withTypes = (p) => ({ ...p, types: Array.isArray(p.types) ? p.types : defaultTypes() });
|
|
50
|
-
|
|
51
|
-
export const listProviders = () => Object.values(load().providers).map((p) => view(withTypes(p)));
|
|
52
|
-
|
|
53
|
-
export function getProvider(id) {
|
|
54
|
-
const p = load().providers[id];
|
|
55
|
-
if (!p) throw new Error(`unknown provider "${id}"`);
|
|
56
|
-
return withTypes(p);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const cleanUrl = (v, what) => {
|
|
60
|
-
const s = String(v ?? '').trim().replace(/\/+$/, '');
|
|
61
|
-
if (!s) return null;
|
|
62
|
-
let u;
|
|
63
|
-
try {
|
|
64
|
-
u = new URL(s);
|
|
65
|
-
} catch {
|
|
66
|
-
throw new Error(`${what} is not a URL: ${s.slice(0, 80)}`);
|
|
67
|
-
}
|
|
68
|
-
if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`${what} must start with http:// or https://`);
|
|
69
|
-
return s;
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
export function saveProvider({ id, name, apiKey, endpoints = {}, models = [], contexts, types }) {
|
|
73
|
-
if (!ID_RE.test(String(id ?? ''))) throw new Error('provider id: lowercase letters, digits and "-", at most 32, starting with a letter or digit');
|
|
74
|
-
const data = load();
|
|
75
|
-
const old = data.providers[id];
|
|
76
|
-
const key = String(apiKey ?? '').trim() || old?.apiKey;
|
|
77
|
-
if (!key) throw new Error('an API key is required');
|
|
78
|
-
if (key.startsWith('!')) throw new Error('an API key must not start with "!"');
|
|
79
|
-
const eps = {};
|
|
80
|
-
for (const proto of PROTOCOLS) {
|
|
81
|
-
const url = cleanUrl(endpoints[proto], `${proto} endpoint`);
|
|
82
|
-
if (url) eps[proto] = url;
|
|
83
|
-
}
|
|
84
|
-
if (!Object.keys(eps).length) throw new Error('give at least one endpoint (anthropic or openai)');
|
|
85
|
-
const list = [...new Set((Array.isArray(models) ? models : String(models).split(/[,\s]+/)).map((m) => String(m).trim()).filter(Boolean))];
|
|
86
|
-
if (!list.length) throw new Error('give at least one model id');
|
|
87
|
-
const known = providerClis().map((c) => c.type);
|
|
88
|
-
const allowed = types === undefined ? (old ? withTypes(old).types : defaultTypes()) : [...new Set(Array.isArray(types) ? types.map(String) : [])];
|
|
89
|
-
const bad = allowed.find((t) => !known.includes(t));
|
|
90
|
-
if (bad) throw new Error(`"${bad}" cannot take a provider; choose from: ${known.join(', ')}`);
|
|
91
|
-
// The context length of a model, where a person or the endpoint gave one: a CLI otherwise assumes a small default (pi: 128K).
|
|
92
|
-
const given = contexts === undefined ? (old?.contexts ?? {}) : contexts && typeof contexts === 'object' ? contexts : {};
|
|
93
|
-
const ctx = Object.fromEntries(list.filter((m) => Number(given[m]) >= 1000 && Number(given[m]) <= 1e8).map((m) => [m, Math.round(Number(given[m]))]));
|
|
94
|
-
const record = { id, name: String(name || id).slice(0, 80), apiKey: key, endpoints: eps, models: list, contexts: ctx, types: allowed, updatedAt: new Date().toISOString() };
|
|
95
|
-
data.providers[id] = record;
|
|
96
|
-
persist(data);
|
|
97
|
-
return view(record);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export function removeProvider(id) {
|
|
101
|
-
const data = load();
|
|
102
|
-
if (!data.providers[id]) throw new Error(`unknown provider "${id}"`);
|
|
103
|
-
delete data.providers[id];
|
|
104
|
-
persist(data);
|
|
105
|
-
const install = currentInstall();
|
|
106
|
-
for (const d of Object.values(drivers)) {
|
|
107
|
-
if (d.provider?.scope === 'global') {
|
|
108
|
-
try {
|
|
109
|
-
removeGlobalProvider({ driver: d, install, piAdapterPath: PI_ADAPTER_PATH, providerId: id });
|
|
110
|
-
} catch {
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
return { id, removed: true };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export async function discoverProviderModels({ id, endpoints, apiKey }) {
|
|
118
|
-
const old = id ? load().providers[id] : null;
|
|
119
|
-
const key = String(apiKey ?? '').trim() || old?.apiKey;
|
|
120
|
-
if (!key) throw new Error('an API key is needed to list the models');
|
|
121
|
-
const eps = {};
|
|
122
|
-
for (const proto of PROTOCOLS) {
|
|
123
|
-
const url = cleanUrl(endpoints?.[proto] ?? old?.endpoints?.[proto], `${proto} endpoint`);
|
|
124
|
-
if (url) eps[proto] = url;
|
|
125
|
-
}
|
|
126
|
-
if (!Object.keys(eps).length) throw new Error('give an endpoint first');
|
|
127
|
-
return discoverModels({ endpoints: eps, apiKey: key });
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export function providerSupport(p) {
|
|
131
|
-
return Object.values(drivers).map((d) => {
|
|
132
|
-
const cap = d.provider;
|
|
133
|
-
if (!cap) return { type: d.type, label: d.label, supported: false, reason: 'no way to take another provider' };
|
|
134
|
-
const proto = providerProtocolOf(d, p.endpoints);
|
|
135
|
-
const has = Boolean(proto && p.endpoints?.[proto]);
|
|
136
|
-
const needed = Array.isArray(cap.protocols) && cap.protocols.length > 1 ? cap.protocols.join(' / ') : cap.protocol;
|
|
137
|
-
return {
|
|
138
|
-
type: d.type,
|
|
139
|
-
label: d.label,
|
|
140
|
-
supported: has,
|
|
141
|
-
enabled: (p.types ?? []).includes(d.type),
|
|
142
|
-
protocol: proto || cap.protocol,
|
|
143
|
-
scope: cap.scope,
|
|
144
|
-
reason: has ? null : `needs an ${needed} endpoint`,
|
|
145
|
-
};
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export function cleanInstanceProvider(value, type) {
|
|
150
|
-
if (value == null || value === '' || value.id === '' || value.id == null) return null;
|
|
151
|
-
const driver = getDriver(type);
|
|
152
|
-
if (!driver?.provider) throw new Error(`${type} cannot use another provider`);
|
|
153
|
-
const p = getProvider(String(value.id));
|
|
154
|
-
if (!p.types.includes(type)) throw new Error(`provider "${p.id}" is not enabled for ${type}: tick it in the provider's settings first`);
|
|
155
|
-
const proto = providerProtocolOf(driver, p.endpoints);
|
|
156
|
-
if (!proto || !p.endpoints[proto]) {
|
|
157
|
-
const needed = Array.isArray(driver.provider.protocols) && driver.provider.protocols.length > 1 ? driver.provider.protocols.join(' or ') : driver.provider.protocol;
|
|
158
|
-
throw new Error(`provider "${p.id}" has no ${needed} endpoint, which ${type} needs`);
|
|
159
|
-
}
|
|
160
|
-
const model = String(value.model || p.models[0]);
|
|
161
|
-
return { id: p.id, model: model.slice(0, 200) };
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
export function providerForSpawn({ driver, name, choice, env }) {
|
|
165
|
-
const p = getProvider(choice.id);
|
|
166
|
-
if (!env?.PI_CLI && driver.type === 'pi') env = { ...env, PI_CLI: piPaths().cli };
|
|
167
|
-
const dir = projectPath(name, 'provider-config', String(instanceIdOf(name)).replace(/[^a-zA-Z0-9._~-]/g, '_'));
|
|
168
|
-
const r = applyProvider({ driver, provider: p, model: choice.model, dir, env });
|
|
169
|
-
if (!r.ok) throw new Error(`provider "${p.id}" cannot be used by ${driver.type}: ${r.skipped}`);
|
|
170
|
-
if (r.applied?.global) {
|
|
171
|
-
syncGlobalProvider({ driver, install: currentInstall(), piAdapterPath: PI_ADAPTER_PATH, applied: r.applied, dir, env: { ...process.env, ...env, ...r.env } });
|
|
172
|
-
}
|
|
173
|
-
return { env: r.env, args: r.args, model: r.model };
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export async function testProviderAll(id, { model, types } = {}) {
|
|
177
|
-
const p = getProvider(id);
|
|
178
|
-
const secrets = [p.apiKey];
|
|
179
|
-
const testModel = model || p.models[0];
|
|
180
|
-
const endpoints = {};
|
|
181
|
-
await Promise.all(
|
|
182
|
-
Object.entries(p.endpoints).map(async ([protocol, endpoint]) => {
|
|
183
|
-
endpoints[protocol] = await checkEndpoint({ protocol, endpoint, apiKey: p.apiKey, model: testModel });
|
|
184
|
-
}),
|
|
185
|
-
);
|
|
186
|
-
const install = currentInstall();
|
|
187
|
-
const wanted = Object.values(drivers).filter((d) => p.types.includes(d.type) && (!types || types.includes(d.type)));
|
|
188
|
-
const results = await Promise.all(
|
|
189
|
-
wanted.map(async (d) => {
|
|
190
|
-
const proto = providerProtocolOf(d, p.endpoints);
|
|
191
|
-
const ep = proto ? endpoints[proto] : null;
|
|
192
|
-
if (!d.provider) return { type: d.type, ok: false, skipped: 'no way to take another provider', detail: 'no way to take another provider', ms: 0 };
|
|
193
|
-
if (!ep) return { type: d.type, ok: false, skipped: `needs an ${proto} endpoint`, detail: `needs an ${proto} endpoint, and this provider has none`, ms: 0 };
|
|
194
|
-
if (!ep.ok && ep.status === null) {
|
|
195
|
-
return { type: d.type, ok: false, skipped: 'endpoint unreachable', detail: `the ${proto} endpoint could not be reached: ${ep.detail}`, ms: 0 };
|
|
196
|
-
}
|
|
197
|
-
const workRoot = mkdtempSync(join(tmpdir(), `provider-test-${d.type}-`));
|
|
198
|
-
try {
|
|
199
|
-
return await testProvider({ driver: d, install, piAdapterPath: PI_ADAPTER_PATH, provider: p, model: testModel, workRoot, timeoutMs: 120_000 });
|
|
200
|
-
} finally {
|
|
201
|
-
rmSync(workRoot, { recursive: true, force: true });
|
|
202
|
-
}
|
|
203
|
-
}),
|
|
204
|
-
);
|
|
205
|
-
return { id, model: testModel, at: new Date().toISOString(), endpoints, results: results.map((r) => ({ ...r, detail: scrub(r.detail, secrets) })) };
|
|
206
|
-
}
|
|
1
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
applyProvider,
|
|
6
|
+
checkEndpoint,
|
|
7
|
+
discoverModels,
|
|
8
|
+
drivers,
|
|
9
|
+
getDriver,
|
|
10
|
+
providerProtocolOf,
|
|
11
|
+
removeGlobalProvider,
|
|
12
|
+
scrub,
|
|
13
|
+
syncGlobalProvider,
|
|
14
|
+
testProvider,
|
|
15
|
+
} from '../../../drivers/index.mjs';
|
|
16
|
+
import { GLOBAL_DIR, atomicWriteJson, instanceIdOf, projectPath } from '../base/index.mjs';
|
|
17
|
+
import { PI_ADAPTER_PATH, currentInstall, piPaths } from '../env/index.mjs';
|
|
18
|
+
|
|
19
|
+
export { checkEndpoint };
|
|
20
|
+
|
|
21
|
+
export const PROVIDERS_FILE = process.env.AGENTD_PROVIDERS_FILE || join(GLOBAL_DIR, 'providers.json');
|
|
22
|
+
const ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
23
|
+
const PROTOCOLS = ['anthropic', 'openai'];
|
|
24
|
+
|
|
25
|
+
function load() {
|
|
26
|
+
try {
|
|
27
|
+
const data = JSON.parse(readFileSync(PROVIDERS_FILE, 'utf8'));
|
|
28
|
+
return data && typeof data === 'object' && data.providers ? data : { schema: 1, providers: {} };
|
|
29
|
+
} catch {
|
|
30
|
+
return { schema: 1, providers: {} };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function persist(data) {
|
|
35
|
+
atomicWriteJson(PROVIDERS_FILE, data, { mode: 0o600 });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function view(p) {
|
|
39
|
+
return { id: p.id, name: p.name, keyHint: p.apiKey ? `…${p.apiKey.slice(-4)}` : '', endpoints: p.endpoints, models: p.models, contexts: p.contexts ?? {}, types: p.types, updatedAt: p.updatedAt };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const providerClis = () =>
|
|
43
|
+
Object.values(drivers)
|
|
44
|
+
.filter((d) => d.provider)
|
|
45
|
+
.map((d) => ({ type: d.type, label: d.label, protocol: d.provider.protocol, scope: d.provider.scope }));
|
|
46
|
+
|
|
47
|
+
const defaultTypes = () => providerClis().map((c) => c.type);
|
|
48
|
+
|
|
49
|
+
const withTypes = (p) => ({ ...p, types: Array.isArray(p.types) ? p.types : defaultTypes() });
|
|
50
|
+
|
|
51
|
+
export const listProviders = () => Object.values(load().providers).map((p) => view(withTypes(p)));
|
|
52
|
+
|
|
53
|
+
export function getProvider(id) {
|
|
54
|
+
const p = load().providers[id];
|
|
55
|
+
if (!p) throw new Error(`unknown provider "${id}"`);
|
|
56
|
+
return withTypes(p);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const cleanUrl = (v, what) => {
|
|
60
|
+
const s = String(v ?? '').trim().replace(/\/+$/, '');
|
|
61
|
+
if (!s) return null;
|
|
62
|
+
let u;
|
|
63
|
+
try {
|
|
64
|
+
u = new URL(s);
|
|
65
|
+
} catch {
|
|
66
|
+
throw new Error(`${what} is not a URL: ${s.slice(0, 80)}`);
|
|
67
|
+
}
|
|
68
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`${what} must start with http:// or https://`);
|
|
69
|
+
return s;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export function saveProvider({ id, name, apiKey, endpoints = {}, models = [], contexts, types }) {
|
|
73
|
+
if (!ID_RE.test(String(id ?? ''))) throw new Error('provider id: lowercase letters, digits and "-", at most 32, starting with a letter or digit');
|
|
74
|
+
const data = load();
|
|
75
|
+
const old = data.providers[id];
|
|
76
|
+
const key = String(apiKey ?? '').trim() || old?.apiKey;
|
|
77
|
+
if (!key) throw new Error('an API key is required');
|
|
78
|
+
if (key.startsWith('!')) throw new Error('an API key must not start with "!"');
|
|
79
|
+
const eps = {};
|
|
80
|
+
for (const proto of PROTOCOLS) {
|
|
81
|
+
const url = cleanUrl(endpoints[proto], `${proto} endpoint`);
|
|
82
|
+
if (url) eps[proto] = url;
|
|
83
|
+
}
|
|
84
|
+
if (!Object.keys(eps).length) throw new Error('give at least one endpoint (anthropic or openai)');
|
|
85
|
+
const list = [...new Set((Array.isArray(models) ? models : String(models).split(/[,\s]+/)).map((m) => String(m).trim()).filter(Boolean))];
|
|
86
|
+
if (!list.length) throw new Error('give at least one model id');
|
|
87
|
+
const known = providerClis().map((c) => c.type);
|
|
88
|
+
const allowed = types === undefined ? (old ? withTypes(old).types : defaultTypes()) : [...new Set(Array.isArray(types) ? types.map(String) : [])];
|
|
89
|
+
const bad = allowed.find((t) => !known.includes(t));
|
|
90
|
+
if (bad) throw new Error(`"${bad}" cannot take a provider; choose from: ${known.join(', ')}`);
|
|
91
|
+
// The context length of a model, where a person or the endpoint gave one: a CLI otherwise assumes a small default (pi: 128K).
|
|
92
|
+
const given = contexts === undefined ? (old?.contexts ?? {}) : contexts && typeof contexts === 'object' ? contexts : {};
|
|
93
|
+
const ctx = Object.fromEntries(list.filter((m) => Number(given[m]) >= 1000 && Number(given[m]) <= 1e8).map((m) => [m, Math.round(Number(given[m]))]));
|
|
94
|
+
const record = { id, name: String(name || id).slice(0, 80), apiKey: key, endpoints: eps, models: list, contexts: ctx, types: allowed, updatedAt: new Date().toISOString() };
|
|
95
|
+
data.providers[id] = record;
|
|
96
|
+
persist(data);
|
|
97
|
+
return view(record);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function removeProvider(id) {
|
|
101
|
+
const data = load();
|
|
102
|
+
if (!data.providers[id]) throw new Error(`unknown provider "${id}"`);
|
|
103
|
+
delete data.providers[id];
|
|
104
|
+
persist(data);
|
|
105
|
+
const install = currentInstall();
|
|
106
|
+
for (const d of Object.values(drivers)) {
|
|
107
|
+
if (d.provider?.scope === 'global') {
|
|
108
|
+
try {
|
|
109
|
+
removeGlobalProvider({ driver: d, install, piAdapterPath: PI_ADAPTER_PATH, providerId: id });
|
|
110
|
+
} catch {
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { id, removed: true };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function discoverProviderModels({ id, endpoints, apiKey }) {
|
|
118
|
+
const old = id ? load().providers[id] : null;
|
|
119
|
+
const key = String(apiKey ?? '').trim() || old?.apiKey;
|
|
120
|
+
if (!key) throw new Error('an API key is needed to list the models');
|
|
121
|
+
const eps = {};
|
|
122
|
+
for (const proto of PROTOCOLS) {
|
|
123
|
+
const url = cleanUrl(endpoints?.[proto] ?? old?.endpoints?.[proto], `${proto} endpoint`);
|
|
124
|
+
if (url) eps[proto] = url;
|
|
125
|
+
}
|
|
126
|
+
if (!Object.keys(eps).length) throw new Error('give an endpoint first');
|
|
127
|
+
return discoverModels({ endpoints: eps, apiKey: key });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function providerSupport(p) {
|
|
131
|
+
return Object.values(drivers).map((d) => {
|
|
132
|
+
const cap = d.provider;
|
|
133
|
+
if (!cap) return { type: d.type, label: d.label, supported: false, reason: 'no way to take another provider' };
|
|
134
|
+
const proto = providerProtocolOf(d, p.endpoints);
|
|
135
|
+
const has = Boolean(proto && p.endpoints?.[proto]);
|
|
136
|
+
const needed = Array.isArray(cap.protocols) && cap.protocols.length > 1 ? cap.protocols.join(' / ') : cap.protocol;
|
|
137
|
+
return {
|
|
138
|
+
type: d.type,
|
|
139
|
+
label: d.label,
|
|
140
|
+
supported: has,
|
|
141
|
+
enabled: (p.types ?? []).includes(d.type),
|
|
142
|
+
protocol: proto || cap.protocol,
|
|
143
|
+
scope: cap.scope,
|
|
144
|
+
reason: has ? null : `needs an ${needed} endpoint`,
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function cleanInstanceProvider(value, type) {
|
|
150
|
+
if (value == null || value === '' || value.id === '' || value.id == null) return null;
|
|
151
|
+
const driver = getDriver(type);
|
|
152
|
+
if (!driver?.provider) throw new Error(`${type} cannot use another provider`);
|
|
153
|
+
const p = getProvider(String(value.id));
|
|
154
|
+
if (!p.types.includes(type)) throw new Error(`provider "${p.id}" is not enabled for ${type}: tick it in the provider's settings first`);
|
|
155
|
+
const proto = providerProtocolOf(driver, p.endpoints);
|
|
156
|
+
if (!proto || !p.endpoints[proto]) {
|
|
157
|
+
const needed = Array.isArray(driver.provider.protocols) && driver.provider.protocols.length > 1 ? driver.provider.protocols.join(' or ') : driver.provider.protocol;
|
|
158
|
+
throw new Error(`provider "${p.id}" has no ${needed} endpoint, which ${type} needs`);
|
|
159
|
+
}
|
|
160
|
+
const model = String(value.model || p.models[0]);
|
|
161
|
+
return { id: p.id, model: model.slice(0, 200) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function providerForSpawn({ driver, name, choice, env }) {
|
|
165
|
+
const p = getProvider(choice.id);
|
|
166
|
+
if (!env?.PI_CLI && driver.type === 'pi') env = { ...env, PI_CLI: piPaths().cli };
|
|
167
|
+
const dir = projectPath(name, 'provider-config', String(instanceIdOf(name)).replace(/[^a-zA-Z0-9._~-]/g, '_'));
|
|
168
|
+
const r = applyProvider({ driver, provider: p, model: choice.model, dir, env });
|
|
169
|
+
if (!r.ok) throw new Error(`provider "${p.id}" cannot be used by ${driver.type}: ${r.skipped}`);
|
|
170
|
+
if (r.applied?.global) {
|
|
171
|
+
syncGlobalProvider({ driver, install: currentInstall(), piAdapterPath: PI_ADAPTER_PATH, applied: r.applied, dir, env: { ...process.env, ...env, ...r.env } });
|
|
172
|
+
}
|
|
173
|
+
return { env: r.env, args: r.args, model: r.model };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function testProviderAll(id, { model, types } = {}) {
|
|
177
|
+
const p = getProvider(id);
|
|
178
|
+
const secrets = [p.apiKey];
|
|
179
|
+
const testModel = model || p.models[0];
|
|
180
|
+
const endpoints = {};
|
|
181
|
+
await Promise.all(
|
|
182
|
+
Object.entries(p.endpoints).map(async ([protocol, endpoint]) => {
|
|
183
|
+
endpoints[protocol] = await checkEndpoint({ protocol, endpoint, apiKey: p.apiKey, model: testModel });
|
|
184
|
+
}),
|
|
185
|
+
);
|
|
186
|
+
const install = currentInstall();
|
|
187
|
+
const wanted = Object.values(drivers).filter((d) => p.types.includes(d.type) && (!types || types.includes(d.type)));
|
|
188
|
+
const results = await Promise.all(
|
|
189
|
+
wanted.map(async (d) => {
|
|
190
|
+
const proto = providerProtocolOf(d, p.endpoints);
|
|
191
|
+
const ep = proto ? endpoints[proto] : null;
|
|
192
|
+
if (!d.provider) return { type: d.type, ok: false, skipped: 'no way to take another provider', detail: 'no way to take another provider', ms: 0 };
|
|
193
|
+
if (!ep) return { type: d.type, ok: false, skipped: `needs an ${proto} endpoint`, detail: `needs an ${proto} endpoint, and this provider has none`, ms: 0 };
|
|
194
|
+
if (!ep.ok && ep.status === null) {
|
|
195
|
+
return { type: d.type, ok: false, skipped: 'endpoint unreachable', detail: `the ${proto} endpoint could not be reached: ${ep.detail}`, ms: 0 };
|
|
196
|
+
}
|
|
197
|
+
const workRoot = mkdtempSync(join(tmpdir(), `provider-test-${d.type}-`));
|
|
198
|
+
try {
|
|
199
|
+
return await testProvider({ driver: d, install, piAdapterPath: PI_ADAPTER_PATH, provider: p, model: testModel, workRoot, timeoutMs: 120_000 });
|
|
200
|
+
} finally {
|
|
201
|
+
rmSync(workRoot, { recursive: true, force: true });
|
|
202
|
+
}
|
|
203
|
+
}),
|
|
204
|
+
);
|
|
205
|
+
return { id, model: testModel, at: new Date().toISOString(), endpoints, results: results.map((r) => ({ ...r, detail: scrub(r.detail, secrets) })) };
|
|
206
|
+
}
|
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import { existsSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { GLOBAL_DIR, projectDir, projectIdsOnDisk } from '../base/index.mjs';
|
|
4
|
-
import { forgetProject as forgetJournal } from './journal.mjs';
|
|
5
|
-
import { forgetReceipts } from './receipts.mjs';
|
|
6
|
-
import { forgetProject as forgetTasks } from './tasks.mjs';
|
|
7
|
-
import { forgetTranscripts } from './transcripts.mjs';
|
|
8
|
-
|
|
9
|
-
export const RUN_LOG_KEEP_MS = 14 * 24 * 3600 * 1000;
|
|
10
|
-
|
|
11
|
-
export function pruneRunLogs(runsDir, keepMs = RUN_LOG_KEEP_MS, now = Date.now()) {
|
|
12
|
-
let removed = 0;
|
|
13
|
-
let names = [];
|
|
14
|
-
try {
|
|
15
|
-
names = readdirSync(runsDir);
|
|
16
|
-
} catch {
|
|
17
|
-
return 0;
|
|
18
|
-
}
|
|
19
|
-
for (const name of names) {
|
|
20
|
-
if (!name.endsWith('.log')) continue;
|
|
21
|
-
const file = join(runsDir, name);
|
|
22
|
-
try {
|
|
23
|
-
if (now - statSync(file).mtimeMs > keepMs) {
|
|
24
|
-
unlinkSync(file);
|
|
25
|
-
removed++;
|
|
26
|
-
}
|
|
27
|
-
} catch {
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return removed;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export function pruneAllRunLogs(keepMs = RUN_LOG_KEEP_MS, now = Date.now()) {
|
|
34
|
-
return projectIdsOnDisk().reduce((sum, id) => sum + pruneRunLogs(join(projectDir(id), 'runs'), keepMs, now), 0);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function forgetProject(project) {
|
|
38
|
-
forgetJournal(project);
|
|
39
|
-
forgetTasks(project);
|
|
40
|
-
forgetReceipts(project);
|
|
41
|
-
forgetTranscripts(project);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function readDaemonLog(lines = 80) {
|
|
45
|
-
const file = join(GLOBAL_DIR, 'agentd.log');
|
|
46
|
-
if (!existsSync(file)) return { file, lines: [] };
|
|
47
|
-
const raw = readFileSync(file, 'utf8').trimEnd();
|
|
48
|
-
if (!raw) return { file, lines: [] };
|
|
49
|
-
const count = Math.max(1, Math.min(Number(lines) || 80, 1000));
|
|
50
|
-
return { file, lines: raw.split(/\r?\n/).slice(-count) };
|
|
51
|
-
}
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { GLOBAL_DIR, projectDir, projectIdsOnDisk } from '../base/index.mjs';
|
|
4
|
+
import { forgetProject as forgetJournal } from './journal.mjs';
|
|
5
|
+
import { forgetReceipts } from './receipts.mjs';
|
|
6
|
+
import { forgetProject as forgetTasks } from './tasks.mjs';
|
|
7
|
+
import { forgetTranscripts } from './transcripts.mjs';
|
|
8
|
+
|
|
9
|
+
export const RUN_LOG_KEEP_MS = 14 * 24 * 3600 * 1000;
|
|
10
|
+
|
|
11
|
+
export function pruneRunLogs(runsDir, keepMs = RUN_LOG_KEEP_MS, now = Date.now()) {
|
|
12
|
+
let removed = 0;
|
|
13
|
+
let names = [];
|
|
14
|
+
try {
|
|
15
|
+
names = readdirSync(runsDir);
|
|
16
|
+
} catch {
|
|
17
|
+
return 0;
|
|
18
|
+
}
|
|
19
|
+
for (const name of names) {
|
|
20
|
+
if (!name.endsWith('.log')) continue;
|
|
21
|
+
const file = join(runsDir, name);
|
|
22
|
+
try {
|
|
23
|
+
if (now - statSync(file).mtimeMs > keepMs) {
|
|
24
|
+
unlinkSync(file);
|
|
25
|
+
removed++;
|
|
26
|
+
}
|
|
27
|
+
} catch {
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return removed;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function pruneAllRunLogs(keepMs = RUN_LOG_KEEP_MS, now = Date.now()) {
|
|
34
|
+
return projectIdsOnDisk().reduce((sum, id) => sum + pruneRunLogs(join(projectDir(id), 'runs'), keepMs, now), 0);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function forgetProject(project) {
|
|
38
|
+
forgetJournal(project);
|
|
39
|
+
forgetTasks(project);
|
|
40
|
+
forgetReceipts(project);
|
|
41
|
+
forgetTranscripts(project);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function readDaemonLog(lines = 80) {
|
|
45
|
+
const file = join(GLOBAL_DIR, 'agentd.log');
|
|
46
|
+
if (!existsSync(file)) return { file, lines: [] };
|
|
47
|
+
const raw = readFileSync(file, 'utf8').trimEnd();
|
|
48
|
+
if (!raw) return { file, lines: [] };
|
|
49
|
+
const count = Math.max(1, Math.min(Number(lines) || 80, 1000));
|
|
50
|
+
return { file, lines: raw.split(/\r?\n/).slice(-count) };
|
|
51
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { RUN_LOG_KEEP_MS, forgetProject, pruneAllRunLogs, pruneRunLogs, readDaemonLog } from './cleanup.mjs';
|
|
2
|
-
export { clearInterrupted, initJournal, interruptedOf, journalEnd, journalStart, reconcileJournal } from './journal.mjs';
|
|
3
|
-
export { computeMetrics } from './metrics.mjs';
|
|
4
|
-
export { appendAudit, appendReceipt, readAudits, readReceipts } from './receipts.mjs';
|
|
5
|
-
export { initRecords, recordInterruptedJobs, withInterrupted } from './recovery.mjs';
|
|
6
|
-
export { REPLY_LIMIT, fitReply } from './reply.mjs';
|
|
7
|
-
export { endRun, initTasks, planRun, recordRun } from './tasks.mjs';
|
|
8
|
-
export { appendEntry, findJobSession, readTranscript } from './transcripts.mjs';
|
|
1
|
+
export { RUN_LOG_KEEP_MS, forgetProject, pruneAllRunLogs, pruneRunLogs, readDaemonLog } from './cleanup.mjs';
|
|
2
|
+
export { clearInterrupted, initJournal, interruptedOf, journalEnd, journalStart, reconcileJournal } from './journal.mjs';
|
|
3
|
+
export { computeMetrics } from './metrics.mjs';
|
|
4
|
+
export { appendAudit, appendReceipt, readAudits, readReceipts } from './receipts.mjs';
|
|
5
|
+
export { initRecords, recordInterruptedJobs, withInterrupted } from './recovery.mjs';
|
|
6
|
+
export { REPLY_LIMIT, fitReply } from './reply.mjs';
|
|
7
|
+
export { endRun, initTasks, planRun, recordRun } from './tasks.mjs';
|
|
8
|
+
export { appendEntry, findJobSession, readTranscript } from './transcripts.mjs';
|