@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,465 +1,465 @@
|
|
|
1
|
-
import { CONFIG, acpMcpServers, defaultModelFor, effortOf, flattenOptions, isEffortOption, log, normPath } from '../../env/index.mjs';
|
|
2
|
-
import { entry, noteSession, saveStore, saved, savedAll } from '../support/index.mjs';
|
|
3
|
-
|
|
4
|
-
const DEFAULT_MODEL_RETRY_DELAYS_MS = [500, 1500, 3000];
|
|
5
|
-
|
|
6
|
-
function resolveModelRetryDelays(override) {
|
|
7
|
-
if (Array.isArray(override)) return override.map((n) => Math.max(0, Number(n) || 0));
|
|
8
|
-
const raw = process.env.AGENTD_MODEL_RETRY_DELAYS_MS;
|
|
9
|
-
if (raw !== undefined) {
|
|
10
|
-
if (!raw.trim()) return [];
|
|
11
|
-
return raw
|
|
12
|
-
.split(',')
|
|
13
|
-
.map((s) => Number(s.trim()))
|
|
14
|
-
.filter((n) => Number.isFinite(n) && n >= 0);
|
|
15
|
-
}
|
|
16
|
-
return DEFAULT_MODEL_RETRY_DELAYS_MS;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export class Sessions {
|
|
20
|
-
constructor({ agent, request, init, enqueue, rulesMeta, modelRetryDelaysMs }) {
|
|
21
|
-
this.agent = agent;
|
|
22
|
-
this.request = request;
|
|
23
|
-
this.init = init;
|
|
24
|
-
this.enqueue = enqueue;
|
|
25
|
-
this.rulesMeta = rulesMeta;
|
|
26
|
-
this.modelRetryDelaysMs = resolveModelRetryDelays(modelRetryDelaysMs);
|
|
27
|
-
this.mcpServers = () => acpMcpServers(agent.spec);
|
|
28
|
-
const spec = agent.spec;
|
|
29
|
-
this.sessionId = null;
|
|
30
|
-
this.cwd = spec.defaultCwd;
|
|
31
|
-
this.preferSession = spec.sessionId ?? null;
|
|
32
|
-
this.preferModel = spec.model ?? CONFIG?.defaultModels?.[spec.type ?? agent.name] ?? null;
|
|
33
|
-
this.preferEffort = spec.effort ?? null;
|
|
34
|
-
this.modelDirty = false;
|
|
35
|
-
this.models = null;
|
|
36
|
-
this.live = new Set();
|
|
37
|
-
this.sessionConfig = new Map();
|
|
38
|
-
this.configOptions = [];
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
forgetProcess() {
|
|
42
|
-
this.sessionId = null;
|
|
43
|
-
this.live.clear();
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
captureConfig(result) {
|
|
47
|
-
const opts = result?.configOptions;
|
|
48
|
-
if (Array.isArray(opts)) {
|
|
49
|
-
this.configOptions = opts;
|
|
50
|
-
if (this.sessionId) this.sessionConfig.set(this.sessionId, opts);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
currentModel() {
|
|
55
|
-
return this.configOptions?.find((o) => o.id === 'model')?.currentValue ?? null;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
_modelSwitchError(want, detail) {
|
|
59
|
-
const actual = this.currentModel() ?? '(unknown)';
|
|
60
|
-
const err = new Error(
|
|
61
|
-
`[${this.agent.name}] failed to switch model to "${want}" (active model is "${actual}")${detail ? `: ${detail}` : ''}`,
|
|
62
|
-
);
|
|
63
|
-
err.code = 'MODEL_SWITCH_FAILED';
|
|
64
|
-
err.expectedModel = want;
|
|
65
|
-
err.actualModel = this.currentModel();
|
|
66
|
-
return err;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async _refreshSession() {
|
|
70
|
-
if (!this.sessionId) return;
|
|
71
|
-
try {
|
|
72
|
-
const res = await this.request('session/resume', {
|
|
73
|
-
sessionId: this.sessionId,
|
|
74
|
-
cwd: this.cwd,
|
|
75
|
-
mcpServers: this.mcpServers(),
|
|
76
|
-
...this.rulesMeta(),
|
|
77
|
-
});
|
|
78
|
-
this.models = res?.models ?? this.models;
|
|
79
|
-
this.captureConfig(res);
|
|
80
|
-
} catch (err) {
|
|
81
|
-
log(`[${this.agent.name}] could not refresh session ${this.sessionId} before model retry: ${err.message}`);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async _setModelWithRetry(want, { reason = 'apply', force = false, refreshOnRetry = true } = {}) {
|
|
86
|
-
if (!want || !this.sessionId) return false;
|
|
87
|
-
const opt = this.configOptions?.find((o) => o.id === 'model');
|
|
88
|
-
if (!force) {
|
|
89
|
-
if (!opt) return false;
|
|
90
|
-
if (opt.currentValue === want) return false;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const delays = this.modelRetryDelaysMs;
|
|
94
|
-
const totalAttempts = 1 + delays.length;
|
|
95
|
-
let lastErr = null;
|
|
96
|
-
|
|
97
|
-
for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
|
|
98
|
-
if (attempt > 0) {
|
|
99
|
-
const waitMs = delays[attempt - 1];
|
|
100
|
-
log(
|
|
101
|
-
`[${this.agent.name}] retrying ${reason} model=${want} (${attempt + 1}/${totalAttempts}) after ${waitMs}ms: ` +
|
|
102
|
-
`${lastErr?.message ?? `active model is "${this.currentModel() ?? '(unknown)'}"`}`,
|
|
103
|
-
);
|
|
104
|
-
if (waitMs > 0) await new Promise((r) => setTimeout(r, waitMs));
|
|
105
|
-
if (refreshOnRetry) {
|
|
106
|
-
await this._refreshSession();
|
|
107
|
-
const refreshedOpt = this.configOptions?.find((o) => o.id === 'model');
|
|
108
|
-
if (!force && refreshedOpt && refreshedOpt.currentValue === want) return true;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
try {
|
|
112
|
-
const r = await this.request('session/set_config_option', {
|
|
113
|
-
sessionId: this.sessionId,
|
|
114
|
-
configId: 'model',
|
|
115
|
-
value: want,
|
|
116
|
-
});
|
|
117
|
-
this.captureConfig(r);
|
|
118
|
-
const afterOpt = this.configOptions?.find((o) => o.id === 'model');
|
|
119
|
-
if (!afterOpt || afterOpt.currentValue === want) return true;
|
|
120
|
-
lastErr = new Error(`CLI kept active model "${afterOpt.currentValue ?? '(unknown)'}" instead of "${want}"`);
|
|
121
|
-
} catch (err) {
|
|
122
|
-
lastErr = err;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const fatal = this._modelSwitchError(want, lastErr?.message);
|
|
127
|
-
log(fatal.message);
|
|
128
|
-
throw fatal;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async reapplyStoredConfig({ skipModel = false } = {}) {
|
|
132
|
-
const stored = saved(this.agent.name, this.sessionId)?.config;
|
|
133
|
-
if (!stored) return [];
|
|
134
|
-
const applied = [];
|
|
135
|
-
for (const [configId, value] of Object.entries(stored)) {
|
|
136
|
-
if (configId === 'model') {
|
|
137
|
-
if (skipModel) continue;
|
|
138
|
-
const changed = await this._setModelWithRetry(value, { reason: 're-apply' });
|
|
139
|
-
if (changed) {
|
|
140
|
-
applied.push({ configId, value });
|
|
141
|
-
log(`[${this.agent.name}] re-applied model=${value}`);
|
|
142
|
-
}
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
const opt = this.configOptions?.find((o) => o.id === configId);
|
|
146
|
-
if (!opt || opt.currentValue === value) continue;
|
|
147
|
-
try {
|
|
148
|
-
const r = await this.request('session/set_config_option', {
|
|
149
|
-
sessionId: this.sessionId,
|
|
150
|
-
configId,
|
|
151
|
-
value,
|
|
152
|
-
});
|
|
153
|
-
this.captureConfig(r);
|
|
154
|
-
applied.push({ configId, value });
|
|
155
|
-
log(`[${this.agent.name}] re-applied ${configId}=${value}`);
|
|
156
|
-
} catch (err) {
|
|
157
|
-
log(`[${this.agent.name}] could not re-apply ${configId}: ${err.message}`);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return applied;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
noteActive() {
|
|
164
|
-
if (!this.sessionId || this.preferSession === this.sessionId) return;
|
|
165
|
-
this.preferSession = this.sessionId;
|
|
166
|
-
try {
|
|
167
|
-
this.agent.onSession?.(this.sessionId);
|
|
168
|
-
} catch (err) {
|
|
169
|
-
log(`[${this.agent.name}] onSession failed: ${err.message}`);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
async applyPreferredModel() {
|
|
174
|
-
if (!this.sessionId) return;
|
|
175
|
-
const storedModel = saved(this.agent.name, this.sessionId)?.config?.model ?? null;
|
|
176
|
-
const want = storedModel || this.preferModel;
|
|
177
|
-
const opt = this.configOptions?.find((o) => o.id === 'model');
|
|
178
|
-
if (!want || !opt || opt.currentValue === want) return;
|
|
179
|
-
const changed = await this._setModelWithRetry(want, { reason: storedModel ? 're-apply' : 'apply' });
|
|
180
|
-
if (!changed) return;
|
|
181
|
-
if (!storedModel) {
|
|
182
|
-
const meta = entry(this.agent.name, this.sessionId);
|
|
183
|
-
meta.config = { ...(meta.config ?? {}), model: want };
|
|
184
|
-
if (!meta.cwd) meta.cwd = this.cwd;
|
|
185
|
-
saveStore(this.agent.name);
|
|
186
|
-
}
|
|
187
|
-
log(`[${this.agent.name}] applied ${storedModel ? 'session' : 'instance'} model ${want}`);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
async applyPreferredEffort() {
|
|
191
|
-
const want = this.preferEffort;
|
|
192
|
-
const opt = this.configOptions?.find(isEffortOption);
|
|
193
|
-
if (!want || !opt || opt.currentValue === want || !this.sessionId) return;
|
|
194
|
-
if (!effortOf(this.configOptions)?.options.some((o) => o.value === want)) return;
|
|
195
|
-
if (saved(this.agent.name, this.sessionId)?.config?.[opt.id]) return;
|
|
196
|
-
try {
|
|
197
|
-
const r = await this.request('session/set_config_option', { sessionId: this.sessionId, configId: opt.id, value: want });
|
|
198
|
-
this.captureConfig(r);
|
|
199
|
-
const meta = entry(this.agent.name, this.sessionId);
|
|
200
|
-
meta.config = { ...(meta.config ?? {}), [opt.id]: want };
|
|
201
|
-
if (!meta.cwd) meta.cwd = this.cwd;
|
|
202
|
-
saveStore(this.agent.name);
|
|
203
|
-
log(`[${this.agent.name}] applied reasoning level ${want}`);
|
|
204
|
-
} catch (err) {
|
|
205
|
-
log(`[${this.agent.name}] could not apply reasoning level ${want}: ${err.message}`);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
async chooseEffort(value) {
|
|
210
|
-
this.preferEffort = value || null;
|
|
211
|
-
const opt = this.configOptions?.find(isEffortOption);
|
|
212
|
-
const sid = this.sessionId ?? this.preferSession;
|
|
213
|
-
const cfg = sid && opt ? saved(this.agent.name, sid)?.config : null;
|
|
214
|
-
if (cfg?.[opt.id]) {
|
|
215
|
-
delete cfg[opt.id];
|
|
216
|
-
saveStore(this.agent.name);
|
|
217
|
-
}
|
|
218
|
-
if (!this.agent.child || !this.sessionId || this.agent.busy) return;
|
|
219
|
-
if (this.preferEffort) await this.applyPreferredEffort();
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
async chooseModel(value) {
|
|
223
|
-
this.preferModel = value ?? defaultModelFor(this.agent.type);
|
|
224
|
-
const sid = this.sessionId ?? this.preferSession;
|
|
225
|
-
const cfg = sid ? saved(this.agent.name, sid)?.config : null;
|
|
226
|
-
if (cfg?.model) {
|
|
227
|
-
delete cfg.model;
|
|
228
|
-
saveStore(this.agent.name);
|
|
229
|
-
}
|
|
230
|
-
if (!this.agent.child || !this.sessionId) return;
|
|
231
|
-
if (this.agent.busy) this.modelDirty = true;
|
|
232
|
-
else await this.applyPreferredModel();
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async ensureReady(cwd, { skipModel = false } = {}) {
|
|
236
|
-
await this.init();
|
|
237
|
-
const wantCwd = cwd || this.agent.spec.defaultCwd || this.cwd;
|
|
238
|
-
if (this.sessionId && wantCwd === this.cwd) {
|
|
239
|
-
if (!skipModel) await this.applyPreferredModel();
|
|
240
|
-
return this.sessionId;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
if (!this.sessionId && this.preferSession) {
|
|
244
|
-
try {
|
|
245
|
-
await this.attach(this.preferSession, wantCwd, { skipModel });
|
|
246
|
-
return this.sessionId;
|
|
247
|
-
} catch (err) {
|
|
248
|
-
if (err?.code === 'MODEL_SWITCH_FAILED') throw err;
|
|
249
|
-
log(`[${this.agent.name}] could not resume ${this.preferSession}: ${err.message}; starting a new session`);
|
|
250
|
-
this.preferSession = null;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
const t0 = Date.now();
|
|
255
|
-
const servers = this.mcpServers();
|
|
256
|
-
const sess = await this.request('session/new', { cwd: wantCwd, mcpServers: servers, ...this.rulesMeta() });
|
|
257
|
-
if (servers.length && this.agent.child) await new Promise((r) => setTimeout(r, 300));
|
|
258
|
-
this.sessionId = sess?.sessionId;
|
|
259
|
-
this.cwd = wantCwd;
|
|
260
|
-
if (this.sessionId) this.live.add(this.sessionId);
|
|
261
|
-
this.captureConfig(sess);
|
|
262
|
-
noteSession(this.agent.name, this.sessionId, { cwd: wantCwd, updatedAt: new Date().toISOString() });
|
|
263
|
-
log(`[${this.agent.name}] new session ${this.sessionId} in ${Date.now() - t0}ms`);
|
|
264
|
-
if (!skipModel) await this.applyPreferredModel();
|
|
265
|
-
await this.applyPreferredEffort();
|
|
266
|
-
this.noteActive();
|
|
267
|
-
return this.sessionId;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
async attach(sessionId, cwd, { skipModel = false } = {}) {
|
|
271
|
-
const res = await this.attachRaw(sessionId, cwd, { skipModel });
|
|
272
|
-
if (!skipModel) await this.applyPreferredModel();
|
|
273
|
-
await this.applyPreferredEffort();
|
|
274
|
-
this.noteActive();
|
|
275
|
-
return res;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
async attachRaw(sessionId, cwd, { skipModel = false } = {}) {
|
|
279
|
-
const wantCwd = cwd || saved(this.agent.name, sessionId)?.cwd || this.cwd;
|
|
280
|
-
|
|
281
|
-
if (this.live.has(sessionId)) {
|
|
282
|
-
this.sessionId = sessionId;
|
|
283
|
-
this.cwd = wantCwd;
|
|
284
|
-
if (this.sessionConfig.has(sessionId)) this.configOptions = this.sessionConfig.get(sessionId);
|
|
285
|
-
const reApplied = await this.reapplyStoredConfig({ skipModel });
|
|
286
|
-
return { sessionId, cwd: wantCwd, resumed: false, live: true, reApplied };
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
let resumed = true;
|
|
290
|
-
try {
|
|
291
|
-
const res = await this.request('session/resume', { sessionId, cwd: wantCwd, mcpServers: this.mcpServers(), ...this.rulesMeta() });
|
|
292
|
-
this.sessionId = res?.sessionId ?? sessionId;
|
|
293
|
-
this.cwd = wantCwd;
|
|
294
|
-
this.models = res?.models ?? this.models;
|
|
295
|
-
this.live.add(this.sessionId);
|
|
296
|
-
this.captureConfig(res);
|
|
297
|
-
noteSession(this.agent.name, this.sessionId, { cwd: wantCwd, updatedAt: new Date().toISOString() });
|
|
298
|
-
} catch (err) {
|
|
299
|
-
if (!/already active/i.test(err.message)) throw err;
|
|
300
|
-
resumed = false;
|
|
301
|
-
this.sessionId = sessionId;
|
|
302
|
-
this.cwd = wantCwd;
|
|
303
|
-
this.live.add(sessionId);
|
|
304
|
-
if (this.sessionConfig.has(sessionId)) this.configOptions = this.sessionConfig.get(sessionId);
|
|
305
|
-
}
|
|
306
|
-
const reApplied = await this.reapplyStoredConfig({ skipModel });
|
|
307
|
-
return { sessionId: this.sessionId, cwd: wantCwd, resumed, live: true, reApplied };
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
async setConfigOption(configId, value, sessionId) {
|
|
311
|
-
return this.enqueue(async () => {
|
|
312
|
-
await this.init();
|
|
313
|
-
const skipModel = configId === 'model';
|
|
314
|
-
if (sessionId && sessionId !== this.sessionId) await this.attach(sessionId, undefined, { skipModel });
|
|
315
|
-
else if (!this.sessionId) await this.ensureReady(undefined, { skipModel });
|
|
316
|
-
|
|
317
|
-
if (configId === 'model') {
|
|
318
|
-
await this._setModelWithRetry(value, { reason: 'set', force: true });
|
|
319
|
-
} else {
|
|
320
|
-
const r = await this.request('session/set_config_option', {
|
|
321
|
-
sessionId: this.sessionId,
|
|
322
|
-
configId,
|
|
323
|
-
value,
|
|
324
|
-
});
|
|
325
|
-
this.captureConfig(r);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
const meta = entry(this.agent.name, this.sessionId);
|
|
329
|
-
meta.config = { ...(meta.config ?? {}), [configId]: value };
|
|
330
|
-
if (!meta.cwd) meta.cwd = this.cwd;
|
|
331
|
-
saveStore(this.agent.name);
|
|
332
|
-
|
|
333
|
-
return { sessionId: this.sessionId, configOptions: this.configOptions };
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
async describeModels(sessionId) {
|
|
338
|
-
if (this.agent.busy && this.sessionId && this.configOptions && (!sessionId || sessionId === this.sessionId)) {
|
|
339
|
-
return { sessionId: this.sessionId, configOptions: this.configOptions.map((opt) => ({ ...opt, options: flattenOptions(opt.options) })) };
|
|
340
|
-
}
|
|
341
|
-
return this.enqueue(async () => {
|
|
342
|
-
await this.init();
|
|
343
|
-
if (sessionId && sessionId !== this.sessionId) await this.attach(sessionId);
|
|
344
|
-
else await this.ensureReady();
|
|
345
|
-
return {
|
|
346
|
-
sessionId: this.sessionId,
|
|
347
|
-
configOptions: this.configOptions.map((opt) => ({
|
|
348
|
-
...opt,
|
|
349
|
-
options: flattenOptions(opt.options),
|
|
350
|
-
})),
|
|
351
|
-
};
|
|
352
|
-
}, sessionId ? { session: { kind: 'other' } } : undefined);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
async useSession(sessionId, cwd) {
|
|
356
|
-
return this.enqueue(
|
|
357
|
-
async () => {
|
|
358
|
-
await this.init();
|
|
359
|
-
return this.attach(sessionId, cwd);
|
|
360
|
-
},
|
|
361
|
-
{ session: { kind: 'use', id: sessionId } },
|
|
362
|
-
);
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
async newSession(cwd) {
|
|
366
|
-
return this.enqueue(
|
|
367
|
-
async () => {
|
|
368
|
-
await this.init();
|
|
369
|
-
this.sessionId = null;
|
|
370
|
-
this.preferSession = null; // an explicit "new" must not fall back to the remembered session
|
|
371
|
-
return this.ensureReady(cwd);
|
|
372
|
-
},
|
|
373
|
-
{ session: { kind: 'other' } },
|
|
374
|
-
);
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
async list({ remote: askCli = false } = {}) {
|
|
378
|
-
let remote = [];
|
|
379
|
-
let remoteError = null;
|
|
380
|
-
if (askCli) {
|
|
381
|
-
await this.init();
|
|
382
|
-
try {
|
|
383
|
-
const res = await this.request('session/list', {}, { timeoutMs: this.agent.busy ? 5_000 : 60_000 });
|
|
384
|
-
remote = res?.sessions ?? (Array.isArray(res) ? res : []);
|
|
385
|
-
} catch (err) {
|
|
386
|
-
remoteError = err.message;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
const local = savedAll(this.agent.name);
|
|
391
|
-
const byId = new Map();
|
|
392
|
-
|
|
393
|
-
const hidden = (id) => Boolean(local[id]?.hidden);
|
|
394
|
-
for (const s of remote) {
|
|
395
|
-
if (hidden(s.sessionId)) continue;
|
|
396
|
-
if (s.cwd && normPath(s.cwd) !== normPath(this.agent.spec.defaultCwd)) continue;
|
|
397
|
-
byId.set(s.sessionId, {
|
|
398
|
-
sessionId: s.sessionId,
|
|
399
|
-
cwd: s.cwd ?? local[s.sessionId]?.cwd ?? null,
|
|
400
|
-
title: s.title ?? null,
|
|
401
|
-
updatedAt: s.updatedAt ?? local[s.sessionId]?.updatedAt ?? null,
|
|
402
|
-
label: local[s.sessionId]?.label ?? null,
|
|
403
|
-
source: 'agent',
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
for (const [id, meta] of Object.entries(local)) {
|
|
407
|
-
if (byId.has(id) || meta.hidden) continue;
|
|
408
|
-
byId.set(id, {
|
|
409
|
-
sessionId: id,
|
|
410
|
-
cwd: meta.cwd ?? null,
|
|
411
|
-
title: null,
|
|
412
|
-
updatedAt: meta.updatedAt ?? null,
|
|
413
|
-
label: meta.label ?? null,
|
|
414
|
-
source: 'local',
|
|
415
|
-
});
|
|
416
|
-
}
|
|
417
|
-
for (const id of this.live) {
|
|
418
|
-
if (byId.has(id) || hidden(id)) continue;
|
|
419
|
-
byId.set(id, {
|
|
420
|
-
sessionId: id,
|
|
421
|
-
cwd: local[id]?.cwd ?? this.cwd,
|
|
422
|
-
title: null,
|
|
423
|
-
updatedAt: local[id]?.updatedAt ?? null,
|
|
424
|
-
label: local[id]?.label ?? null,
|
|
425
|
-
source: 'live',
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
if (this.sessionId && !byId.has(this.sessionId)) {
|
|
429
|
-
byId.set(this.sessionId, {
|
|
430
|
-
sessionId: this.sessionId,
|
|
431
|
-
cwd: this.cwd,
|
|
432
|
-
title: null,
|
|
433
|
-
updatedAt: local[this.sessionId]?.updatedAt ?? null,
|
|
434
|
-
label: local[this.sessionId]?.label ?? null,
|
|
435
|
-
source: 'local',
|
|
436
|
-
});
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
const rows = [...byId.values()].map((r) => ({ ...r, active: r.sessionId === this.sessionId }));
|
|
440
|
-
rows.sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
|
|
441
|
-
return { sessions: rows, remoteError };
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
remove(sessionId) {
|
|
445
|
-
if (!sessionId) throw new Error('sessionId is required');
|
|
446
|
-
if (sessionId === this.sessionId) throw new Error('cannot delete the active session; switch to another first');
|
|
447
|
-
const e = entry(this.agent.name, sessionId);
|
|
448
|
-
e.hidden = true;
|
|
449
|
-
delete e.label;
|
|
450
|
-
this.live.delete(sessionId);
|
|
451
|
-
saveStore(this.agent.name);
|
|
452
|
-
return { sessionId, deleted: true };
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
rename(sessionId, label) {
|
|
456
|
-
const id = sessionId || this.sessionId;
|
|
457
|
-
if (!id) throw new Error('no active session to rename');
|
|
458
|
-
const e = entry(this.agent.name, id);
|
|
459
|
-
if (label === null || label === '') delete e.label;
|
|
460
|
-
else e.label = label;
|
|
461
|
-
if (!e.cwd) e.cwd = this.cwd;
|
|
462
|
-
saveStore(this.agent.name);
|
|
463
|
-
return { sessionId: id, label: e.label ?? null };
|
|
464
|
-
}
|
|
465
|
-
}
|
|
1
|
+
import { CONFIG, acpMcpServers, defaultModelFor, effortOf, flattenOptions, isEffortOption, log, normPath } from '../../env/index.mjs';
|
|
2
|
+
import { entry, noteSession, saveStore, saved, savedAll } from '../support/index.mjs';
|
|
3
|
+
|
|
4
|
+
const DEFAULT_MODEL_RETRY_DELAYS_MS = [500, 1500, 3000];
|
|
5
|
+
|
|
6
|
+
function resolveModelRetryDelays(override) {
|
|
7
|
+
if (Array.isArray(override)) return override.map((n) => Math.max(0, Number(n) || 0));
|
|
8
|
+
const raw = process.env.AGENTD_MODEL_RETRY_DELAYS_MS;
|
|
9
|
+
if (raw !== undefined) {
|
|
10
|
+
if (!raw.trim()) return [];
|
|
11
|
+
return raw
|
|
12
|
+
.split(',')
|
|
13
|
+
.map((s) => Number(s.trim()))
|
|
14
|
+
.filter((n) => Number.isFinite(n) && n >= 0);
|
|
15
|
+
}
|
|
16
|
+
return DEFAULT_MODEL_RETRY_DELAYS_MS;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class Sessions {
|
|
20
|
+
constructor({ agent, request, init, enqueue, rulesMeta, modelRetryDelaysMs }) {
|
|
21
|
+
this.agent = agent;
|
|
22
|
+
this.request = request;
|
|
23
|
+
this.init = init;
|
|
24
|
+
this.enqueue = enqueue;
|
|
25
|
+
this.rulesMeta = rulesMeta;
|
|
26
|
+
this.modelRetryDelaysMs = resolveModelRetryDelays(modelRetryDelaysMs);
|
|
27
|
+
this.mcpServers = () => acpMcpServers(agent.spec);
|
|
28
|
+
const spec = agent.spec;
|
|
29
|
+
this.sessionId = null;
|
|
30
|
+
this.cwd = spec.defaultCwd;
|
|
31
|
+
this.preferSession = spec.sessionId ?? null;
|
|
32
|
+
this.preferModel = spec.model ?? CONFIG?.defaultModels?.[spec.type ?? agent.name] ?? null;
|
|
33
|
+
this.preferEffort = spec.effort ?? null;
|
|
34
|
+
this.modelDirty = false;
|
|
35
|
+
this.models = null;
|
|
36
|
+
this.live = new Set();
|
|
37
|
+
this.sessionConfig = new Map();
|
|
38
|
+
this.configOptions = [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
forgetProcess() {
|
|
42
|
+
this.sessionId = null;
|
|
43
|
+
this.live.clear();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
captureConfig(result) {
|
|
47
|
+
const opts = result?.configOptions;
|
|
48
|
+
if (Array.isArray(opts)) {
|
|
49
|
+
this.configOptions = opts;
|
|
50
|
+
if (this.sessionId) this.sessionConfig.set(this.sessionId, opts);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
currentModel() {
|
|
55
|
+
return this.configOptions?.find((o) => o.id === 'model')?.currentValue ?? null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
_modelSwitchError(want, detail) {
|
|
59
|
+
const actual = this.currentModel() ?? '(unknown)';
|
|
60
|
+
const err = new Error(
|
|
61
|
+
`[${this.agent.name}] failed to switch model to "${want}" (active model is "${actual}")${detail ? `: ${detail}` : ''}`,
|
|
62
|
+
);
|
|
63
|
+
err.code = 'MODEL_SWITCH_FAILED';
|
|
64
|
+
err.expectedModel = want;
|
|
65
|
+
err.actualModel = this.currentModel();
|
|
66
|
+
return err;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async _refreshSession() {
|
|
70
|
+
if (!this.sessionId) return;
|
|
71
|
+
try {
|
|
72
|
+
const res = await this.request('session/resume', {
|
|
73
|
+
sessionId: this.sessionId,
|
|
74
|
+
cwd: this.cwd,
|
|
75
|
+
mcpServers: this.mcpServers(),
|
|
76
|
+
...this.rulesMeta(),
|
|
77
|
+
});
|
|
78
|
+
this.models = res?.models ?? this.models;
|
|
79
|
+
this.captureConfig(res);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
log(`[${this.agent.name}] could not refresh session ${this.sessionId} before model retry: ${err.message}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async _setModelWithRetry(want, { reason = 'apply', force = false, refreshOnRetry = true } = {}) {
|
|
86
|
+
if (!want || !this.sessionId) return false;
|
|
87
|
+
const opt = this.configOptions?.find((o) => o.id === 'model');
|
|
88
|
+
if (!force) {
|
|
89
|
+
if (!opt) return false;
|
|
90
|
+
if (opt.currentValue === want) return false;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const delays = this.modelRetryDelaysMs;
|
|
94
|
+
const totalAttempts = 1 + delays.length;
|
|
95
|
+
let lastErr = null;
|
|
96
|
+
|
|
97
|
+
for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
|
|
98
|
+
if (attempt > 0) {
|
|
99
|
+
const waitMs = delays[attempt - 1];
|
|
100
|
+
log(
|
|
101
|
+
`[${this.agent.name}] retrying ${reason} model=${want} (${attempt + 1}/${totalAttempts}) after ${waitMs}ms: ` +
|
|
102
|
+
`${lastErr?.message ?? `active model is "${this.currentModel() ?? '(unknown)'}"`}`,
|
|
103
|
+
);
|
|
104
|
+
if (waitMs > 0) await new Promise((r) => setTimeout(r, waitMs));
|
|
105
|
+
if (refreshOnRetry) {
|
|
106
|
+
await this._refreshSession();
|
|
107
|
+
const refreshedOpt = this.configOptions?.find((o) => o.id === 'model');
|
|
108
|
+
if (!force && refreshedOpt && refreshedOpt.currentValue === want) return true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const r = await this.request('session/set_config_option', {
|
|
113
|
+
sessionId: this.sessionId,
|
|
114
|
+
configId: 'model',
|
|
115
|
+
value: want,
|
|
116
|
+
});
|
|
117
|
+
this.captureConfig(r);
|
|
118
|
+
const afterOpt = this.configOptions?.find((o) => o.id === 'model');
|
|
119
|
+
if (!afterOpt || afterOpt.currentValue === want) return true;
|
|
120
|
+
lastErr = new Error(`CLI kept active model "${afterOpt.currentValue ?? '(unknown)'}" instead of "${want}"`);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
lastErr = err;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const fatal = this._modelSwitchError(want, lastErr?.message);
|
|
127
|
+
log(fatal.message);
|
|
128
|
+
throw fatal;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async reapplyStoredConfig({ skipModel = false } = {}) {
|
|
132
|
+
const stored = saved(this.agent.name, this.sessionId)?.config;
|
|
133
|
+
if (!stored) return [];
|
|
134
|
+
const applied = [];
|
|
135
|
+
for (const [configId, value] of Object.entries(stored)) {
|
|
136
|
+
if (configId === 'model') {
|
|
137
|
+
if (skipModel) continue;
|
|
138
|
+
const changed = await this._setModelWithRetry(value, { reason: 're-apply' });
|
|
139
|
+
if (changed) {
|
|
140
|
+
applied.push({ configId, value });
|
|
141
|
+
log(`[${this.agent.name}] re-applied model=${value}`);
|
|
142
|
+
}
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const opt = this.configOptions?.find((o) => o.id === configId);
|
|
146
|
+
if (!opt || opt.currentValue === value) continue;
|
|
147
|
+
try {
|
|
148
|
+
const r = await this.request('session/set_config_option', {
|
|
149
|
+
sessionId: this.sessionId,
|
|
150
|
+
configId,
|
|
151
|
+
value,
|
|
152
|
+
});
|
|
153
|
+
this.captureConfig(r);
|
|
154
|
+
applied.push({ configId, value });
|
|
155
|
+
log(`[${this.agent.name}] re-applied ${configId}=${value}`);
|
|
156
|
+
} catch (err) {
|
|
157
|
+
log(`[${this.agent.name}] could not re-apply ${configId}: ${err.message}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return applied;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
noteActive() {
|
|
164
|
+
if (!this.sessionId || this.preferSession === this.sessionId) return;
|
|
165
|
+
this.preferSession = this.sessionId;
|
|
166
|
+
try {
|
|
167
|
+
this.agent.onSession?.(this.sessionId);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
log(`[${this.agent.name}] onSession failed: ${err.message}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async applyPreferredModel() {
|
|
174
|
+
if (!this.sessionId) return;
|
|
175
|
+
const storedModel = saved(this.agent.name, this.sessionId)?.config?.model ?? null;
|
|
176
|
+
const want = storedModel || this.preferModel;
|
|
177
|
+
const opt = this.configOptions?.find((o) => o.id === 'model');
|
|
178
|
+
if (!want || !opt || opt.currentValue === want) return;
|
|
179
|
+
const changed = await this._setModelWithRetry(want, { reason: storedModel ? 're-apply' : 'apply' });
|
|
180
|
+
if (!changed) return;
|
|
181
|
+
if (!storedModel) {
|
|
182
|
+
const meta = entry(this.agent.name, this.sessionId);
|
|
183
|
+
meta.config = { ...(meta.config ?? {}), model: want };
|
|
184
|
+
if (!meta.cwd) meta.cwd = this.cwd;
|
|
185
|
+
saveStore(this.agent.name);
|
|
186
|
+
}
|
|
187
|
+
log(`[${this.agent.name}] applied ${storedModel ? 'session' : 'instance'} model ${want}`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async applyPreferredEffort() {
|
|
191
|
+
const want = this.preferEffort;
|
|
192
|
+
const opt = this.configOptions?.find(isEffortOption);
|
|
193
|
+
if (!want || !opt || opt.currentValue === want || !this.sessionId) return;
|
|
194
|
+
if (!effortOf(this.configOptions)?.options.some((o) => o.value === want)) return;
|
|
195
|
+
if (saved(this.agent.name, this.sessionId)?.config?.[opt.id]) return;
|
|
196
|
+
try {
|
|
197
|
+
const r = await this.request('session/set_config_option', { sessionId: this.sessionId, configId: opt.id, value: want });
|
|
198
|
+
this.captureConfig(r);
|
|
199
|
+
const meta = entry(this.agent.name, this.sessionId);
|
|
200
|
+
meta.config = { ...(meta.config ?? {}), [opt.id]: want };
|
|
201
|
+
if (!meta.cwd) meta.cwd = this.cwd;
|
|
202
|
+
saveStore(this.agent.name);
|
|
203
|
+
log(`[${this.agent.name}] applied reasoning level ${want}`);
|
|
204
|
+
} catch (err) {
|
|
205
|
+
log(`[${this.agent.name}] could not apply reasoning level ${want}: ${err.message}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async chooseEffort(value) {
|
|
210
|
+
this.preferEffort = value || null;
|
|
211
|
+
const opt = this.configOptions?.find(isEffortOption);
|
|
212
|
+
const sid = this.sessionId ?? this.preferSession;
|
|
213
|
+
const cfg = sid && opt ? saved(this.agent.name, sid)?.config : null;
|
|
214
|
+
if (cfg?.[opt.id]) {
|
|
215
|
+
delete cfg[opt.id];
|
|
216
|
+
saveStore(this.agent.name);
|
|
217
|
+
}
|
|
218
|
+
if (!this.agent.child || !this.sessionId || this.agent.busy) return;
|
|
219
|
+
if (this.preferEffort) await this.applyPreferredEffort();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async chooseModel(value) {
|
|
223
|
+
this.preferModel = value ?? defaultModelFor(this.agent.type);
|
|
224
|
+
const sid = this.sessionId ?? this.preferSession;
|
|
225
|
+
const cfg = sid ? saved(this.agent.name, sid)?.config : null;
|
|
226
|
+
if (cfg?.model) {
|
|
227
|
+
delete cfg.model;
|
|
228
|
+
saveStore(this.agent.name);
|
|
229
|
+
}
|
|
230
|
+
if (!this.agent.child || !this.sessionId) return;
|
|
231
|
+
if (this.agent.busy) this.modelDirty = true;
|
|
232
|
+
else await this.applyPreferredModel();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async ensureReady(cwd, { skipModel = false } = {}) {
|
|
236
|
+
await this.init();
|
|
237
|
+
const wantCwd = cwd || this.agent.spec.defaultCwd || this.cwd;
|
|
238
|
+
if (this.sessionId && wantCwd === this.cwd) {
|
|
239
|
+
if (!skipModel) await this.applyPreferredModel();
|
|
240
|
+
return this.sessionId;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!this.sessionId && this.preferSession) {
|
|
244
|
+
try {
|
|
245
|
+
await this.attach(this.preferSession, wantCwd, { skipModel });
|
|
246
|
+
return this.sessionId;
|
|
247
|
+
} catch (err) {
|
|
248
|
+
if (err?.code === 'MODEL_SWITCH_FAILED') throw err;
|
|
249
|
+
log(`[${this.agent.name}] could not resume ${this.preferSession}: ${err.message}; starting a new session`);
|
|
250
|
+
this.preferSession = null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const t0 = Date.now();
|
|
255
|
+
const servers = this.mcpServers();
|
|
256
|
+
const sess = await this.request('session/new', { cwd: wantCwd, mcpServers: servers, ...this.rulesMeta() });
|
|
257
|
+
if (servers.length && this.agent.child) await new Promise((r) => setTimeout(r, 300));
|
|
258
|
+
this.sessionId = sess?.sessionId;
|
|
259
|
+
this.cwd = wantCwd;
|
|
260
|
+
if (this.sessionId) this.live.add(this.sessionId);
|
|
261
|
+
this.captureConfig(sess);
|
|
262
|
+
noteSession(this.agent.name, this.sessionId, { cwd: wantCwd, updatedAt: new Date().toISOString() });
|
|
263
|
+
log(`[${this.agent.name}] new session ${this.sessionId} in ${Date.now() - t0}ms`);
|
|
264
|
+
if (!skipModel) await this.applyPreferredModel();
|
|
265
|
+
await this.applyPreferredEffort();
|
|
266
|
+
this.noteActive();
|
|
267
|
+
return this.sessionId;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async attach(sessionId, cwd, { skipModel = false } = {}) {
|
|
271
|
+
const res = await this.attachRaw(sessionId, cwd, { skipModel });
|
|
272
|
+
if (!skipModel) await this.applyPreferredModel();
|
|
273
|
+
await this.applyPreferredEffort();
|
|
274
|
+
this.noteActive();
|
|
275
|
+
return res;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async attachRaw(sessionId, cwd, { skipModel = false } = {}) {
|
|
279
|
+
const wantCwd = cwd || saved(this.agent.name, sessionId)?.cwd || this.cwd;
|
|
280
|
+
|
|
281
|
+
if (this.live.has(sessionId)) {
|
|
282
|
+
this.sessionId = sessionId;
|
|
283
|
+
this.cwd = wantCwd;
|
|
284
|
+
if (this.sessionConfig.has(sessionId)) this.configOptions = this.sessionConfig.get(sessionId);
|
|
285
|
+
const reApplied = await this.reapplyStoredConfig({ skipModel });
|
|
286
|
+
return { sessionId, cwd: wantCwd, resumed: false, live: true, reApplied };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let resumed = true;
|
|
290
|
+
try {
|
|
291
|
+
const res = await this.request('session/resume', { sessionId, cwd: wantCwd, mcpServers: this.mcpServers(), ...this.rulesMeta() });
|
|
292
|
+
this.sessionId = res?.sessionId ?? sessionId;
|
|
293
|
+
this.cwd = wantCwd;
|
|
294
|
+
this.models = res?.models ?? this.models;
|
|
295
|
+
this.live.add(this.sessionId);
|
|
296
|
+
this.captureConfig(res);
|
|
297
|
+
noteSession(this.agent.name, this.sessionId, { cwd: wantCwd, updatedAt: new Date().toISOString() });
|
|
298
|
+
} catch (err) {
|
|
299
|
+
if (!/already active/i.test(err.message)) throw err;
|
|
300
|
+
resumed = false;
|
|
301
|
+
this.sessionId = sessionId;
|
|
302
|
+
this.cwd = wantCwd;
|
|
303
|
+
this.live.add(sessionId);
|
|
304
|
+
if (this.sessionConfig.has(sessionId)) this.configOptions = this.sessionConfig.get(sessionId);
|
|
305
|
+
}
|
|
306
|
+
const reApplied = await this.reapplyStoredConfig({ skipModel });
|
|
307
|
+
return { sessionId: this.sessionId, cwd: wantCwd, resumed, live: true, reApplied };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async setConfigOption(configId, value, sessionId) {
|
|
311
|
+
return this.enqueue(async () => {
|
|
312
|
+
await this.init();
|
|
313
|
+
const skipModel = configId === 'model';
|
|
314
|
+
if (sessionId && sessionId !== this.sessionId) await this.attach(sessionId, undefined, { skipModel });
|
|
315
|
+
else if (!this.sessionId) await this.ensureReady(undefined, { skipModel });
|
|
316
|
+
|
|
317
|
+
if (configId === 'model') {
|
|
318
|
+
await this._setModelWithRetry(value, { reason: 'set', force: true });
|
|
319
|
+
} else {
|
|
320
|
+
const r = await this.request('session/set_config_option', {
|
|
321
|
+
sessionId: this.sessionId,
|
|
322
|
+
configId,
|
|
323
|
+
value,
|
|
324
|
+
});
|
|
325
|
+
this.captureConfig(r);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const meta = entry(this.agent.name, this.sessionId);
|
|
329
|
+
meta.config = { ...(meta.config ?? {}), [configId]: value };
|
|
330
|
+
if (!meta.cwd) meta.cwd = this.cwd;
|
|
331
|
+
saveStore(this.agent.name);
|
|
332
|
+
|
|
333
|
+
return { sessionId: this.sessionId, configOptions: this.configOptions };
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async describeModels(sessionId) {
|
|
338
|
+
if (this.agent.busy && this.sessionId && this.configOptions && (!sessionId || sessionId === this.sessionId)) {
|
|
339
|
+
return { sessionId: this.sessionId, configOptions: this.configOptions.map((opt) => ({ ...opt, options: flattenOptions(opt.options) })) };
|
|
340
|
+
}
|
|
341
|
+
return this.enqueue(async () => {
|
|
342
|
+
await this.init();
|
|
343
|
+
if (sessionId && sessionId !== this.sessionId) await this.attach(sessionId);
|
|
344
|
+
else await this.ensureReady();
|
|
345
|
+
return {
|
|
346
|
+
sessionId: this.sessionId,
|
|
347
|
+
configOptions: this.configOptions.map((opt) => ({
|
|
348
|
+
...opt,
|
|
349
|
+
options: flattenOptions(opt.options),
|
|
350
|
+
})),
|
|
351
|
+
};
|
|
352
|
+
}, sessionId ? { session: { kind: 'other' } } : undefined);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async useSession(sessionId, cwd) {
|
|
356
|
+
return this.enqueue(
|
|
357
|
+
async () => {
|
|
358
|
+
await this.init();
|
|
359
|
+
return this.attach(sessionId, cwd);
|
|
360
|
+
},
|
|
361
|
+
{ session: { kind: 'use', id: sessionId } },
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async newSession(cwd) {
|
|
366
|
+
return this.enqueue(
|
|
367
|
+
async () => {
|
|
368
|
+
await this.init();
|
|
369
|
+
this.sessionId = null;
|
|
370
|
+
this.preferSession = null; // an explicit "new" must not fall back to the remembered session
|
|
371
|
+
return this.ensureReady(cwd);
|
|
372
|
+
},
|
|
373
|
+
{ session: { kind: 'other' } },
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async list({ remote: askCli = false } = {}) {
|
|
378
|
+
let remote = [];
|
|
379
|
+
let remoteError = null;
|
|
380
|
+
if (askCli) {
|
|
381
|
+
await this.init();
|
|
382
|
+
try {
|
|
383
|
+
const res = await this.request('session/list', {}, { timeoutMs: this.agent.busy ? 5_000 : 60_000 });
|
|
384
|
+
remote = res?.sessions ?? (Array.isArray(res) ? res : []);
|
|
385
|
+
} catch (err) {
|
|
386
|
+
remoteError = err.message;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const local = savedAll(this.agent.name);
|
|
391
|
+
const byId = new Map();
|
|
392
|
+
|
|
393
|
+
const hidden = (id) => Boolean(local[id]?.hidden);
|
|
394
|
+
for (const s of remote) {
|
|
395
|
+
if (hidden(s.sessionId)) continue;
|
|
396
|
+
if (s.cwd && normPath(s.cwd) !== normPath(this.agent.spec.defaultCwd)) continue;
|
|
397
|
+
byId.set(s.sessionId, {
|
|
398
|
+
sessionId: s.sessionId,
|
|
399
|
+
cwd: s.cwd ?? local[s.sessionId]?.cwd ?? null,
|
|
400
|
+
title: s.title ?? null,
|
|
401
|
+
updatedAt: s.updatedAt ?? local[s.sessionId]?.updatedAt ?? null,
|
|
402
|
+
label: local[s.sessionId]?.label ?? null,
|
|
403
|
+
source: 'agent',
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
for (const [id, meta] of Object.entries(local)) {
|
|
407
|
+
if (byId.has(id) || meta.hidden) continue;
|
|
408
|
+
byId.set(id, {
|
|
409
|
+
sessionId: id,
|
|
410
|
+
cwd: meta.cwd ?? null,
|
|
411
|
+
title: null,
|
|
412
|
+
updatedAt: meta.updatedAt ?? null,
|
|
413
|
+
label: meta.label ?? null,
|
|
414
|
+
source: 'local',
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
for (const id of this.live) {
|
|
418
|
+
if (byId.has(id) || hidden(id)) continue;
|
|
419
|
+
byId.set(id, {
|
|
420
|
+
sessionId: id,
|
|
421
|
+
cwd: local[id]?.cwd ?? this.cwd,
|
|
422
|
+
title: null,
|
|
423
|
+
updatedAt: local[id]?.updatedAt ?? null,
|
|
424
|
+
label: local[id]?.label ?? null,
|
|
425
|
+
source: 'live',
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
if (this.sessionId && !byId.has(this.sessionId)) {
|
|
429
|
+
byId.set(this.sessionId, {
|
|
430
|
+
sessionId: this.sessionId,
|
|
431
|
+
cwd: this.cwd,
|
|
432
|
+
title: null,
|
|
433
|
+
updatedAt: local[this.sessionId]?.updatedAt ?? null,
|
|
434
|
+
label: local[this.sessionId]?.label ?? null,
|
|
435
|
+
source: 'local',
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const rows = [...byId.values()].map((r) => ({ ...r, active: r.sessionId === this.sessionId }));
|
|
440
|
+
rows.sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
|
|
441
|
+
return { sessions: rows, remoteError };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
remove(sessionId) {
|
|
445
|
+
if (!sessionId) throw new Error('sessionId is required');
|
|
446
|
+
if (sessionId === this.sessionId) throw new Error('cannot delete the active session; switch to another first');
|
|
447
|
+
const e = entry(this.agent.name, sessionId);
|
|
448
|
+
e.hidden = true;
|
|
449
|
+
delete e.label;
|
|
450
|
+
this.live.delete(sessionId);
|
|
451
|
+
saveStore(this.agent.name);
|
|
452
|
+
return { sessionId, deleted: true };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
rename(sessionId, label) {
|
|
456
|
+
const id = sessionId || this.sessionId;
|
|
457
|
+
if (!id) throw new Error('no active session to rename');
|
|
458
|
+
const e = entry(this.agent.name, id);
|
|
459
|
+
if (label === null || label === '') delete e.label;
|
|
460
|
+
else e.label = label;
|
|
461
|
+
if (!e.cwd) e.cwd = this.cwd;
|
|
462
|
+
saveStore(this.agent.name);
|
|
463
|
+
return { sessionId: id, label: e.label ?? null };
|
|
464
|
+
}
|
|
465
|
+
}
|