odai-dsh-agent 0.2.0 → 0.2.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.
Files changed (61) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +138 -134
  3. package/bin/odai-dsh-agent.mjs +108 -108
  4. package/package.json +69 -69
  5. package/preset/odai/agent.cordis.yml +260 -260
  6. package/preset/odai/preset.yml +3 -3
  7. package/preset/odai/runtime/compaction-config.mjs +388 -388
  8. package/preset/odai/runtime/context-activation.mjs +71 -0
  9. package/preset/odai/runtime/context-capability.mjs +86 -0
  10. package/preset/odai/runtime/governance.mjs +128 -121
  11. package/preset/odai/runtime/human-care.mjs +45 -0
  12. package/preset/odai/runtime/human-safety-continuity.mjs +2 -2
  13. package/preset/odai/runtime/human-safety.mjs +3 -3
  14. package/preset/odai/runtime/index.mjs +2461 -1977
  15. package/preset/odai/runtime/output-config.mjs +360 -304
  16. package/preset/odai/runtime/research-packet.mjs +150 -150
  17. package/preset/odai/runtime/responsibility-gap.mjs +8 -10
  18. package/preset/odai/runtime/responsibility-scope.mjs +199 -0
  19. package/preset/odai/runtime/role-overlays.mjs +27 -27
  20. package/preset/odai/runtime/route-card.mjs +168 -152
  21. package/preset/odai/runtime/router.mjs +683 -651
  22. package/preset/odai/runtime/routing-config.mjs +480 -436
  23. package/preset/odai/runtime/routing-context.mjs +321 -321
  24. package/preset/odai/runtime/semantic-memory-store.mjs +452 -452
  25. package/preset/odai/runtime/semantic-memory.mjs +842 -842
  26. package/preset/odai/runtime/session-compat.mjs +389 -389
  27. package/preset/odai/runtime/skill-bundle.mjs +318 -318
  28. package/preset/odai/runtime/skill-evolution.mjs +1413 -1413
  29. package/preset/odai/skills/odai/SKILL.md +69 -68
  30. package/preset/odai/skills/odai/agents/openai.yaml +4 -4
  31. package/preset/odai/skills/odai/assets/claude-agents/agent.md +11 -11
  32. package/preset/odai/skills/odai/assets/codex-agents/config.toml +11 -11
  33. package/preset/odai/skills/odai/assets/codex-agents/role.toml +5 -5
  34. package/preset/odai/skills/odai/assets/copilot-agents/agent.md +13 -13
  35. package/preset/odai/skills/odai/assets/hooks-policy.example.json +24 -24
  36. package/preset/odai/skills/odai/assets/routing-roles/controller.md +15 -15
  37. package/preset/odai/skills/odai/assets/routing-roles/executor.md +11 -11
  38. package/preset/odai/skills/odai/assets/routing-roles/frontend.md +7 -7
  39. package/preset/odai/skills/odai/assets/routing-roles/planner.md +29 -29
  40. package/preset/odai/skills/odai/assets/routing-roles/researcher.md +6 -6
  41. package/preset/odai/skills/odai/assets/routing-roles/reviewer.md +11 -11
  42. package/preset/odai/skills/odai/assets/task-state.md +14 -14
  43. package/preset/odai/skills/odai/manifest.json +37 -36
  44. package/preset/odai/skills/odai/references/care.md +26 -0
  45. package/preset/odai/skills/odai/references/craft.md +54 -54
  46. package/preset/odai/skills/odai/references/dao.md +30 -30
  47. package/preset/odai/skills/odai/references/human-safety.md +33 -54
  48. package/preset/odai/skills/odai/references/leverage.md +53 -53
  49. package/preset/odai/skills/odai/references/planning.md +82 -82
  50. package/preset/odai/skills/odai/references/support.md +36 -36
  51. package/preset/odai/skills/odai/references/verification.md +23 -23
  52. package/preset/odai/skills/odai/scripts/build-hooks.mjs +273 -273
  53. package/preset/odai/skills/odai/scripts/build-routing.mjs +274 -274
  54. package/preset/odai/skills/odai/scripts/install-routing.mjs +397 -397
  55. package/preset/odai/skills/odai/scripts/odai-hook.mjs +457 -457
  56. package/preset/odai/skills/odai/scripts/run-role.mjs +336 -336
  57. package/preset/odai/skills/odai/scripts/run-routing.mjs +1154 -1154
  58. package/preset/odai/skills/odai/scripts/verify-routing.mjs +103 -103
  59. package/scripts/verify-agent-load.mjs +257 -257
  60. package/src/dsh-version.mjs +6 -2
  61. package/src/installer.mjs +382 -382
@@ -1,388 +1,388 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- copyFileSync,
4
- mkdirSync,
5
- readFileSync,
6
- renameSync,
7
- rmSync,
8
- writeFileSync,
9
- } from "node:fs";
10
- import { homedir } from "node:os";
11
- import { dirname, resolve } from "node:path";
12
-
13
- import { requireModelRoute, sameModelRoute } from "./model-route.mjs";
14
- import { acquireOwnedStoreLock } from "./store-lock.mjs";
15
-
16
- const STORE_SCHEMA_VERSION = 1;
17
- const TARGET_FIELDS = new Set(["provider", "model", "reasoningEffort"]);
18
- const STATE_PROTOCOL_SOURCE = Object.freeze({
19
- kind: "plugin",
20
- plugin: "odai-dsh-runtime",
21
- form: "instructions",
22
- });
23
-
24
- export const COMPACTION_STATE_PROTOCOL = [
25
- "Additional checkpoint integrity protocol:",
26
- "- Treat facts explicitly marked CURRENT, corrected, or authoritative as the active state.",
27
- "- Facts marked SUPERSEDED, REJECTED, obsolete, or historical may be retained only as rejected history; never describe them as current, latest, selected, or pending.",
28
- "- Preserve opaque identifiers, paths, commands, status values, delimiters, and numeric values byte-for-byte when they determine continuation state.",
29
- "- Before emitting the checkpoint, self-check that no rejected fact is framed as active and that no active value conflicts with another section.",
30
- ].join("\n");
31
-
32
- export const COMPACTION_CONFIG_PROMPT = [
33
- "## Odai compaction model configuration",
34
- "When the user naturally asks to inspect, set, change, or reset the model or reasoning effort used to summarize compacted context, use odai_compaction_config.",
35
- "Set a compaction target only when the user explicitly supplies both provider and model. Pass reasoningEffort only when the user explicitly supplies it. Never infer or silently choose any value. If the user changes only the effort for an existing persisted target, inspect and preserve that exact provider/model pair.",
36
- "The default is inherit: compaction uses the current conversation route. A configured target changes only compaction-summary requests; it does not change the controller, researcher, planner, executor, reviewer, frontend, normal conversation, summary output budget, or cache-retention policy. An optional explicit reasoning effort is likewise scoped only to compaction summaries; omitting it preserves the existing reasoning inheritance and cross-model isolation behavior.",
37
- "Configured targets also receive a provider-neutral checkpoint integrity protocol that keeps current facts above superseded or rejected history and preserves continuation-critical opaque values exactly.",
38
- "Do not ask the user to edit YAML, JSON, managed Agent files, or Plugin configuration. The tool owns persistence. Set/remove changes apply to the next compaction request.",
39
- "An invalid persisted store is visible through the tool while runtime requests safely inherit the conversation route. If the configured route fails or produces an incomplete summary, DSH must preserve the original history rather than landing a partial checkpoint.",
40
- ].join("\n");
41
-
42
- export class CompactionModelStoreValidationError extends Error {}
43
-
44
- function assertPlainObject(value, field) {
45
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
46
- throw new TypeError(`${field} must be an object`);
47
- }
48
- return value;
49
- }
50
-
51
- export function resolveCompactionTarget(value, field = "Odai compaction model target") {
52
- const target = assertPlainObject(value, field);
53
- const unknown = Object.keys(target).filter((name) => !TARGET_FIELDS.has(name));
54
- if (unknown.length > 0) throw new TypeError(`${field} has unknown fields: ${unknown.join(", ")}`);
55
- if (typeof target.provider !== "string" || target.provider.trim() === "") {
56
- throw new TypeError(`${field}.provider must be a non-empty string`);
57
- }
58
- if (typeof target.model !== "string" || target.model.trim() === "") {
59
- throw new TypeError(`${field}.model must be a non-empty string`);
60
- }
61
- if (target.reasoningEffort !== undefined
62
- && (typeof target.reasoningEffort !== "string" || target.reasoningEffort.trim() === "")) {
63
- throw new TypeError(`${field}.reasoningEffort must be a non-empty string`);
64
- }
65
- return Object.freeze({
66
- provider: target.provider.trim(),
67
- model: target.model.trim(),
68
- ...(target.reasoningEffort === undefined ? {} : { reasoningEffort: target.reasoningEffort.trim() }),
69
- });
70
- }
71
-
72
- export function resolveCompactionConfigPath(configuredPath, env = process.env) {
73
- if (configuredPath !== undefined) {
74
- if (typeof configuredPath !== "string" || configuredPath.trim() === "") {
75
- throw new TypeError("config.compaction.configPath must be a non-empty string");
76
- }
77
- return resolve(configuredPath.trim());
78
- }
79
- const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== ""
80
- ? resolve(env.DSH_HOME.trim())
81
- : resolve(homedir(), ".dsh");
82
- return resolve(dshHome, "odai", "compaction.json");
83
- }
84
-
85
- export function readCompactionModelStore(configPath) {
86
- let text;
87
- try {
88
- text = readFileSync(configPath, "utf8");
89
- } catch (error) {
90
- if (error?.code === "ENOENT") return Object.freeze({ schemaVersion: STORE_SCHEMA_VERSION });
91
- throw new Error(`cannot read Odai compaction model configuration ${configPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
92
- }
93
- let parsed;
94
- try {
95
- parsed = JSON.parse(text);
96
- } catch (error) {
97
- throw new CompactionModelStoreValidationError(`Odai compaction model configuration ${configPath} is not valid JSON`, { cause: error });
98
- }
99
- try {
100
- const store = assertPlainObject(parsed, `Odai compaction model configuration ${configPath}`);
101
- const unknown = Object.keys(store).filter((field) => !["schemaVersion", "target"].includes(field));
102
- if (unknown.length > 0) {
103
- throw new TypeError(`Odai compaction model configuration ${configPath} has unknown fields: ${unknown.join(", ")}`);
104
- }
105
- if (store.schemaVersion !== STORE_SCHEMA_VERSION) {
106
- throw new TypeError(`Odai compaction model configuration ${configPath} has unsupported schemaVersion ${String(store.schemaVersion)}`);
107
- }
108
- if (store.target === undefined) return Object.freeze({ schemaVersion: STORE_SCHEMA_VERSION });
109
- return Object.freeze({
110
- schemaVersion: STORE_SCHEMA_VERSION,
111
- target: resolveCompactionTarget(store.target, `Odai compaction model configuration ${configPath}.target`),
112
- });
113
- } catch (error) {
114
- if (error instanceof CompactionModelStoreValidationError) throw error;
115
- throw new CompactionModelStoreValidationError(
116
- `Odai compaction model configuration ${configPath} failed validation: ${error instanceof Error ? error.message : String(error)}`,
117
- { cause: error },
118
- );
119
- }
120
- }
121
-
122
- export function effectiveCompactionTarget(configPath) {
123
- const stored = readCompactionModelStore(configPath);
124
- return Object.freeze({
125
- ...(stored.target === undefined ? {} : { target: stored.target }),
126
- source: stored.target === undefined ? "inherit" : "persisted",
127
- });
128
- }
129
-
130
- export function applyCompactionTarget(options, target, sessions) {
131
- if (options?.purpose !== "compaction" || target === undefined) return false;
132
- const currentRoute = options.sessionId === undefined
133
- ? undefined
134
- : sessions?.get?.(options.sessionId)?.requestHeader?.()?.config;
135
- const durableRouteKnown = typeof currentRoute?.provider === "string"
136
- && currentRoute.provider.length > 0
137
- && typeof currentRoute.model === "string"
138
- && currentRoute.model.length > 0;
139
- const targetChangesDurableRoute = durableRouteKnown
140
- && (currentRoute.provider !== target.provider || currentRoute.model !== target.model);
141
- const inheritedReasoning = targetChangesDurableRoute
142
- && typeof currentRoute.reasoningEffort === "string"
143
- && currentRoute.reasoningEffort.length > 0
144
- && options.reasoningEffort === currentRoute.reasoningEffort;
145
- const changesRoute = options.provider !== target.provider || options.model !== target.model;
146
- const changesReasoning = target.reasoningEffort !== undefined
147
- && options.reasoningEffort !== target.reasoningEffort;
148
- if (!changesRoute && !inheritedReasoning && !changesReasoning) return false;
149
- if (!Object.isExtensible(options)) {
150
- throw new Error("configured Odai compaction model cannot be applied to an immutable request");
151
- }
152
-
153
- if (target.reasoningEffort !== undefined) options.reasoningEffort = target.reasoningEffort;
154
- else if (inheritedReasoning) delete options.reasoningEffort;
155
- if (changesRoute) {
156
- options.provider = target.provider;
157
- options.model = target.model;
158
- }
159
- return true;
160
- }
161
-
162
- export function applyCompactionStateProtocol(options, target) {
163
- if (options?.purpose !== "compaction" || target === undefined) return false;
164
- if (!Array.isArray(options.messages) || !Object.isExtensible(options)) {
165
- throw new Error("configured Odai compaction model requires a mutable message envelope for checkpoint integrity");
166
- }
167
- const alreadyApplied = options.messages.some((message) => (
168
- message?.source?.kind === STATE_PROTOCOL_SOURCE.kind
169
- && message.source.plugin === STATE_PROTOCOL_SOURCE.plugin
170
- && message.source.form === STATE_PROTOCOL_SOURCE.form
171
- && Array.isArray(message.content)
172
- && message.content.some((block) => block?.type === "text" && block.text === COMPACTION_STATE_PROTOCOL)
173
- ));
174
- if (alreadyApplied) return false;
175
- options.messages = [...options.messages, {
176
- id: randomUUID(),
177
- role: "user",
178
- content: [{ type: "text", text: COMPACTION_STATE_PROTOCOL }],
179
- source: STATE_PROTOCOL_SOURCE,
180
- }];
181
- return true;
182
- }
183
-
184
- function writeCompactionModelStore(configPath, target) {
185
- mkdirSync(dirname(configPath), { recursive: true, mode: 0o700 });
186
- const temporary = `${configPath}.tmp-${process.pid}-${randomUUID()}`;
187
- const value = `${JSON.stringify({ schemaVersion: STORE_SCHEMA_VERSION, target }, null, 2)}\n`;
188
- try {
189
- writeFileSync(temporary, value, { encoding: "utf8", mode: 0o600, flag: "wx" });
190
- renameSync(temporary, configPath);
191
- } finally {
192
- rmSync(temporary, { force: true });
193
- }
194
- }
195
-
196
- function preserveInvalidStore(configPath) {
197
- try {
198
- renameSync(configPath, `${configPath}.invalid-${Date.now()}-${randomUUID()}`);
199
- return true;
200
- } catch (error) {
201
- if (error?.code === "ENOENT") return false;
202
- throw error;
203
- }
204
- }
205
-
206
- export function invalidatePersistedCompactionTarget(configPath, expectedTarget) {
207
- const releaseLock = acquireOwnedStoreLock(configPath, "Odai compaction model configuration");
208
- try {
209
- const current = readCompactionModelStore(configPath);
210
- if (!sameModelRoute(current.target, expectedTarget)) {
211
- return Object.freeze({ invalidated: false, reason: "target-changed-or-not-persisted" });
212
- }
213
- const backupPath = `${configPath}.invalidated-${Date.now()}-${randomUUID()}`;
214
- copyFileSync(configPath, backupPath);
215
- rmSync(configPath, { force: true });
216
- return Object.freeze({ invalidated: true, backupPath, target: current.target });
217
- } finally {
218
- releaseLock();
219
- }
220
- }
221
-
222
- function resultFor(configPath, action, selection, recoveredInvalidStore = false) {
223
- return {
224
- action,
225
- configPath,
226
- source: selection.source,
227
- ...(selection.target === undefined ? {} : { target: selection.target }),
228
- requiresNextCompaction: action !== "show",
229
- ...(selection.invalidStore ? { invalidStore: true } : {}),
230
- ...(recoveredInvalidStore ? { recoveredInvalidStore: true } : {}),
231
- };
232
- }
233
-
234
- export function createCompactionConfigTool(configPath, options = {}) {
235
- const onConfigured = typeof options.onConfigured === "function" ? options.onConfigured : () => {};
236
- const resolveCallConfig = typeof options.resolveCallConfig === "function" ? options.resolveCallConfig : undefined;
237
- const isChild = typeof options.isChild === "function"
238
- ? options.isChild
239
- : (agent) => {
240
- const header = agent?.session?.header;
241
- return header?.origin === "subagent"
242
- || (Number.isSafeInteger(header?.delegationDepth) && header.delegationDepth > 0);
243
- };
244
- return {
245
- name: "odai_compaction_config",
246
- description: [
247
- "Inspect, set, or remove the shared Odai compaction-summary target.",
248
- "Use only when the user naturally asks about the compaction model/reasoning effort or explicitly supplies the provider and model to set. Never select a provider, model, or reasoning effort on the user's behalf.",
249
- "The default is inherit. A persisted target changes only future compaction-summary requests; controller and responsibility routes, output budget, and cache retention stay unchanged. An optional user-specified reasoning effort applies only to those summaries.",
250
- "Persisted targets also receive a provider-neutral integrity protocol that keeps current facts above superseded history and preserves continuation-critical opaque values exactly.",
251
- "An invalid store is reported while runtime requests safely inherit. If the configured route or summary fails, DSH preserves the original history. Changes apply from the next compaction request.",
252
- ].join(" "),
253
- parameters: {
254
- type: "object",
255
- additionalProperties: false,
256
- required: ["action"],
257
- properties: {
258
- action: {
259
- type: "string",
260
- enum: ["show", "set", "remove"],
261
- description: "Show the effective target, set a user-specified provider/model and optional reasoning effort, or remove it to restore inheritance.",
262
- },
263
- provider: {
264
- type: "string",
265
- description: "Provider id explicitly supplied by the user; required for set.",
266
- },
267
- model: {
268
- type: "string",
269
- description: "Model id explicitly supplied by the user; required for set.",
270
- },
271
- reasoningEffort: {
272
- type: "string",
273
- description: "Optional compaction reasoning effort explicitly supplied by the user.",
274
- },
275
- },
276
- },
277
- output: {
278
- schema: {
279
- type: "object",
280
- additionalProperties: false,
281
- required: ["action", "configPath", "source", "requiresNextCompaction"],
282
- properties: {
283
- action: { type: "string", enum: ["show", "set", "remove"] },
284
- configPath: { type: "string" },
285
- source: { type: "string", enum: ["inherit", "persisted"] },
286
- target: {
287
- type: "object",
288
- additionalProperties: false,
289
- required: ["provider", "model"],
290
- properties: {
291
- provider: { type: "string" },
292
- model: { type: "string" },
293
- reasoningEffort: { type: "string" },
294
- },
295
- },
296
- requiresNextCompaction: { type: "boolean" },
297
- invalidStore: { type: "boolean" },
298
- recoveredInvalidStore: { type: "boolean" },
299
- },
300
- },
301
- render(_args, value) {
302
- const target = value.target
303
- ? `${value.target.provider}/${value.target.model} (reasoning: ${value.target.reasoningEffort ?? "not configured"})`
304
- : "inherit the current conversation model and reasoning";
305
- return [{
306
- type: "text",
307
- text: [
308
- `${value.action === "show" ? "Current" : "Updated"} Odai compaction target (${value.source}): ${target}.`,
309
- " This affects compaction summaries only; other model routes, the summary budget, and cache retention are unchanged.",
310
- ...(value.invalidStore ? [" The persisted store is invalid, so runtime requests currently inherit; set or remove the target to repair it."] : []),
311
- ...(value.recoveredInvalidStore ? [" An invalid prior store was preserved before the configuration was repaired or reset."] : []),
312
- ...(value.requiresNextCompaction ? [" The change applies from the next compaction request."] : []),
313
- ].join(""),
314
- }];
315
- },
316
- },
317
- execute(args, execution) {
318
- if (!execution.agent) throw new Error("odai_compaction_config requires an owning agent session");
319
- if (isChild(execution.agent)) throw new Error("child agents may not change Odai compaction model configuration");
320
- if (!args || typeof args !== "object" || Array.isArray(args)) throw new TypeError("arguments must be an object");
321
- const unknown = Object.keys(args).filter((field) => !["action", "provider", "model", "reasoningEffort"].includes(field));
322
- if (unknown.length > 0) throw new TypeError(`unknown arguments: ${unknown.join(", ")}`);
323
- if (!["show", "set", "remove"].includes(args.action)) throw new TypeError("action must be show, set, or remove");
324
- if (args.action === "show") {
325
- if (args.provider !== undefined || args.model !== undefined || args.reasoningEffort !== undefined) {
326
- throw new TypeError("provider, model, and reasoningEffort must be omitted for show");
327
- }
328
- let selection;
329
- try {
330
- selection = effectiveCompactionTarget(configPath);
331
- } catch (error) {
332
- if (!(error instanceof CompactionModelStoreValidationError)) throw error;
333
- selection = Object.freeze({ source: "inherit", invalidStore: true });
334
- }
335
- return Promise.resolve(resultFor(configPath, "show", selection));
336
- }
337
- if (args.action === "remove"
338
- && (args.provider !== undefined || args.model !== undefined || args.reasoningEffort !== undefined)) {
339
- throw new TypeError("provider, model, and reasoningEffort must be omitted for remove");
340
- }
341
- const proposed = args.action === "set"
342
- ? resolveCompactionTarget({
343
- provider: args.provider,
344
- model: args.model,
345
- ...(args.reasoningEffort === undefined ? {} : { reasoningEffort: args.reasoningEffort }),
346
- })
347
- : undefined;
348
-
349
- const commit = (validationStatus) => {
350
- const releaseLock = acquireOwnedStoreLock(configPath, "Odai compaction model configuration");
351
- try {
352
- let recoveredInvalidStore = false;
353
- try {
354
- readCompactionModelStore(configPath);
355
- } catch (error) {
356
- if (!(error instanceof CompactionModelStoreValidationError)) {
357
- throw new Error("Odai compaction model configuration could not be read safely; no changes were made", { cause: error });
358
- }
359
- recoveredInvalidStore = preserveInvalidStore(configPath);
360
- }
361
- if (args.action === "set") writeCompactionModelStore(configPath, proposed);
362
- else rmSync(configPath, { force: true });
363
- const selection = args.action === "set"
364
- ? Object.freeze({ target: proposed, source: "persisted" })
365
- : Object.freeze({ source: "inherit" });
366
- onConfigured(execution.agent, {
367
- action: args.action,
368
- ...(selection.target === undefined ? {} : { target: selection.target }),
369
- ...(validationStatus === "verified" ? { validationStatus } : {}),
370
- ...(recoveredInvalidStore ? { recoveredInvalidStore: true } : {}),
371
- });
372
- return resultFor(configPath, args.action, selection, recoveredInvalidStore);
373
- } finally {
374
- releaseLock();
375
- }
376
- };
377
- if (args.action === "set") {
378
- return requireModelRoute(
379
- resolveCallConfig,
380
- proposed,
381
- execution.signal,
382
- "compaction model route",
383
- ).then((validation) => commit(validation.status));
384
- }
385
- return Promise.resolve(commit());
386
- },
387
- };
388
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ copyFileSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { dirname, resolve } from "node:path";
12
+
13
+ import { requireModelRoute, sameModelRoute } from "./model-route.mjs";
14
+ import { acquireOwnedStoreLock } from "./store-lock.mjs";
15
+
16
+ const STORE_SCHEMA_VERSION = 1;
17
+ const TARGET_FIELDS = new Set(["provider", "model", "reasoningEffort"]);
18
+ const STATE_PROTOCOL_SOURCE = Object.freeze({
19
+ kind: "plugin",
20
+ plugin: "odai-dsh-runtime",
21
+ form: "instructions",
22
+ });
23
+
24
+ export const COMPACTION_STATE_PROTOCOL = [
25
+ "Additional checkpoint integrity protocol:",
26
+ "- Treat facts explicitly marked CURRENT, corrected, or authoritative as the active state.",
27
+ "- Facts marked SUPERSEDED, REJECTED, obsolete, or historical may be retained only as rejected history; never describe them as current, latest, selected, or pending.",
28
+ "- Preserve opaque identifiers, paths, commands, status values, delimiters, and numeric values byte-for-byte when they determine continuation state.",
29
+ "- Before emitting the checkpoint, self-check that no rejected fact is framed as active and that no active value conflicts with another section.",
30
+ ].join("\n");
31
+
32
+ export const COMPACTION_CONFIG_PROMPT = [
33
+ "## Odai compaction model configuration",
34
+ "When the user naturally asks to inspect, set, change, or reset the model or reasoning effort used to summarize compacted context, use odai_compaction_config.",
35
+ "Set a compaction target only when the user explicitly supplies both provider and model. Pass reasoningEffort only when the user explicitly supplies it. Never infer or silently choose any value. If the user changes only the effort for an existing persisted target, inspect and preserve that exact provider/model pair.",
36
+ "The default is inherit: compaction uses the current conversation route. A configured target changes only compaction-summary requests; it does not change the controller, researcher, planner, executor, reviewer, frontend, normal conversation, summary output budget, or cache-retention policy. An optional explicit reasoning effort is likewise scoped only to compaction summaries; omitting it preserves the existing reasoning inheritance and cross-model isolation behavior.",
37
+ "Configured targets also receive a provider-neutral checkpoint integrity protocol that keeps current facts above superseded or rejected history and preserves continuation-critical opaque values exactly.",
38
+ "Do not ask the user to edit YAML, JSON, managed Agent files, or Plugin configuration. The tool owns persistence. Set/remove changes apply to the next compaction request.",
39
+ "An invalid persisted store is visible through the tool while runtime requests safely inherit the conversation route. If the configured route fails or produces an incomplete summary, DSH must preserve the original history rather than landing a partial checkpoint.",
40
+ ].join("\n");
41
+
42
+ export class CompactionModelStoreValidationError extends Error {}
43
+
44
+ function assertPlainObject(value, field) {
45
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
46
+ throw new TypeError(`${field} must be an object`);
47
+ }
48
+ return value;
49
+ }
50
+
51
+ export function resolveCompactionTarget(value, field = "Odai compaction model target") {
52
+ const target = assertPlainObject(value, field);
53
+ const unknown = Object.keys(target).filter((name) => !TARGET_FIELDS.has(name));
54
+ if (unknown.length > 0) throw new TypeError(`${field} has unknown fields: ${unknown.join(", ")}`);
55
+ if (typeof target.provider !== "string" || target.provider.trim() === "") {
56
+ throw new TypeError(`${field}.provider must be a non-empty string`);
57
+ }
58
+ if (typeof target.model !== "string" || target.model.trim() === "") {
59
+ throw new TypeError(`${field}.model must be a non-empty string`);
60
+ }
61
+ if (target.reasoningEffort !== undefined
62
+ && (typeof target.reasoningEffort !== "string" || target.reasoningEffort.trim() === "")) {
63
+ throw new TypeError(`${field}.reasoningEffort must be a non-empty string`);
64
+ }
65
+ return Object.freeze({
66
+ provider: target.provider.trim(),
67
+ model: target.model.trim(),
68
+ ...(target.reasoningEffort === undefined ? {} : { reasoningEffort: target.reasoningEffort.trim() }),
69
+ });
70
+ }
71
+
72
+ export function resolveCompactionConfigPath(configuredPath, env = process.env) {
73
+ if (configuredPath !== undefined) {
74
+ if (typeof configuredPath !== "string" || configuredPath.trim() === "") {
75
+ throw new TypeError("config.compaction.configPath must be a non-empty string");
76
+ }
77
+ return resolve(configuredPath.trim());
78
+ }
79
+ const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== ""
80
+ ? resolve(env.DSH_HOME.trim())
81
+ : resolve(homedir(), ".dsh");
82
+ return resolve(dshHome, "odai", "compaction.json");
83
+ }
84
+
85
+ export function readCompactionModelStore(configPath) {
86
+ let text;
87
+ try {
88
+ text = readFileSync(configPath, "utf8");
89
+ } catch (error) {
90
+ if (error?.code === "ENOENT") return Object.freeze({ schemaVersion: STORE_SCHEMA_VERSION });
91
+ throw new Error(`cannot read Odai compaction model configuration ${configPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
92
+ }
93
+ let parsed;
94
+ try {
95
+ parsed = JSON.parse(text);
96
+ } catch (error) {
97
+ throw new CompactionModelStoreValidationError(`Odai compaction model configuration ${configPath} is not valid JSON`, { cause: error });
98
+ }
99
+ try {
100
+ const store = assertPlainObject(parsed, `Odai compaction model configuration ${configPath}`);
101
+ const unknown = Object.keys(store).filter((field) => !["schemaVersion", "target"].includes(field));
102
+ if (unknown.length > 0) {
103
+ throw new TypeError(`Odai compaction model configuration ${configPath} has unknown fields: ${unknown.join(", ")}`);
104
+ }
105
+ if (store.schemaVersion !== STORE_SCHEMA_VERSION) {
106
+ throw new TypeError(`Odai compaction model configuration ${configPath} has unsupported schemaVersion ${String(store.schemaVersion)}`);
107
+ }
108
+ if (store.target === undefined) return Object.freeze({ schemaVersion: STORE_SCHEMA_VERSION });
109
+ return Object.freeze({
110
+ schemaVersion: STORE_SCHEMA_VERSION,
111
+ target: resolveCompactionTarget(store.target, `Odai compaction model configuration ${configPath}.target`),
112
+ });
113
+ } catch (error) {
114
+ if (error instanceof CompactionModelStoreValidationError) throw error;
115
+ throw new CompactionModelStoreValidationError(
116
+ `Odai compaction model configuration ${configPath} failed validation: ${error instanceof Error ? error.message : String(error)}`,
117
+ { cause: error },
118
+ );
119
+ }
120
+ }
121
+
122
+ export function effectiveCompactionTarget(configPath) {
123
+ const stored = readCompactionModelStore(configPath);
124
+ return Object.freeze({
125
+ ...(stored.target === undefined ? {} : { target: stored.target }),
126
+ source: stored.target === undefined ? "inherit" : "persisted",
127
+ });
128
+ }
129
+
130
+ export function applyCompactionTarget(options, target, sessions) {
131
+ if (options?.purpose !== "compaction" || target === undefined) return false;
132
+ const currentRoute = options.sessionId === undefined
133
+ ? undefined
134
+ : sessions?.get?.(options.sessionId)?.requestHeader?.()?.config;
135
+ const durableRouteKnown = typeof currentRoute?.provider === "string"
136
+ && currentRoute.provider.length > 0
137
+ && typeof currentRoute.model === "string"
138
+ && currentRoute.model.length > 0;
139
+ const targetChangesDurableRoute = durableRouteKnown
140
+ && (currentRoute.provider !== target.provider || currentRoute.model !== target.model);
141
+ const inheritedReasoning = targetChangesDurableRoute
142
+ && typeof currentRoute.reasoningEffort === "string"
143
+ && currentRoute.reasoningEffort.length > 0
144
+ && options.reasoningEffort === currentRoute.reasoningEffort;
145
+ const changesRoute = options.provider !== target.provider || options.model !== target.model;
146
+ const changesReasoning = target.reasoningEffort !== undefined
147
+ && options.reasoningEffort !== target.reasoningEffort;
148
+ if (!changesRoute && !inheritedReasoning && !changesReasoning) return false;
149
+ if (!Object.isExtensible(options)) {
150
+ throw new Error("configured Odai compaction model cannot be applied to an immutable request");
151
+ }
152
+
153
+ if (target.reasoningEffort !== undefined) options.reasoningEffort = target.reasoningEffort;
154
+ else if (inheritedReasoning) delete options.reasoningEffort;
155
+ if (changesRoute) {
156
+ options.provider = target.provider;
157
+ options.model = target.model;
158
+ }
159
+ return true;
160
+ }
161
+
162
+ export function applyCompactionStateProtocol(options, target) {
163
+ if (options?.purpose !== "compaction" || target === undefined) return false;
164
+ if (!Array.isArray(options.messages) || !Object.isExtensible(options)) {
165
+ throw new Error("configured Odai compaction model requires a mutable message envelope for checkpoint integrity");
166
+ }
167
+ const alreadyApplied = options.messages.some((message) => (
168
+ message?.source?.kind === STATE_PROTOCOL_SOURCE.kind
169
+ && message.source.plugin === STATE_PROTOCOL_SOURCE.plugin
170
+ && message.source.form === STATE_PROTOCOL_SOURCE.form
171
+ && Array.isArray(message.content)
172
+ && message.content.some((block) => block?.type === "text" && block.text === COMPACTION_STATE_PROTOCOL)
173
+ ));
174
+ if (alreadyApplied) return false;
175
+ options.messages = [...options.messages, {
176
+ id: randomUUID(),
177
+ role: "user",
178
+ content: [{ type: "text", text: COMPACTION_STATE_PROTOCOL }],
179
+ source: STATE_PROTOCOL_SOURCE,
180
+ }];
181
+ return true;
182
+ }
183
+
184
+ function writeCompactionModelStore(configPath, target) {
185
+ mkdirSync(dirname(configPath), { recursive: true, mode: 0o700 });
186
+ const temporary = `${configPath}.tmp-${process.pid}-${randomUUID()}`;
187
+ const value = `${JSON.stringify({ schemaVersion: STORE_SCHEMA_VERSION, target }, null, 2)}\n`;
188
+ try {
189
+ writeFileSync(temporary, value, { encoding: "utf8", mode: 0o600, flag: "wx" });
190
+ renameSync(temporary, configPath);
191
+ } finally {
192
+ rmSync(temporary, { force: true });
193
+ }
194
+ }
195
+
196
+ function preserveInvalidStore(configPath) {
197
+ try {
198
+ renameSync(configPath, `${configPath}.invalid-${Date.now()}-${randomUUID()}`);
199
+ return true;
200
+ } catch (error) {
201
+ if (error?.code === "ENOENT") return false;
202
+ throw error;
203
+ }
204
+ }
205
+
206
+ export function invalidatePersistedCompactionTarget(configPath, expectedTarget) {
207
+ const releaseLock = acquireOwnedStoreLock(configPath, "Odai compaction model configuration");
208
+ try {
209
+ const current = readCompactionModelStore(configPath);
210
+ if (!sameModelRoute(current.target, expectedTarget)) {
211
+ return Object.freeze({ invalidated: false, reason: "target-changed-or-not-persisted" });
212
+ }
213
+ const backupPath = `${configPath}.invalidated-${Date.now()}-${randomUUID()}`;
214
+ copyFileSync(configPath, backupPath);
215
+ rmSync(configPath, { force: true });
216
+ return Object.freeze({ invalidated: true, backupPath, target: current.target });
217
+ } finally {
218
+ releaseLock();
219
+ }
220
+ }
221
+
222
+ function resultFor(configPath, action, selection, recoveredInvalidStore = false) {
223
+ return {
224
+ action,
225
+ configPath,
226
+ source: selection.source,
227
+ ...(selection.target === undefined ? {} : { target: selection.target }),
228
+ requiresNextCompaction: action !== "show",
229
+ ...(selection.invalidStore ? { invalidStore: true } : {}),
230
+ ...(recoveredInvalidStore ? { recoveredInvalidStore: true } : {}),
231
+ };
232
+ }
233
+
234
+ export function createCompactionConfigTool(configPath, options = {}) {
235
+ const onConfigured = typeof options.onConfigured === "function" ? options.onConfigured : () => {};
236
+ const resolveCallConfig = typeof options.resolveCallConfig === "function" ? options.resolveCallConfig : undefined;
237
+ const isChild = typeof options.isChild === "function"
238
+ ? options.isChild
239
+ : (agent) => {
240
+ const header = agent?.session?.header;
241
+ return header?.origin === "subagent"
242
+ || (Number.isSafeInteger(header?.delegationDepth) && header.delegationDepth > 0);
243
+ };
244
+ return {
245
+ name: "odai_compaction_config",
246
+ description: [
247
+ "Inspect, set, or remove the shared Odai compaction-summary target.",
248
+ "Use only when the user naturally asks about the compaction model/reasoning effort or explicitly supplies the provider and model to set. Never select a provider, model, or reasoning effort on the user's behalf.",
249
+ "The default is inherit. A persisted target changes only future compaction-summary requests; controller and responsibility routes, output budget, and cache retention stay unchanged. An optional user-specified reasoning effort applies only to those summaries.",
250
+ "Persisted targets also receive a provider-neutral integrity protocol that keeps current facts above superseded history and preserves continuation-critical opaque values exactly.",
251
+ "An invalid store is reported while runtime requests safely inherit. If the configured route or summary fails, DSH preserves the original history. Changes apply from the next compaction request.",
252
+ ].join(" "),
253
+ parameters: {
254
+ type: "object",
255
+ additionalProperties: false,
256
+ required: ["action"],
257
+ properties: {
258
+ action: {
259
+ type: "string",
260
+ enum: ["show", "set", "remove"],
261
+ description: "Show the effective target, set a user-specified provider/model and optional reasoning effort, or remove it to restore inheritance.",
262
+ },
263
+ provider: {
264
+ type: "string",
265
+ description: "Provider id explicitly supplied by the user; required for set.",
266
+ },
267
+ model: {
268
+ type: "string",
269
+ description: "Model id explicitly supplied by the user; required for set.",
270
+ },
271
+ reasoningEffort: {
272
+ type: "string",
273
+ description: "Optional compaction reasoning effort explicitly supplied by the user.",
274
+ },
275
+ },
276
+ },
277
+ output: {
278
+ schema: {
279
+ type: "object",
280
+ additionalProperties: false,
281
+ required: ["action", "configPath", "source", "requiresNextCompaction"],
282
+ properties: {
283
+ action: { type: "string", enum: ["show", "set", "remove"] },
284
+ configPath: { type: "string" },
285
+ source: { type: "string", enum: ["inherit", "persisted"] },
286
+ target: {
287
+ type: "object",
288
+ additionalProperties: false,
289
+ required: ["provider", "model"],
290
+ properties: {
291
+ provider: { type: "string" },
292
+ model: { type: "string" },
293
+ reasoningEffort: { type: "string" },
294
+ },
295
+ },
296
+ requiresNextCompaction: { type: "boolean" },
297
+ invalidStore: { type: "boolean" },
298
+ recoveredInvalidStore: { type: "boolean" },
299
+ },
300
+ },
301
+ render(_args, value) {
302
+ const target = value.target
303
+ ? `${value.target.provider}/${value.target.model} (reasoning: ${value.target.reasoningEffort ?? "not configured"})`
304
+ : "inherit the current conversation model and reasoning";
305
+ return [{
306
+ type: "text",
307
+ text: [
308
+ `${value.action === "show" ? "Current" : "Updated"} Odai compaction target (${value.source}): ${target}.`,
309
+ " This affects compaction summaries only; other model routes, the summary budget, and cache retention are unchanged.",
310
+ ...(value.invalidStore ? [" The persisted store is invalid, so runtime requests currently inherit; set or remove the target to repair it."] : []),
311
+ ...(value.recoveredInvalidStore ? [" An invalid prior store was preserved before the configuration was repaired or reset."] : []),
312
+ ...(value.requiresNextCompaction ? [" The change applies from the next compaction request."] : []),
313
+ ].join(""),
314
+ }];
315
+ },
316
+ },
317
+ execute(args, execution) {
318
+ if (!execution.agent) throw new Error("odai_compaction_config requires an owning agent session");
319
+ if (isChild(execution.agent)) throw new Error("child agents may not change Odai compaction model configuration");
320
+ if (!args || typeof args !== "object" || Array.isArray(args)) throw new TypeError("arguments must be an object");
321
+ const unknown = Object.keys(args).filter((field) => !["action", "provider", "model", "reasoningEffort"].includes(field));
322
+ if (unknown.length > 0) throw new TypeError(`unknown arguments: ${unknown.join(", ")}`);
323
+ if (!["show", "set", "remove"].includes(args.action)) throw new TypeError("action must be show, set, or remove");
324
+ if (args.action === "show") {
325
+ if (args.provider !== undefined || args.model !== undefined || args.reasoningEffort !== undefined) {
326
+ throw new TypeError("provider, model, and reasoningEffort must be omitted for show");
327
+ }
328
+ let selection;
329
+ try {
330
+ selection = effectiveCompactionTarget(configPath);
331
+ } catch (error) {
332
+ if (!(error instanceof CompactionModelStoreValidationError)) throw error;
333
+ selection = Object.freeze({ source: "inherit", invalidStore: true });
334
+ }
335
+ return Promise.resolve(resultFor(configPath, "show", selection));
336
+ }
337
+ if (args.action === "remove"
338
+ && (args.provider !== undefined || args.model !== undefined || args.reasoningEffort !== undefined)) {
339
+ throw new TypeError("provider, model, and reasoningEffort must be omitted for remove");
340
+ }
341
+ const proposed = args.action === "set"
342
+ ? resolveCompactionTarget({
343
+ provider: args.provider,
344
+ model: args.model,
345
+ ...(args.reasoningEffort === undefined ? {} : { reasoningEffort: args.reasoningEffort }),
346
+ })
347
+ : undefined;
348
+
349
+ const commit = (validationStatus) => {
350
+ const releaseLock = acquireOwnedStoreLock(configPath, "Odai compaction model configuration");
351
+ try {
352
+ let recoveredInvalidStore = false;
353
+ try {
354
+ readCompactionModelStore(configPath);
355
+ } catch (error) {
356
+ if (!(error instanceof CompactionModelStoreValidationError)) {
357
+ throw new Error("Odai compaction model configuration could not be read safely; no changes were made", { cause: error });
358
+ }
359
+ recoveredInvalidStore = preserveInvalidStore(configPath);
360
+ }
361
+ if (args.action === "set") writeCompactionModelStore(configPath, proposed);
362
+ else rmSync(configPath, { force: true });
363
+ const selection = args.action === "set"
364
+ ? Object.freeze({ target: proposed, source: "persisted" })
365
+ : Object.freeze({ source: "inherit" });
366
+ onConfigured(execution.agent, {
367
+ action: args.action,
368
+ ...(selection.target === undefined ? {} : { target: selection.target }),
369
+ ...(validationStatus === "verified" ? { validationStatus } : {}),
370
+ ...(recoveredInvalidStore ? { recoveredInvalidStore: true } : {}),
371
+ });
372
+ return resultFor(configPath, args.action, selection, recoveredInvalidStore);
373
+ } finally {
374
+ releaseLock();
375
+ }
376
+ };
377
+ if (args.action === "set") {
378
+ return requireModelRoute(
379
+ resolveCallConfig,
380
+ proposed,
381
+ execution.signal,
382
+ "compaction model route",
383
+ ).then((validation) => commit(validation.status));
384
+ }
385
+ return Promise.resolve(commit());
386
+ },
387
+ };
388
+ }