omp-superagent 0.0.0-stage → 0.1.2
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/DESIGN.md +1502 -0
- package/LICENSE +21 -0
- package/README.ko.md +198 -0
- package/README.md +224 -2
- package/THIRD_PARTY_NOTICES.md +388 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1178 -0
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +65 -4
- package/scripts/ci.ts +33 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +58 -0
- package/scripts/setup.sh +25 -0
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +100 -0
- package/skills/head/references/model-selection.md +83 -0
- package/skills/head/references/routing.md +181 -0
- package/skills/head/references/supervision.md +122 -0
- package/skills/lane/SKILL.md +66 -0
- package/skills/lane/references/workflow.md +95 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +253 -0
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +266 -0
- package/src/contracts.ts +381 -0
- package/src/credentials.ts +172 -0
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +17 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +1012 -0
- package/src/extension.ts +446 -0
- package/src/gateway-client.ts +229 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +440 -0
- package/src/gateway-store.ts +251 -0
- package/src/gateway.ts +654 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +561 -0
- package/src/host-owner.ts +366 -0
- package/src/host-protocol.ts +144 -0
- package/src/host-services.ts +54 -0
- package/src/host.ts +415 -0
- package/src/installed-omp.ts +71 -0
- package/src/lane-extension.ts +184 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/lane-rows.ts +12 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +143 -0
- package/src/native-presets.ts +370 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +131 -0
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +4229 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +779 -0
- package/src/store.ts +862 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +677 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@oh-my-pi/pi-coding-agent";
|
|
2
|
+
import { IsStandardObject as isRecord } from "@sinclair/typebox/value";
|
|
3
|
+
import { acquireModelRoleMutation, getModelPreset, getModelPresetNames, isValidModelPresetName } from "@oh-my-pi/pi-coding-agent/config/model-presets";
|
|
4
|
+
import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
|
|
5
|
+
import type { Settings, SettingsMirrorState } from "@oh-my-pi/pi-coding-agent/config/settings";
|
|
6
|
+
import { cfgDefaultThinkingLevel } from "@oh-my-pi/pi-coding-agent/session/settings";
|
|
7
|
+
import { MODEL_PRESET_NAMES, type LaneModel, type LanePresetSnapshot, type ResolvedLanePreset, type StorePort } from "./contracts";
|
|
8
|
+
import { isLaneModel, sameLaneModel } from "./lane-models";
|
|
9
|
+
import { editNativeGlobalConfig, hasUnresolvedNativeLegacy, readNativeSettings } from "./native-settings";
|
|
10
|
+
|
|
11
|
+
export type NativeModel = Awaited<ReturnType<ExtensionContext["models"]["list"]>>[number];
|
|
12
|
+
export type BootstrapName = (typeof MODEL_PRESET_NAMES)[number];
|
|
13
|
+
type PresetSource = "runtime" | "overlay" | "project" | "global";
|
|
14
|
+
export type NativePresetChoices = Partial<Record<BootstrapName, { model: LaneModel; reason: string }>>;
|
|
15
|
+
const followingRoles = { high: "slow", middle: "default", low: "smol" } as const;
|
|
16
|
+
const followedPresets = "head:role-following-presets";
|
|
17
|
+
type FollowedPreset = { readonly preset: LanePresetSnapshot; readonly roles?: string };
|
|
18
|
+
type PresetOwnership = Partial<Record<BootstrapName, FollowedPreset | null>>;
|
|
19
|
+
|
|
20
|
+
export interface NativePresetStatus {
|
|
21
|
+
name: string;
|
|
22
|
+
status: "valid" | "invalid" | "missing" | "disabled";
|
|
23
|
+
source?: PresetSource;
|
|
24
|
+
reason?: string;
|
|
25
|
+
/** A hidden global entry also prevents initialization from replacing it. */
|
|
26
|
+
globalEntry: boolean;
|
|
27
|
+
available: boolean;
|
|
28
|
+
resolvedDefault?: LaneModel;
|
|
29
|
+
modelRoles?: Record<string, string>;
|
|
30
|
+
defaultThinkingLevel?: LanePresetSnapshot["defaultThinkingLevel"];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface NativePresetInspection {
|
|
34
|
+
settings: LanePresetSnapshot;
|
|
35
|
+
configuredDefault: { available: boolean; resolvedDefault?: LaneModel; reason?: string };
|
|
36
|
+
availableModels: LaneModel[];
|
|
37
|
+
presets: NativePresetStatus[];
|
|
38
|
+
bootstrap: { missing: BootstrapName[]; blocked: BootstrapName[] };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isCodingModel(model: NativeModel): boolean {
|
|
42
|
+
return isLaneModel(model) && (model.kind === undefined || model.kind === "chat");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Native getOwnedModelPreset hides tombstones, so inspect just their ownership, not their payload. */
|
|
46
|
+
function disabledSource(state: SettingsMirrorState, name: string): PresetSource | undefined {
|
|
47
|
+
for (const [source, layer] of [["runtime", state.overrides], ["overlay", state.configOverlay]] as const) {
|
|
48
|
+
if (!Object.hasOwn(layer, "modelPresets")) continue;
|
|
49
|
+
const presets = layer.modelPresets;
|
|
50
|
+
if (isRecord(presets) && Object.hasOwn(presets, name)) {
|
|
51
|
+
return presets[name] === null || presets[name] === undefined ? source : undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Native settings are the sole registry. No active role is changed to inspect or resolve a preset. */
|
|
58
|
+
export class NativePresetManager {
|
|
59
|
+
private readonly source: Settings;
|
|
60
|
+
|
|
61
|
+
constructor(
|
|
62
|
+
private settings: Settings,
|
|
63
|
+
private readonly availableModels: () => Promise<NativeModel[]>,
|
|
64
|
+
private readonly hasConcreteAuth: (provider: string) => boolean,
|
|
65
|
+
) {
|
|
66
|
+
if (settings.overlayParent() || settings.mirrorState().derived) {
|
|
67
|
+
throw new Error("Native presets require the persistent native base settings");
|
|
68
|
+
}
|
|
69
|
+
this.source = settings;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private async reload(): Promise<void> {
|
|
73
|
+
await this.source.reloadFromDisk();
|
|
74
|
+
this.settings = await readNativeSettings(this.source);
|
|
75
|
+
if (await hasUnresolvedNativeLegacy(this.settings.getAgentDir())) {
|
|
76
|
+
throw new Error("Native global settings require legacy migration");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private capture(): LanePresetSnapshot {
|
|
81
|
+
return {
|
|
82
|
+
modelRoles: Object.fromEntries(Object.entries(this.settings.getModelRoles())
|
|
83
|
+
.filter((entry): entry is [string, string] => typeof entry[1] === "string" && entry[1].length > 0)),
|
|
84
|
+
defaultThinkingLevel: cfgDefaultThinkingLevel.get(this.settings),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private freeze(
|
|
89
|
+
name: string, preset: LanePresetSnapshot, models: NativeModel[],
|
|
90
|
+
thinkingContext?: Pick<LanePresetSnapshot, "defaultThinkingLevel">,
|
|
91
|
+
): ResolvedLanePreset {
|
|
92
|
+
const selector = preset.modelRoles.default;
|
|
93
|
+
const resolved = selector ? resolveModelRoleValue(selector, models, {
|
|
94
|
+
settings: this.settings,
|
|
95
|
+
// Native preset application resolves aliases against the whole preset first,
|
|
96
|
+
// falling through to configured roles only when that role is absent.
|
|
97
|
+
roleLookup: {
|
|
98
|
+
getModelRole: role => Object.hasOwn(preset.modelRoles, role)
|
|
99
|
+
? preset.modelRoles[role] : this.settings.getModelRole(role),
|
|
100
|
+
},
|
|
101
|
+
}) : undefined;
|
|
102
|
+
const model = selector ? resolved?.model : pickDefaultAvailableModel(models, this.hasConcreteAuth);
|
|
103
|
+
if (!model) throw new Error(selector
|
|
104
|
+
? `Default model selector for native preset "${name}" is not available in the authorized coding-model pool`
|
|
105
|
+
: `No authorized coding model is available for native preset "${name}"`);
|
|
106
|
+
// Keep the preset's thinking policy intact. An explicit selector effort wins
|
|
107
|
+
// over that policy in native OMP, so retain its resolved equivalent as a suffix.
|
|
108
|
+
const suffix = resolved?.explicitThinkingLevel && resolved.thinkingLevel !== undefined
|
|
109
|
+
? `:${resolved.thinkingLevel}` : "";
|
|
110
|
+
const snapshot: LanePresetSnapshot = {
|
|
111
|
+
...preset,
|
|
112
|
+
modelRoles: { ...preset.modelRoles, default: `${model.provider}/${model.id}${suffix}` },
|
|
113
|
+
// Native omission keeps the current level. A supplied HEAD context owns
|
|
114
|
+
// that policy even when undefined; lanes freeze the persistent base now
|
|
115
|
+
// rather than reading a changed level when the lane is reopened.
|
|
116
|
+
defaultThinkingLevel: preset.defaultThinkingLevel ?? (thinkingContext !== undefined
|
|
117
|
+
? thinkingContext.defaultThinkingLevel : cfgDefaultThinkingLevel.get(this.settings)),
|
|
118
|
+
};
|
|
119
|
+
return { preset: name, model: { provider: model.provider, id: model.id }, snapshot };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private inspectLoaded(models: NativeModel[]): NativePresetInspection {
|
|
123
|
+
const state = this.settings.mirrorState();
|
|
124
|
+
const names = new Set<string>([...MODEL_PRESET_NAMES, ...getModelPresetNames(this.settings)]);
|
|
125
|
+
for (const layer of [state.global, state.project, state.configOverlay, state.overrides]) {
|
|
126
|
+
if (isRecord(layer.modelPresets)) for (const name of Object.keys(layer.modelPresets)) names.add(name);
|
|
127
|
+
}
|
|
128
|
+
const presets: NativePresetStatus[] = [...names].sort().map(name => {
|
|
129
|
+
const globalEntry = isRecord(state.global.modelPresets) && Object.hasOwn(state.global.modelPresets, name);
|
|
130
|
+
const disabled = disabledSource(state, name);
|
|
131
|
+
if (disabled) return { name, status: "disabled", source: disabled, globalEntry, available: false };
|
|
132
|
+
const lookup = getModelPreset(this.settings, name);
|
|
133
|
+
const source = this.settings.getOwnedModelPreset(name)?.source;
|
|
134
|
+
if (lookup.kind === "missing") {
|
|
135
|
+
return { name, status: "missing", globalEntry, available: false,
|
|
136
|
+
...(globalEntry ? { reason: "A global entry already owns this name" } : {}) };
|
|
137
|
+
}
|
|
138
|
+
if (lookup.kind === "invalid") {
|
|
139
|
+
return { name, status: "invalid", source, globalEntry, available: false, reason: lookup.reason };
|
|
140
|
+
}
|
|
141
|
+
const status: NativePresetStatus = { name, status: "valid", source, globalEntry,
|
|
142
|
+
modelRoles: { ...lookup.preset.modelRoles }, available: false,
|
|
143
|
+
...(lookup.preset.defaultThinkingLevel !== undefined
|
|
144
|
+
? { defaultThinkingLevel: lookup.preset.defaultThinkingLevel } : {}) };
|
|
145
|
+
try { status.resolvedDefault = this.freeze(name, lookup.preset, models).model; status.available = true; }
|
|
146
|
+
catch (error) { status.reason = (error as Error).message; }
|
|
147
|
+
return status;
|
|
148
|
+
});
|
|
149
|
+
const settings = this.capture();
|
|
150
|
+
let configuredDefault: NativePresetInspection["configuredDefault"];
|
|
151
|
+
try { configuredDefault = { available: true, resolvedDefault: this.freeze("configured default", settings, models).model }; }
|
|
152
|
+
catch (error) { configuredDefault = { available: false, reason: (error as Error).message }; }
|
|
153
|
+
return {
|
|
154
|
+
settings, configuredDefault, availableModels: models.map(model => ({ provider: model.provider, id: model.id })), presets,
|
|
155
|
+
bootstrap: {
|
|
156
|
+
missing: MODEL_PRESET_NAMES.filter(name => presets.some(p => p.name === name && p.status === "missing" && !p.globalEntry)),
|
|
157
|
+
blocked: MODEL_PRESET_NAMES.filter(name => presets.some(p => p.name === name &&
|
|
158
|
+
(p.status === "disabled" || p.status === "invalid" || (p.status === "missing" && p.globalEntry)))),
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async inspect(): Promise<NativePresetInspection> {
|
|
164
|
+
await this.reload();
|
|
165
|
+
return this.inspectLoaded((await this.availableModels()).filter(isCodingModel));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Follow persistent native roles without changing the active native session. */
|
|
169
|
+
async syncRoles(store: Pick<StorePort, "getMeta" | "setMeta">, canWrite: () => boolean,
|
|
170
|
+
reloadCatalog?: () => Promise<void>): Promise<void> {
|
|
171
|
+
const release = await acquireModelRoleMutation();
|
|
172
|
+
try {
|
|
173
|
+
await this.reload();
|
|
174
|
+
if (!canWrite()) return;
|
|
175
|
+
const settings = this.settings;
|
|
176
|
+
const base = this.capture();
|
|
177
|
+
const before = store.getMeta(followedPresets);
|
|
178
|
+
const ownership: PresetOwnership = before === null ? {} : JSON.parse(before);
|
|
179
|
+
const resolveRoles = (models: NativeModel[]) => MODEL_PRESET_NAMES.map(name => {
|
|
180
|
+
const selector = base.modelRoles[followingRoles[name]];
|
|
181
|
+
const resolution = selector ? resolveModelRoleValue(selector, models, { settings }) : undefined;
|
|
182
|
+
const model = resolution?.model;
|
|
183
|
+
const defaultSelector = model ? `${model.provider}/${model.id}${
|
|
184
|
+
resolution?.explicitThinkingLevel && resolution.thinkingLevel !== undefined ? `:${resolution.thinkingLevel}` : ""}` : null;
|
|
185
|
+
return { name, selector, model, defaultSelector };
|
|
186
|
+
});
|
|
187
|
+
let models = (await this.availableModels()).filter(isCodingModel);
|
|
188
|
+
let resolved = resolveRoles(models);
|
|
189
|
+
if (reloadCatalog && canWrite() && resolved.some(({ selector, model }) => selector && !model)) {
|
|
190
|
+
// Another OMP process may have discovered the new model after this
|
|
191
|
+
// head loaded its registry. Read through the native cache, not the network.
|
|
192
|
+
await reloadCatalog();
|
|
193
|
+
models = (await this.availableModels()).filter(isCodingModel);
|
|
194
|
+
resolved = resolveRoles(models);
|
|
195
|
+
}
|
|
196
|
+
const roles = JSON.stringify(resolved.map(({ selector, defaultSelector }) => [selector ?? null, defaultSelector]));
|
|
197
|
+
// A temporarily unavailable configured role is not a new policy.
|
|
198
|
+
if (resolved.some(({ selector, defaultSelector }) => selector && !defaultSelector)) return;
|
|
199
|
+
const edits: { name: BootstrapName; snapshot: LanePresetSnapshot }[] = [];
|
|
200
|
+
for (const { name, model, defaultSelector } of resolved) {
|
|
201
|
+
if (!canWrite()) break;
|
|
202
|
+
const tracked = ownership[name];
|
|
203
|
+
if (tracked === null) continue; // A manual edit/deletion releases management.
|
|
204
|
+
const owned = settings.getOwnedModelPreset(name);
|
|
205
|
+
const current = getModelPreset(settings, name);
|
|
206
|
+
if (!owned || owned.source !== "global" || current.kind !== "found") {
|
|
207
|
+
if (tracked && !owned && !disabledSource(settings.mirrorState(), name)) ownership[name] = null;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const preset = current.preset;
|
|
211
|
+
if (tracked && !Bun.deepEquals(preset, tracked.preset)) {
|
|
212
|
+
ownership[name] = null;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (!model || !defaultSelector) continue;
|
|
216
|
+
if (!tracked) {
|
|
217
|
+
// Adopt only an earlier full role snapshot that already selects this
|
|
218
|
+
// role's model. An unrelated/manual preset is not ours to replace.
|
|
219
|
+
const { default: _old, ...oldRoles } = preset.modelRoles;
|
|
220
|
+
const { default: _base, ...baseRoles } = base.modelRoles;
|
|
221
|
+
const old = resolveModelRoleValue(preset.modelRoles.default, models, { settings });
|
|
222
|
+
if (!Bun.deepEquals(oldRoles, baseRoles) || !sameLaneModel(old?.model, model)) continue;
|
|
223
|
+
ownership[name] = { preset, roles };
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (tracked.roles === roles) continue;
|
|
227
|
+
const next = { ...base, modelRoles: { ...base.modelRoles, default: defaultSelector } };
|
|
228
|
+
if (Bun.deepEquals(preset, next)) ownership[name] = { preset, roles };
|
|
229
|
+
else edits.push({ name, snapshot: next });
|
|
230
|
+
}
|
|
231
|
+
if (edits.length) {
|
|
232
|
+
const applied = await editNativeGlobalConfig(settings, edits.map(({ name, snapshot }) => ({
|
|
233
|
+
path: `modelPresets.${name}`, value: snapshot,
|
|
234
|
+
})), actual => canWrite() && edits.every(({ name }) => actual.getOwnedModelPreset(name)?.source === "global")
|
|
235
|
+
&& Bun.deepEquals(actual.getModelRoles(), base.modelRoles)
|
|
236
|
+
&& cfgDefaultThinkingLevel.get(actual) === base.defaultThinkingLevel);
|
|
237
|
+
for (const [index, { name, snapshot }] of edits.entries()) if (applied[index]) ownership[name] = { preset: snapshot, roles };
|
|
238
|
+
}
|
|
239
|
+
const saved = JSON.stringify(ownership);
|
|
240
|
+
if (saved !== (before ?? "{}")) store.setMeta(followedPresets, saved);
|
|
241
|
+
} finally { release(); }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async resolve(name: string, thinkingContext?: Pick<LanePresetSnapshot, "defaultThinkingLevel">): Promise<ResolvedLanePreset> {
|
|
245
|
+
if (typeof name !== "string" || !isValidModelPresetName(name)) throw new Error("Invalid native preset name");
|
|
246
|
+
await this.reload();
|
|
247
|
+
const lookup = getModelPreset(this.settings, name);
|
|
248
|
+
if (lookup.kind !== "found") throw new Error(`Native preset "${name}" is ${lookup.kind}`);
|
|
249
|
+
return this.freeze(name, lookup.preset, (await this.availableModels()).filter(isCodingModel), thinkingContext);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Persist the frozen snapshot only after the head has successfully applied it.
|
|
254
|
+
* Global defaults are replaced in full, independent of modelRoleStorage; named
|
|
255
|
+
* presets and higher-priority project/overlay/runtime settings stay untouched.
|
|
256
|
+
* Those layers can still shadow these defaults in other sessions. A failed
|
|
257
|
+
* save/readback is reported without rolling back the successful head selection.
|
|
258
|
+
*/
|
|
259
|
+
async persistSelection(selection: ResolvedLanePreset): Promise<LanePresetSnapshot> {
|
|
260
|
+
const expected: LanePresetSnapshot = {
|
|
261
|
+
modelRoles: { ...selection.snapshot.modelRoles },
|
|
262
|
+
...(selection.snapshot.defaultThinkingLevel !== undefined
|
|
263
|
+
? { defaultThinkingLevel: selection.snapshot.defaultThinkingLevel } : {}),
|
|
264
|
+
};
|
|
265
|
+
const release = await acquireModelRoleMutation();
|
|
266
|
+
try {
|
|
267
|
+
await this.reload();
|
|
268
|
+
const validation = getModelPreset(this.settings.overlay({ modelPresets: { selection: expected } }), "selection");
|
|
269
|
+
if (validation.kind !== "found") throw new Error("Invalid native model selection snapshot");
|
|
270
|
+
// Explicit global authorization replaces this record, not the host's
|
|
271
|
+
// active model scope or any project/overlay/runtime assignment.
|
|
272
|
+
await editNativeGlobalConfig(this.settings, [
|
|
273
|
+
{ path: "modelRoles", value: expected.modelRoles },
|
|
274
|
+
{ path: "defaultThinkingLevel", value: expected.defaultThinkingLevel },
|
|
275
|
+
]);
|
|
276
|
+
await this.reload();
|
|
277
|
+
const global = this.settings.getGlobalSettings();
|
|
278
|
+
const persisted = {
|
|
279
|
+
modelRoles: global.modelRoles,
|
|
280
|
+
...(global.defaultThinkingLevel !== undefined
|
|
281
|
+
? { defaultThinkingLevel: global.defaultThinkingLevel } : {}),
|
|
282
|
+
};
|
|
283
|
+
if (!Bun.deepEquals(persisted, expected)) {
|
|
284
|
+
throw new Error("Global model defaults do not match the applied preset after native readback");
|
|
285
|
+
}
|
|
286
|
+
return persisted as LanePresetSnapshot;
|
|
287
|
+
} finally { release(); }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Application conditional creation checks absence under the native persistence
|
|
292
|
+
* lock, so an operator insertion after preview is preserved. This is not a
|
|
293
|
+
* multi-entry transaction: partial creation and conflicts are read back, never
|
|
294
|
+
* repaired by overwriting or rolling back the operator's entry.
|
|
295
|
+
*/
|
|
296
|
+
async initialize(choices: NativePresetChoices, store?: Pick<StorePort, "getMeta" | "setMeta">): Promise<{
|
|
297
|
+
created: BootstrapName[]; preserved: BootstrapName[]; conflicts: BootstrapName[]; inspection: NativePresetInspection;
|
|
298
|
+
}> {
|
|
299
|
+
if (!isRecord(choices) || Object.keys(choices).length === 0) {
|
|
300
|
+
throw new Error("Native preset choices must be a nonempty mapping");
|
|
301
|
+
}
|
|
302
|
+
for (const [name, choice] of Object.entries(choices)) {
|
|
303
|
+
if (!(MODEL_PRESET_NAMES as readonly string[]).includes(name) || !isRecord(choice) ||
|
|
304
|
+
!isRecord(choice.model) || typeof choice.model.provider !== "string" || !choice.model.provider.trim() ||
|
|
305
|
+
typeof choice.model.id !== "string" || !choice.model.id.trim() ||
|
|
306
|
+
typeof choice.reason !== "string" || !choice.reason.trim()) {
|
|
307
|
+
throw new Error("Each native bootstrap choice requires high/middle/low, an exact model identity, and a reason");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const release = await acquireModelRoleMutation();
|
|
311
|
+
try {
|
|
312
|
+
await this.reload();
|
|
313
|
+
// Validate every supplied candidate before any writes, including choices
|
|
314
|
+
// whose existing preset will be preserved rather than replaced.
|
|
315
|
+
const models = (await this.availableModels()).filter(isCodingModel);
|
|
316
|
+
for (const name of MODEL_PRESET_NAMES) {
|
|
317
|
+
const choice = choices[name];
|
|
318
|
+
if (!choice) continue;
|
|
319
|
+
if (!models.some(model => model.provider === choice.model.provider && model.id === choice.model.id)) {
|
|
320
|
+
throw new Error("Native bootstrap choice is not an available authorized coding model");
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const before = this.inspectLoaded(models);
|
|
324
|
+
const expected = new Map<BootstrapName, LanePresetSnapshot>();
|
|
325
|
+
const preserved: BootstrapName[] = [];
|
|
326
|
+
const conflicts: BootstrapName[] = [];
|
|
327
|
+
const configured = before.settings;
|
|
328
|
+
for (const name of MODEL_PRESET_NAMES) {
|
|
329
|
+
const choice = choices[name];
|
|
330
|
+
if (!choice) continue;
|
|
331
|
+
if (!before.bootstrap.missing.includes(name)) {
|
|
332
|
+
preserved.push(name);
|
|
333
|
+
if (before.bootstrap.blocked.includes(name)) conflicts.push(name);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
expected.set(name, { ...configured, modelRoles: { ...configured.modelRoles,
|
|
337
|
+
default: `${choice.model.provider}/${choice.model.id}` } });
|
|
338
|
+
}
|
|
339
|
+
const staged = new Set<BootstrapName>();
|
|
340
|
+
for (const [name, snapshot] of expected) {
|
|
341
|
+
const [created] = await editNativeGlobalConfig(this.settings, [
|
|
342
|
+
{ path: `modelPresets.${name}`, value: snapshot, ifMissing: true },
|
|
343
|
+
]);
|
|
344
|
+
if (created) staged.add(name);
|
|
345
|
+
else conflicts.push(name);
|
|
346
|
+
}
|
|
347
|
+
if (expected.size > 0) {
|
|
348
|
+
await this.reload();
|
|
349
|
+
}
|
|
350
|
+
const created: BootstrapName[] = [];
|
|
351
|
+
for (const [name, snapshot] of expected) {
|
|
352
|
+
if (!staged.has(name)) continue;
|
|
353
|
+
const lookup = getModelPreset(this.settings, name);
|
|
354
|
+
const global = this.settings.getGlobalSettings().modelPresets;
|
|
355
|
+
if (lookup.kind === "found" && this.settings.getOwnedModelPreset(name)?.source === "global" &&
|
|
356
|
+
isRecord(global) && Bun.deepEquals(global[name], snapshot)) created.push(name);
|
|
357
|
+
else conflicts.push(name);
|
|
358
|
+
}
|
|
359
|
+
if (store && created.length) {
|
|
360
|
+
const ownership: PresetOwnership = JSON.parse(store.getMeta(followedPresets) ?? "{}");
|
|
361
|
+
for (const name of created) {
|
|
362
|
+
const preset = expected.get(name);
|
|
363
|
+
if (preset) ownership[name] = { preset };
|
|
364
|
+
}
|
|
365
|
+
store.setMeta(followedPresets, JSON.stringify(ownership));
|
|
366
|
+
}
|
|
367
|
+
return { created, preserved, conflicts, inspection: this.inspectLoaded(models) };
|
|
368
|
+
} finally { release(); }
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { SessionManager } from "@oh-my-pi/pi-coding-agent/session/session-manager";
|
|
4
|
+
import { readSessionInfo } from "@oh-my-pi/pi-coding-agent/session/session-listing";
|
|
5
|
+
|
|
6
|
+
/** Stock OMP follows leaf session links for discovery and writes through them. */
|
|
7
|
+
export async function publishNativeSession(sessionFile: string, cwd: string): Promise<string | undefined> {
|
|
8
|
+
const info = await readSessionInfo(sessionFile);
|
|
9
|
+
if (!info) return;
|
|
10
|
+
const source = await fs.realpath(sessionFile);
|
|
11
|
+
const directory = SessionManager.getDefaultSessionDir(cwd);
|
|
12
|
+
const target = join(directory, `${info.created.toISOString().replace(/[:.]/g, "-")}_${info.id}.jsonl`);
|
|
13
|
+
if (target === source) return target;
|
|
14
|
+
|
|
15
|
+
const link = async (original: string, destination: string) => {
|
|
16
|
+
try { await fs.symlink(original, destination); }
|
|
17
|
+
catch (error) {
|
|
18
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
19
|
+
const existing = await fs.readlink(destination).catch(() => undefined);
|
|
20
|
+
if (!existing || resolve(dirname(destination), existing) !== original)
|
|
21
|
+
throw new Error(`Native session discovery path already belongs to another file: ${destination}`);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
// The resumed session must keep its original spill artifacts and child journals.
|
|
25
|
+
if (source.endsWith(".jsonl")) {
|
|
26
|
+
const artifacts = source.slice(0, -".jsonl".length);
|
|
27
|
+
await fs.mkdir(artifacts, { recursive: true, mode: 0o700 });
|
|
28
|
+
await link(artifacts, target.slice(0, -".jsonl".length));
|
|
29
|
+
}
|
|
30
|
+
await link(source, target);
|
|
31
|
+
return target;
|
|
32
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { basename, delimiter, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
|
|
4
|
+
import { writeFileAtomically } from "@oh-my-pi/pi-coding-agent/utils/atomic-file";
|
|
5
|
+
import { getAgentDbPath, MAIN_CONFIG_FILENAMES } from "@oh-my-pi/pi-utils/dirs";
|
|
6
|
+
import { withFileLock } from "@oh-my-pi/pi-utils/file-lock";
|
|
7
|
+
import { expandTilde } from "@oh-my-pi/pi-utils/path";
|
|
8
|
+
import { stringifyYamlConfig } from "@oh-my-pi/pi-utils/yaml-config";
|
|
9
|
+
import { IsStandardObject as isRecord } from "@sinclair/typebox/value";
|
|
10
|
+
|
|
11
|
+
async function isPresent(path: string): Promise<boolean> {
|
|
12
|
+
try { await stat(path); return true; }
|
|
13
|
+
catch (error) {
|
|
14
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A read-only native load deliberately cannot settle unmigrated global storage. */
|
|
20
|
+
export async function hasUnresolvedNativeLegacy(agentDir: string): Promise<boolean> {
|
|
21
|
+
for (const filename of MAIN_CONFIG_FILENAMES) {
|
|
22
|
+
if (await isPresent(join(agentDir, filename))) return false;
|
|
23
|
+
}
|
|
24
|
+
return (await Promise.all([
|
|
25
|
+
isPresent(join(agentDir, "settings.json")), isPresent(getAgentDbPath(agentDir)),
|
|
26
|
+
])).some(Boolean);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readNativeSettings(settings: Settings): Promise<Settings> {
|
|
30
|
+
const cwd = settings.getCwd();
|
|
31
|
+
const configFiles = settings.getConfigFiles();
|
|
32
|
+
// Stock loading prepends PI_CONFIG_FILES itself. Do not replay that prefix
|
|
33
|
+
// twice, which would merge array-valued overlays twice as well.
|
|
34
|
+
const environmentFiles = (process.env.PI_CONFIG_FILES?.split(delimiter).filter(Boolean) ?? [])
|
|
35
|
+
.map(file => resolve(cwd, expandTilde(file)));
|
|
36
|
+
if (environmentFiles.some((file, index) => configFiles[index] !== file)) {
|
|
37
|
+
throw new Error("Native config overlay environment changed after the scope was loaded");
|
|
38
|
+
}
|
|
39
|
+
return Settings.loadReadOnly({
|
|
40
|
+
cwd, agentDir: settings.getAgentDir(),
|
|
41
|
+
configFiles: configFiles.slice(environmentFiles.length), overrides: settings.mirrorState().overrides,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type GlobalEdit = {
|
|
46
|
+
path: "memory.backend" | "modelRoles" | "defaultThinkingLevel" | `modelPresets.${string}`;
|
|
47
|
+
value: unknown;
|
|
48
|
+
/** Preset creation never replaces a global entry or a higher-layer owner. */
|
|
49
|
+
ifMissing?: boolean;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function valueAt(record: unknown, path: readonly string[]): unknown {
|
|
53
|
+
for (const segment of path) {
|
|
54
|
+
record = isRecord(record) && Object.hasOwn(record, segment) ? record[segment] : undefined;
|
|
55
|
+
}
|
|
56
|
+
return record;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Application-owned edits only. Native read-only loading validates all inputs;
|
|
61
|
+
* the native lock and atomic publisher serialize with stock Settings writers.
|
|
62
|
+
* A stale key is preserved while disjoint keys are merged from the locked file.
|
|
63
|
+
*/
|
|
64
|
+
export async function editNativeGlobalConfig(settings: Settings, edits: readonly GlobalEdit[],
|
|
65
|
+
accept?: (actual: Settings) => boolean): Promise<boolean[]> {
|
|
66
|
+
const agentDir = settings.getAgentDir();
|
|
67
|
+
if (await hasUnresolvedNativeLegacy(agentDir)) throw new Error("Native global settings require legacy migration");
|
|
68
|
+
let configPath = join(agentDir, MAIN_CONFIG_FILENAMES[0]);
|
|
69
|
+
for (const filename of MAIN_CONFIG_FILENAMES) {
|
|
70
|
+
const candidate = join(agentDir, filename);
|
|
71
|
+
if (await isPresent(candidate)) { configPath = candidate; break; }
|
|
72
|
+
}
|
|
73
|
+
await mkdir(agentDir, { recursive: true });
|
|
74
|
+
let writePath: string;
|
|
75
|
+
try { writePath = await realpath(configPath); }
|
|
76
|
+
catch (error) {
|
|
77
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
78
|
+
// Never replace a dangling user-managed symlink with a regular config file.
|
|
79
|
+
try {
|
|
80
|
+
if ((await lstat(configPath)).isSymbolicLink()) throw new Error("Native global config symlink has no target");
|
|
81
|
+
} catch (metadataError) {
|
|
82
|
+
if ((metadataError as NodeJS.ErrnoException).code !== "ENOENT") throw metadataError;
|
|
83
|
+
}
|
|
84
|
+
writePath = join(await realpath(dirname(configPath)), basename(configPath));
|
|
85
|
+
}
|
|
86
|
+
const baseline = settings.getGlobalSettings();
|
|
87
|
+
return withFileLock(writePath, async () => {
|
|
88
|
+
const actual = await readNativeSettings(settings);
|
|
89
|
+
if (await hasUnresolvedNativeLegacy(agentDir)) throw new Error("Native global settings require legacy migration");
|
|
90
|
+
if (accept && !accept(actual)) return edits.map(() => false);
|
|
91
|
+
for (const filename of MAIN_CONFIG_FILENAMES) {
|
|
92
|
+
const candidate = join(agentDir, filename);
|
|
93
|
+
if (await isPresent(candidate)) {
|
|
94
|
+
if (candidate !== configPath || await realpath(candidate) !== writePath) {
|
|
95
|
+
throw new Error("Native global config destination changed during the edit");
|
|
96
|
+
}
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
let raw: unknown;
|
|
101
|
+
try { raw = Bun.YAML.parse(await readFile(writePath, "utf8")); }
|
|
102
|
+
catch (error) {
|
|
103
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
104
|
+
}
|
|
105
|
+
if (raw === null || raw === undefined) raw = {};
|
|
106
|
+
if (!isRecord(raw)) throw new Error("Native global config must be a mapping");
|
|
107
|
+
const global = raw;
|
|
108
|
+
const updated = structuredClone(global);
|
|
109
|
+
const applied = edits.map(edit => {
|
|
110
|
+
const path = edit.path.split(".");
|
|
111
|
+
if (edit.ifMissing) {
|
|
112
|
+
const name = path[1]!;
|
|
113
|
+
if (Object.hasOwn(isRecord(global.modelPresets) ? global.modelPresets : {}, name) ||
|
|
114
|
+
actual.getOwnedModelPreset(name) ||
|
|
115
|
+
[actual.mirrorState().overrides, actual.mirrorState().configOverlay].some(layer =>
|
|
116
|
+
isRecord(layer.modelPresets) && Object.hasOwn(layer.modelPresets, name))) return false;
|
|
117
|
+
} else if (!Bun.deepEquals(valueAt(global, path), valueAt(baseline, path))) return false;
|
|
118
|
+
let target = updated;
|
|
119
|
+
for (const segment of path.slice(0, -1)) {
|
|
120
|
+
if (!isRecord(target[segment])) target[segment] = {};
|
|
121
|
+
target = target[segment] as Record<string, unknown>;
|
|
122
|
+
}
|
|
123
|
+
const key = path.at(-1)!;
|
|
124
|
+
if (edit.value === undefined) delete target[key];
|
|
125
|
+
else target[key] = structuredClone(edit.value);
|
|
126
|
+
return true;
|
|
127
|
+
});
|
|
128
|
+
if (!Bun.deepEquals(updated, global)) await writeFileAtomically(writePath, stringifyYamlConfig(updated));
|
|
129
|
+
return applied;
|
|
130
|
+
});
|
|
131
|
+
}
|