@dsmm/dsmm 0.3.15 → 0.3.17

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 (55) hide show
  1. package/README.md +13 -5
  2. package/docs/agent-presets.md +1 -1
  3. package/docs/compatibility.md +5 -5
  4. package/docs/deferred-native-approval-risk.md +1 -1
  5. package/docs/design.md +1 -1
  6. package/docs/lsp.md +1 -1
  7. package/docs/maintenance.md +2 -1
  8. package/docs/model-routing.md +13 -6
  9. package/docs/native-permissions.md +1 -1
  10. package/docs/profiles.md +3 -1
  11. package/docs/releasing.md +2 -2
  12. package/docs/roadmap.md +3 -3
  13. package/docs/runtime-recovery.md +4 -4
  14. package/docs/safety-guards.md +1 -1
  15. package/docs/settings-status.md +4 -2
  16. package/docs/tui.md +53 -0
  17. package/dsh-plugin.json +41 -0
  18. package/lib/client/ProfilesSection.js +1 -1
  19. package/lib/client/SessionProfiles.js +8 -7
  20. package/lib/client/children-locales.d.ts +1 -1
  21. package/lib/client/controller.d.ts +13 -1
  22. package/lib/client/controller.js +114 -20
  23. package/lib/client/deployment-locales.js +3 -2
  24. package/lib/client/deployment-modules.js +1 -1
  25. package/lib/client/index.js +22 -4
  26. package/lib/client/locales.d.ts +1 -0
  27. package/lib/client/locales.js +2 -0
  28. package/lib/client.js +144 -29
  29. package/lib/commands.d.ts +7 -3
  30. package/lib/commands.js +20 -11
  31. package/lib/host-llm.js +6 -1
  32. package/lib/index.d.ts +1 -1
  33. package/lib/index.js +2 -6
  34. package/lib/model-routing.js +43 -19
  35. package/lib/profile-diagnostics.js +1 -0
  36. package/lib/profile-runtime.js +1 -1
  37. package/lib/request-routing.d.ts +27 -0
  38. package/lib/request-routing.js +69 -0
  39. package/lib/role-llm-runtime.js +15 -2
  40. package/lib/role-routing.d.ts +4 -3
  41. package/lib/role-routing.js +17 -10
  42. package/lib/runtime-recovery.js +56 -16
  43. package/lib/settings.d.ts +3 -0
  44. package/lib/settings.js +9 -0
  45. package/lib/state.d.ts +2 -2
  46. package/lib/state.js +13 -4
  47. package/lib/status.d.ts +5 -0
  48. package/lib/status.js +18 -7
  49. package/lib/tui-actions.d.ts +21 -0
  50. package/lib/tui-actions.js +301 -0
  51. package/lib/tui-adapter.d.ts +25 -0
  52. package/lib/tui-adapter.js +422 -0
  53. package/lib/tui-types.d.ts +98 -0
  54. package/lib/tui-types.js +2 -0
  55. package/package.json +4 -2
package/lib/settings.d.ts CHANGED
@@ -29,6 +29,7 @@ export interface DsmmInvocationOptions {
29
29
  route?: DsmmLevelOverride;
30
30
  }
31
31
  export type DsmmToolTopology = "per-role" | "parameterized";
32
+ export type DsmmRootModelPolicy = "native" | "configured";
32
33
  export interface DsmmWorkflowSettings {
33
34
  policy: "risk-based" | "legacy";
34
35
  strictGates: boolean;
@@ -99,6 +100,7 @@ export interface DsmmPluginConfig {
99
100
  modelParameters?: {
100
101
  passthrough?: boolean;
101
102
  };
103
+ rootModelPolicy?: DsmmRootModelPolicy;
102
104
  locale?: DsmmLocale;
103
105
  /** Only global deployment input; native/legacy profile transport rejects it. */
104
106
  modules?: {
@@ -127,6 +129,7 @@ export interface DsmmSettings {
127
129
  modelParameters: {
128
130
  passthrough: boolean;
129
131
  };
132
+ rootModelPolicy: DsmmRootModelPolicy;
130
133
  locale?: DsmmLocale;
131
134
  modules: {
132
135
  deepwork: {
package/lib/settings.js CHANGED
@@ -14,6 +14,7 @@ export const DSMM_STATUS_COMMAND = "dsmm-status";
14
14
  export const DEFAULT_DSMM_SETTINGS = {
15
15
  permissionControl: DEFAULT_PERMISSION_CONTROL,
16
16
  modelParameters: { passthrough: true },
17
+ rootModelPolicy: "native",
17
18
  modules: { deepwork: { enabled: true } },
18
19
  modeName: "deepwork",
19
20
  defaultActive: false,
@@ -85,6 +86,7 @@ const MODEL_ROUTE_SCHEMA = Schema.transform(Schema.any(), (input) => normalizeMo
85
86
  const LEVEL_OVERRIDE_SCHEMA = Schema.union([MODEL_ROUTE_SCHEMA, Schema.object({ reasoningEffort: Schema.string().required() })]);
86
87
  const LEVELS_SCHEMA = Schema.object({ low: LEVEL_OVERRIDE_SCHEMA, high: LEVEL_OVERRIDE_SCHEMA, max: LEVEL_OVERRIDE_SCHEMA });
87
88
  const LOCALE_SCHEMA = Schema.union(DSMM_LOCALES.map(locale => Schema.const(locale)));
89
+ const ROOT_MODEL_POLICY_SCHEMA = Schema.union([Schema.const("native"), Schema.const("configured")]);
88
90
  const RATE_LIMIT_CONFIG_SCHEMA = Schema.object(Object.fromEntries(Object.keys(DEFAULT_DSMM_RUNTIME_POLICY.rateLimit).map((key) => [key, Schema.number()])));
89
91
  const ROUTING_STRATEGY_CONFIG_SCHEMA = Schema.union([Schema.const("startup-lock"), Schema.const("rate-limit-fallback")]);
90
92
  const RUNTIME_POLICY_CONFIG_SCHEMA = Schema.object({ strategy: ROUTING_STRATEGY_CONFIG_SCHEMA, rateLimit: RATE_LIMIT_CONFIG_SCHEMA });
@@ -106,6 +108,8 @@ const ROLE_ROUTING_VALIDATION_SCHEMA = Schema.transform(Schema.any(), (input) =>
106
108
  rejectDeprecatedFields(input);
107
109
  if (Object.hasOwn(input, "locale"))
108
110
  validateLocale(input.locale);
111
+ if (Object.hasOwn(input, "rootModelPolicy"))
112
+ validateShape(input.rootModelPolicy, ROOT_MODEL_POLICY_SCHEMA, ["rootModelPolicy"]);
109
113
  if (isRoutingRecord(input.guards) && Object.hasOwn(input.guards, "gitWriteScope"))
110
114
  validateShape(input.guards.gitWriteScope, GIT_WRITE_SCOPE_SCHEMA, ["guards", "gitWriteScope"]);
111
115
  if (isRoutingRecord(input.runtimeRecovery) && Array.isArray(input.runtimeRecovery.fallbackRoutes)) {
@@ -205,6 +209,7 @@ const LSP_SCHEMA = Schema.object({
205
209
  const CONFIG_FIELDS_SCHEMA = Schema.object({
206
210
  permissionControl: permissionControlSchema,
207
211
  modelParameters: Schema.object({ passthrough: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.modelParameters.passthrough) }),
212
+ rootModelPolicy: ROOT_MODEL_POLICY_SCHEMA.default(DEFAULT_DSMM_SETTINGS.rootModelPolicy),
208
213
  locale: LOCALE_SCHEMA,
209
214
  modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
210
215
  section: Schema.string(),
@@ -301,6 +306,7 @@ export function validateNativeConfig(input) {
301
306
  export const DSMM_SETTINGS_SCHEMA = Schema.intersect([ROLE_ROUTING_VALIDATION_SCHEMA, Schema.object({
302
307
  permissionControl: permissionControlSchema,
303
308
  modelParameters: Schema.object({ passthrough: Schema.boolean().default(DEFAULT_DSMM_SETTINGS.modelParameters.passthrough) }),
309
+ rootModelPolicy: ROOT_MODEL_POLICY_SCHEMA.default(DEFAULT_DSMM_SETTINGS.rootModelPolicy),
304
310
  locale: LOCALE_SCHEMA,
305
311
  modules: Schema.object({ deepwork: Schema.object({ enabled: Schema.boolean().default(true) }) }),
306
312
  modeName: Schema.string().default(DEFAULT_DSMM_SETTINGS.modeName),
@@ -321,6 +327,8 @@ export function resolveConfig(config = {}) {
321
327
  rejectDeprecatedFields(config);
322
328
  if (Object.hasOwn(config, "locale"))
323
329
  validateLocale(config.locale);
330
+ if (Object.hasOwn(config, "rootModelPolicy"))
331
+ validateShape(config.rootModelPolicy, ROOT_MODEL_POLICY_SCHEMA, ["rootModelPolicy"]);
324
332
  if (config.subagents !== undefined)
325
333
  validateShape(config.subagents, SUBAGENTS_SCHEMA, ["subagents"]);
326
334
  if (config.modelParameters !== undefined)
@@ -330,6 +338,7 @@ export function resolveConfig(config = {}) {
330
338
  const settings = {
331
339
  permissionControl: resolvePermissionControl(config.permissionControl),
332
340
  modelParameters: { passthrough: config.modelParameters?.passthrough ?? DEFAULT_DSMM_SETTINGS.modelParameters.passthrough },
341
+ rootModelPolicy: config.rootModelPolicy ?? DEFAULT_DSMM_SETTINGS.rootModelPolicy,
333
342
  ...(config.locale === undefined ? {} : { locale: config.locale }),
334
343
  modules: { deepwork: { enabled: config.modules?.deepwork?.enabled ?? DEFAULT_DSMM_SETTINGS.modules.deepwork.enabled } },
335
344
  modeName: normalizeModeName(config.modeName),
package/lib/state.d.ts CHANGED
@@ -19,8 +19,8 @@ export declare class DeepworkModeController {
19
19
  private childDefaultActive;
20
20
  describe(agent: DshAgent, defaultActive: boolean): SessionDeepworkState;
21
21
  private intent;
22
- select(agent: DshAgent, active: boolean, defaultActive?: boolean): Promise<DeepworkSelectionOutcome>;
22
+ select(agent: DshAgent, active: boolean, defaultActive?: boolean, authority?: () => void, committed?: (revision: string) => void): Promise<DeepworkSelectionOutcome>;
23
23
  /** Called inside the existing native maintenance / admission CAS boundary. */
24
- selectIdle(agent: DshAgent, active: boolean, _defaultActive: boolean): Promise<void>;
24
+ selectIdle(agent: DshAgent, active: boolean, defaultActive: boolean, authority?: () => void, committed?: (revision: string) => void): Promise<void>;
25
25
  }
26
26
  //# sourceMappingURL=state.d.ts.map
package/lib/state.js CHANGED
@@ -101,7 +101,8 @@ export class DeepworkModeController {
101
101
  }
102
102
  return undefined;
103
103
  }
104
- async select(agent, active, defaultActive = false) {
104
+ async select(agent, active, defaultActive = false, authority, committed) {
105
+ authority?.();
105
106
  if (active && !this.runtimeReady())
106
107
  throw new Error("Deepwork runtime is not ready; enable it in native settings and restart the Host");
107
108
  if (active && !this.moduleEnabled(agent))
@@ -115,7 +116,8 @@ export class DeepworkModeController {
115
116
  signal?.throwIfAborted();
116
117
  if (this.describe(agent, defaultActive).revision !== before.revision)
117
118
  throw new Error("Deepwork mode changed; refresh before retrying");
118
- await this.selectIdle(agent, active, defaultActive);
119
+ authority?.();
120
+ await this.selectIdle(agent, active, defaultActive, authority, committed);
119
121
  };
120
122
  if (agent.runMaintenance === undefined)
121
123
  throw new Error("Deepwork mode requires native idle maintenance");
@@ -123,7 +125,7 @@ export class DeepworkModeController {
123
125
  return "committed";
124
126
  }
125
127
  /** Called inside the existing native maintenance / admission CAS boundary. */
126
- async selectIdle(agent, active, _defaultActive) {
128
+ async selectIdle(agent, active, defaultActive, authority, committed) {
127
129
  if (active && !this.runtimeReady())
128
130
  throw new Error("Deepwork runtime is not ready; enable it in native settings and restart the Host");
129
131
  if (active && !this.moduleEnabled(agent))
@@ -132,8 +134,15 @@ export class DeepworkModeController {
132
134
  throw new Error("Deepwork mode requires an idle session");
133
135
  if (this.intent(agent) === active)
134
136
  return;
137
+ authority?.();
135
138
  appendModeRecord(agent.session, active);
136
- this.changed(agent);
139
+ const revision = this.describe(agent, defaultActive).revision;
140
+ try {
141
+ committed?.(revision);
142
+ }
143
+ finally {
144
+ this.changed(agent);
145
+ }
137
146
  }
138
147
  }
139
148
  //# sourceMappingURL=state.js.map
package/lib/status.d.ts CHANGED
@@ -16,6 +16,11 @@ export interface DsmmStatusSnapshot {
16
16
  source: string;
17
17
  capture: string;
18
18
  };
19
+ rootModelPolicy?: {
20
+ value: DsmmSettings["rootModelPolicy"];
21
+ source: string;
22
+ capture: string;
23
+ };
19
24
  version: typeof DSMM_STATUS_VERSION;
20
25
  modules?: DsmmModuleState[];
21
26
  admission?: Pick<DsmmProfileAdmission, "profile" | "epoch" | "scope">;
package/lib/status.js CHANGED
@@ -20,12 +20,14 @@ export function createDsmmStatusSnapshot(input) {
20
20
  invalidDescriptor = true;
21
21
  }
22
22
  const inScope = modeActive || role !== undefined;
23
- const policy = ordinaryRoot || role === undefined ? undefined : settings.roleRouting[role];
23
+ const nativeRoot = ordinaryRoot && !(input.admission?.settings === settings
24
+ && settings.rootModelPolicy === "configured" && settings.modules.deepwork.enabled && role !== undefined && !invalidDescriptor);
25
+ const policy = nativeRoot || role === undefined ? undefined : settings.roleRouting[role];
24
26
  const runtimePolicy = resolveRoleRuntimePolicy(settings, role);
25
27
  const roleRuntimeState = input.roleRuntimeState ?? (input.admission === undefined || invalidDescriptor ? undefined
26
28
  : roleRouteRuntimeState(agent, settings, role, input.admission.epoch));
27
- const fallbacks = ordinaryRoot || invalidDescriptor ? [] : runtimePolicy.fallbackRoutes;
28
- const selectedRoute = resolveRoute(agent);
29
+ const fallbacks = nativeRoot || invalidDescriptor ? [] : runtimePolicy.fallbackRoutes;
30
+ const selectedRoute = resolveRoute(agent, !ordinaryRoot || nativeRoot);
29
31
  const family = classifyModelFamily({
30
32
  providerID: selectedRoute.provider,
31
33
  modelID: selectedRoute.model
@@ -36,6 +38,11 @@ export function createDsmmStatusSnapshot(input) {
36
38
  ...(input.admission?.warnings === undefined ? {} : { warnings: structuredClone(input.admission.warnings) }),
37
39
  ...(input.subagentRuntime === undefined && input.admission?.subagentRuntime === undefined ? {} : { subagentRuntime: { ...(input.subagentRuntime ?? input.admission.subagentRuntime) } }),
38
40
  ...(settings.locale === undefined ? {} : { locale: { value: settings.locale, source: input.admission?.sources?.locale ?? "defaults", capture: input.admission?.sourceCaptures?.fields.locale ?? "admission" } }),
41
+ ...(input.admission === undefined ? {} : { rootModelPolicy: {
42
+ value: input.admission.settings.rootModelPolicy,
43
+ source: input.admission.sources?.rootModelPolicy ?? "defaults",
44
+ capture: input.admission.sourceCaptures?.fields.rootModelPolicy ?? "admission"
45
+ } }),
39
46
  ...(input.modules === undefined ? {} : { modules: structuredClone(input.modules) }),
40
47
  ...(input.admission?.store === undefined ? {} : { profileStore: { ...input.admission.store } }),
41
48
  ...(input.admission?.deployment === undefined ? {} : { deployment: {
@@ -69,12 +76,12 @@ export function createDsmmStatusSnapshot(input) {
69
76
  applies: inScope && !invalidDescriptor,
70
77
  ...(policy?.primary === undefined ? {} : { primary: { ...policy.primary } }),
71
78
  fallbackRoutes: fallbacks.map((route) => ({ ...route })),
72
- fallbackSource: ordinaryRoot || invalidDescriptor ? "disabled" : runtimePolicy.fallbackSource,
73
- strategy: ordinaryRoot ? "startup-lock" : runtimePolicy.strategy,
79
+ fallbackSource: nativeRoot || invalidDescriptor ? "disabled" : runtimePolicy.fallbackSource,
80
+ strategy: nativeRoot ? "startup-lock" : runtimePolicy.strategy,
74
81
  rateLimit: { ...runtimePolicy.rateLimit },
75
82
  ...(roleRuntimeState === undefined ? {} : { runtimeState: {
76
83
  ...roleRuntimeState,
77
- ...(ordinaryRoot ? { strategy: "startup-lock" } : {}),
84
+ ...(nativeRoot ? { strategy: "startup-lock" } : {}),
78
85
  rateLimit: { ...roleRuntimeState.rateLimit },
79
86
  ...(roleRuntimeState.route === undefined ? {} : { route: { ...roleRuntimeState.route } })
80
87
  } }),
@@ -118,6 +125,7 @@ export function formatDsmmStatus(snapshot) {
118
125
  ...(snapshot.deployment?.sourceCaptures?.startup === undefined ? [] : [`Startup-pinned sources: global=${snapshot.deployment.sourceCaptures.startup.globalRevision}; native=${snapshot.deployment.sourceCaptures.startup.nativeRevision}`]),
119
126
  ...(snapshot.profileStore === undefined ? [] : [`Named store: ${snapshot.profileStore.origin}; ${snapshot.profileStore.readOnly ? "read-only" : "writable"}${snapshot.profileStore.writeRestriction === undefined ? "" : `; ${snapshot.profileStore.writeRestriction}`}`]),
120
127
  `Workflow policy: ${snapshot.effectiveSettings.workflow.policy}`,
128
+ ...(snapshot.rootModelPolicy === undefined ? [] : [`Root model policy: ${snapshot.rootModelPolicy.value} (${snapshot.rootModelPolicy.source}, ${snapshot.rootModelPolicy.capture})`]),
121
129
  `Route: ${provider}/${model} [${snapshot.route.family}]`,
122
130
  `Role policy: ${displayRole(snapshot.rolePolicy.role)}; strategy=${snapshot.rolePolicy.strategy}; primary=${snapshot.rolePolicy.primary === undefined ? "inherit" : `${snapshot.rolePolicy.primary.provider}/${snapshot.rolePolicy.primary.model}`}; fallbacks=${snapshot.rolePolicy.fallbackSource}; retries=${snapshot.rolePolicy.rateLimit.maxRetries}; threshold=${snapshot.rolePolicy.rateLimit.switchAfterRateLimits}; switches=${snapshot.rolePolicy.rateLimit.maxSwitches}`,
123
131
  ...(snapshot.rolePolicy.runtimeState === undefined ? [] : [`Retry state: retries=${snapshot.rolePolicy.runtimeState.retries}; rate limits=${snapshot.rolePolicy.runtimeState.rateLimitFailures}; switches=${snapshot.rolePolicy.runtimeState.switches}; delay ms=${snapshot.rolePolicy.runtimeState.totalDelayMs}`]),
@@ -127,7 +135,7 @@ export function formatDsmmStatus(snapshot) {
127
135
  "Effective settings: use /dsmm-status json for the normalized snapshot"
128
136
  ].join("\n");
129
137
  }
130
- function resolveRoute(agent) {
138
+ function resolveRoute(agent, includeBaseline) {
131
139
  const requestHeader = agent.session.requestHeader?.();
132
140
  if (requestHeader !== undefined) {
133
141
  const config = requestHeader?.config;
@@ -137,6 +145,8 @@ function resolveRoute(agent) {
137
145
  reasoningEffort: readString(config?.reasoningEffort)
138
146
  };
139
147
  }
148
+ if (!includeBaseline)
149
+ return {};
140
150
  return {
141
151
  provider: readString(agent.options?.provider),
142
152
  model: readString(agent.options?.model),
@@ -151,6 +161,7 @@ export function readOnlySettings(settings) {
151
161
  return {
152
162
  permissionControl: structuredClone(settings.permissionControl),
153
163
  modelParameters: { ...settings.modelParameters },
164
+ rootModelPolicy: settings.rootModelPolicy,
154
165
  modules: { deepwork: { enabled: settings.modules.deepwork.enabled } },
155
166
  ...(settings.locale === undefined ? {} : { locale: settings.locale }),
156
167
  modeName: settings.modeName,
@@ -0,0 +1,21 @@
1
+ import type { DsmmCommandDefinition } from "./commands.js";
2
+ import type { DsmmSettingsGetter } from "./settings.js";
3
+ import type { DeepworkModeController } from "./state.js";
4
+ import type { DsmmProfileRuntime } from "./profile-runtime.js";
5
+ import type { DsmmDeploymentConfig } from "./deployment-config.js";
6
+ import type { BeginDsmmTuiAction } from "./tui-types.js";
7
+ export declare const DSMM_TUI_COMPONENT_ID = "com.hugefiver.dsmm";
8
+ export declare const DSMM_TUI_CONTRIBUTIONS: Readonly<{
9
+ manage: "com.hugefiver.dsmm.manage";
10
+ }>;
11
+ declare const DIALOG_TIMEOUT_MS = 30000;
12
+ export interface DsmmTuiActionDependencies {
13
+ controller: DeepworkModeController;
14
+ getSettings: DsmmSettingsGetter;
15
+ profiles: DsmmProfileRuntime;
16
+ deployment: DsmmDeploymentConfig;
17
+ begin: BeginDsmmTuiAction;
18
+ }
19
+ export declare function createDsmmManagementCommandDefinition(deps: DsmmTuiActionDependencies): DsmmCommandDefinition;
20
+ export { DIALOG_TIMEOUT_MS };
21
+ //# sourceMappingURL=tui-actions.d.ts.map
@@ -0,0 +1,301 @@
1
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
+ import { createDsmmStatusSnapshot, formatDsmmStatus } from "./status.js";
3
+ import { handleDsmmStatusCommand, parseDeepworkCommandInput } from "./commands.js";
4
+ export const DSMM_TUI_COMPONENT_ID = "com.hugefiver.dsmm";
5
+ export const DSMM_TUI_CONTRIBUTIONS = Object.freeze({
6
+ manage: `${DSMM_TUI_COMPONENT_ID}.manage`
7
+ });
8
+ const DIALOG_TIMEOUT_MS = 30_000;
9
+ const INHERIT = "inherit";
10
+ const BOOLEAN_VALUES = Object.freeze([
11
+ { id: INHERIT, label: "Inherit" },
12
+ { id: "true", label: "Enabled", value: true },
13
+ { id: "false", label: "Disabled", value: false }
14
+ ]);
15
+ const GLOBAL_FIELDS = Object.freeze([
16
+ { id: "root-model-policy", label: "Root model policy", path: ["rootModelPolicy"], values: [
17
+ { id: INHERIT, label: "Inherit" }, { id: "native", label: "Native", value: "native" }, { id: "configured", label: "Configured", value: "configured" }
18
+ ] },
19
+ { id: "default-active", label: "Deepwork default", path: ["defaultActive"], values: BOOLEAN_VALUES },
20
+ { id: "locale", label: "Locale", path: ["locale"], values: [
21
+ { id: INHERIT, label: "Inherit" }, ...["en", "zh-Hans", "zh-Hant", "ja", "ko", "de", "fr", "es", "pt-BR", "ru"].map(value => ({ id: value, label: value, value }))
22
+ ] },
23
+ { id: "workflow-policy", label: "Workflow policy", path: ["workflow", "policy"], values: [
24
+ { id: INHERIT, label: "Inherit" }, { id: "risk-based", label: "Risk based", value: "risk-based" }, { id: "legacy", label: "Legacy", value: "legacy" }
25
+ ] },
26
+ { id: "tool-topology", label: "Subagent tool topology", path: ["subagents", "toolTopology"], values: [
27
+ { id: INHERIT, label: "Inherit" }, { id: "per-role", label: "Per role", value: "per-role" }, { id: "parameterized", label: "Parameterized", value: "parameterized" }
28
+ ] },
29
+ { id: "deepwork-module", label: "Deepwork module", path: ["modules", "deepwork", "enabled"], values: BOOLEAN_VALUES, restart: true }
30
+ ]);
31
+ async function handleManagedDeepwork(deps, invocation, authority) {
32
+ let committed = false;
33
+ try {
34
+ const parsed = parseDeepworkCommandInput(invocation.rawInput);
35
+ const settings = deps.getSettings(invocation.agent);
36
+ if (parsed.action === "on" && deps.getSettings.subagentRuntime !== undefined && !deps.getSettings.subagentRuntime().deliveryFenceReady) {
37
+ return error("Deepwork runtime is unavailable; check native runtime settings and restart status.");
38
+ }
39
+ if (parsed.action === "on" && !settings.modules.deepwork.enabled) {
40
+ return error("Deepwork module is not admitted in this session; mode cannot enable it.");
41
+ }
42
+ const expectedModeRevision = deps.controller.describe(invocation.agent, settings.defaultActive).revision;
43
+ const target = sessionIdentity(invocation);
44
+ const action = parsed.action === "on" ? "enable" : "disable";
45
+ const detail = parsed.message === "" ? "" : ` and steer one message (${bounded(parsed.message, 120)})`;
46
+ const confirmed = await authority.confirm("Confirm Deepwork action", `${action} Deepwork for session ${target}${detail}; mode revision ${expectedModeRevision}.`, action === "enable" ? "Enable" : "Disable");
47
+ if (confirmed !== true)
48
+ return error("Deepwork action cancelled; no change was started.");
49
+ authority.assertCurrent();
50
+ if (deps.controller.describe(invocation.agent, settings.defaultActive).revision !== expectedModeRevision) {
51
+ return error("Deepwork mode changed; run the command again to confirm the current revision.");
52
+ }
53
+ let committedRevision;
54
+ const outcome = await deps.controller.select(invocation.agent, parsed.action === "on", settings.defaultActive, () => authority.assertCurrent(), revision => { committed = true; committedRevision = revision; });
55
+ committed ||= outcome === "committed";
56
+ if (parsed.action === "on" && parsed.message !== "") {
57
+ try {
58
+ authority.assertCurrent();
59
+ const steerRevision = committed ? committedRevision : expectedModeRevision;
60
+ if (steerRevision === undefined || deps.controller.describe(invocation.agent, settings.defaultActive).revision !== steerRevision) {
61
+ return committed
62
+ ? success("Deepwork mode was committed, but the mode changed before the requested steer; no automatic retry was attempted.")
63
+ : error("Deepwork mode changed before the requested steer; run the command again.");
64
+ }
65
+ await invocation.agent.steer?.(createUserMessage({ content: [{ type: "text", text: parsed.message }], source: { kind: "user" } }));
66
+ }
67
+ catch {
68
+ return committed
69
+ ? success("Deepwork mode was committed, but the requested steer was not confirmed; no automatic retry was attempted.")
70
+ : error("The steer was refused before any confirmed mode change.");
71
+ }
72
+ }
73
+ return parsed.action === "on" ? success("Entering deepwork mode.") : success("Leaving deepwork mode.");
74
+ }
75
+ catch (cause) {
76
+ return committed
77
+ ? success("Deepwork mode was committed, but the remaining action did not complete; no automatic retry was attempted.")
78
+ : actionError(cause);
79
+ }
80
+ }
81
+ export function createDsmmManagementCommandDefinition(deps) {
82
+ return {
83
+ name: "dsmm",
84
+ description: "Manage DSMM status, Deepwork and simple configuration",
85
+ input: { hint: "[status [json]|deepwork [off|message]|config|profiles]" },
86
+ handler: invocation => handleManagement(deps, invocation)
87
+ };
88
+ }
89
+ async function handleManagement(deps, invocation) {
90
+ const input = invocation.rawInput.trim();
91
+ const match = /^(\S+)(?:\s+([\s\S]*))?$/u.exec(input);
92
+ const subcommand = match?.[1] ?? "";
93
+ const argument = match?.[2] ?? "";
94
+ if (!["", "status", "deepwork", "config", "profiles"].includes(subcommand)
95
+ || (subcommand === "status" && argument !== "" && argument !== "json")
96
+ || (["config", "profiles"].includes(subcommand) && argument !== "")) {
97
+ return error("Usage: /dsmm [status [json]|deepwork [off|message]|config|profiles]");
98
+ }
99
+ let authority;
100
+ try {
101
+ authority = deps.begin(invocation, DSMM_TUI_CONTRIBUTIONS.manage, subcommand !== "status");
102
+ let action = subcommand;
103
+ if (action === "") {
104
+ const selected = await authority.select("DSMM", [
105
+ { id: "status", label: "Status", description: "Show desired and admitted state" },
106
+ { id: "deepwork", label: "Deepwork", description: "Enable Deepwork for this session" },
107
+ { id: "config", label: "Global configuration", description: "Edit a limited shared scalar" },
108
+ { id: "profiles", label: "Named profiles", description: "Browse or select an existing profile" }
109
+ ]);
110
+ if (selected === undefined)
111
+ return error("DSMM menu cancelled.");
112
+ action = selected;
113
+ }
114
+ authority.assertCurrent();
115
+ if (action === "status") {
116
+ if (argument === "json")
117
+ return handleDsmmStatusCommand(deps.controller, deps.getSettings, { ...invocation, rawInput: "json" });
118
+ return await managementStatus(deps, invocation, authority);
119
+ }
120
+ if (action === "deepwork")
121
+ return await handleManagedDeepwork(deps, { ...invocation, rawInput: argument }, authority);
122
+ if (action === "config")
123
+ return await manageGlobal(deps, authority);
124
+ if (action === "profiles")
125
+ return await manageProfiles(deps, invocation, authority);
126
+ return error("The selected DSMM action is not available.");
127
+ }
128
+ catch (cause) {
129
+ return actionError(cause);
130
+ }
131
+ finally {
132
+ authority?.close();
133
+ }
134
+ }
135
+ async function managementStatus(deps, invocation, authority) {
136
+ const settings = deps.getSettings(invocation.agent);
137
+ const admission = deps.getSettings.admission?.(invocation.agent);
138
+ const snapshot = createDsmmStatusSnapshot({ agent: invocation.agent, settings, admission,
139
+ modules: deps.getSettings.moduleStates?.(invocation.agent), modeActive: deps.controller.active(invocation.agent, settings.defaultActive) });
140
+ const desired = await deps.deployment.readDesired();
141
+ authority.assertCurrent();
142
+ return success([
143
+ formatDsmmStatus(snapshot),
144
+ "",
145
+ "Desired deployment (future admission)",
146
+ `Root model policy: ${desired.settings.rootModelPolicy}`,
147
+ `Default active: ${desired.settings.defaultActive}`,
148
+ `Locale: ${desired.settings.locale ?? "inherit"}`,
149
+ `Workflow policy: ${desired.settings.workflow.policy}`,
150
+ `Tool topology: ${desired.settings.subagents.toolTopology}`,
151
+ `Deepwork module desired: ${desired.settings.modules.deepwork.enabled}`,
152
+ `Revisions: global=${desired.globalRevision}; native=${desired.nativeRevision}`
153
+ ].join("\n"));
154
+ }
155
+ async function manageGlobal(deps, authority) {
156
+ const snapshot = await deps.deployment.readGlobal();
157
+ authority.assertCurrent();
158
+ const fieldId = await authority.select("Global DSMM field", GLOBAL_FIELDS.map(field => ({ id: field.id, label: field.label,
159
+ description: `${displayValue(getPath(snapshot.config, field.path))}${field.restart ? "; restart may be required" : ""}` })));
160
+ if (fieldId === undefined)
161
+ return error("Global configuration action cancelled.");
162
+ const field = GLOBAL_FIELDS.find(candidate => candidate.id === fieldId);
163
+ if (field === undefined)
164
+ return error("The selected Global field is no longer available.");
165
+ authority.assertCurrent();
166
+ const valueId = await authority.select(`Set ${field.label}`, field.values.map(value => ({ id: value.id, label: value.label })));
167
+ if (valueId === undefined)
168
+ return error("Global configuration action cancelled.");
169
+ const selected = field.values.find(value => value.id === valueId);
170
+ if (selected === undefined)
171
+ return error("The selected Global value is no longer available.");
172
+ authority.assertCurrent();
173
+ const before = displayValue(getPath(snapshot.config, field.path));
174
+ const after = selected.id === INHERIT ? "inherit" : displayValue(selected.value);
175
+ const message = `Change shared Global ${field.path.join(".")} from ${before} to ${after}, requested by session ${authorityIdentity(authority)} at revision ${snapshot.revision}. Existing admissions are unchanged.${field.restart ? " A Host restart may be required." : ""}`;
176
+ if (await authority.confirm("Confirm Global DSMM change", message, "Save") !== true)
177
+ return error("Global configuration action cancelled; no write was started.");
178
+ authority.assertCurrent();
179
+ const edit = selected.id === INHERIT
180
+ ? { op: "unset", path: [...field.path] }
181
+ : { op: "set", path: [...field.path], value: selected.value };
182
+ const saved = await deps.deployment.saveGlobal({ expectedRevision: snapshot.revision, edits: [edit] }, () => authority.assertCurrent());
183
+ return success(`Saved Global ${field.path.join(".")}=${after}; desired revision is ${saved.revision}.${saved.refreshRequired ? " Refresh is required before another edit." : ""}`);
184
+ }
185
+ async function manageProfiles(deps, invocation, authority) {
186
+ const operation = await authority.select("Named profiles", [
187
+ { id: "browse", label: "Browse", description: "Show saved profile IDs, diagnostics and revisions" },
188
+ { id: "future", label: "Select future default", description: "Set or clear the default for new sessions" },
189
+ { id: "session", label: "Apply to current session", description: "Pin a profile or the deployment baseline" }
190
+ ]);
191
+ if (operation === undefined)
192
+ return error("Named profile action cancelled.");
193
+ authority.assertCurrent();
194
+ const inventory = await deps.profiles.describe();
195
+ authority.assertCurrent();
196
+ if (operation === "browse")
197
+ return success(formatProfileInventory(inventory));
198
+ const target = await chooseProfile(authority, inventory);
199
+ if (target === undefined)
200
+ return error("Named profile action cancelled.");
201
+ authority.assertCurrent();
202
+ const id = target === null ? null : target.id;
203
+ const revision = target === null ? undefined : target.revision ?? undefined;
204
+ if (target !== null && revision === undefined)
205
+ return error("The selected profile has no valid revision and cannot be applied.");
206
+ if (operation === "future") {
207
+ const message = `Change the future Global named-profile default to ${id ?? "deployment baseline"}, requested by session ${authorityIdentity(authority)}; selection revision ${inventory.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}. Current sessions are unchanged.`;
208
+ if (await authority.confirm("Confirm future profile default", message, "Select") !== true)
209
+ return error("Named profile action cancelled; no selection was started.");
210
+ authority.assertCurrent();
211
+ const selected = await deps.profiles.select({ id, expectedSelectionRevision: inventory.selectionRevision,
212
+ ...(revision === undefined ? {} : { expectedRevision: revision }) }, () => authority.assertCurrent());
213
+ return success(`Future named-profile default is ${selected.selectedId ?? "deployment baseline"}; current sessions were not changed.${selected.refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
214
+ }
215
+ const session = await deps.profiles.getSession(invocation.agent);
216
+ authority.assertCurrent();
217
+ const message = `Apply ${id ?? "deployment baseline"} to live root session ${session.sessionId}; admission ${session.admissionEpoch}; selection revision ${session.selection.selectionRevision}${revision === undefined ? "" : `; profile revision ${revision}`}.`;
218
+ if (await authority.confirm("Confirm session profile", message, "Apply") !== true)
219
+ return error("Session profile action cancelled; no maintenance was started.");
220
+ authority.assertCurrent();
221
+ const selected = await deps.profiles.selectSession({ sessionId: session.sessionId, id,
222
+ expectedSelectionRevision: session.selection.selectionRevision, expectedAdmissionEpoch: session.admissionEpoch,
223
+ ...(revision === undefined ? {} : { expectedRevision: revision }) }, invocation.agent, authority.signal, () => authority.assertCurrent());
224
+ const refreshRequired = selected.refreshRequired === true || selected.selection.refreshRequired === true;
225
+ return success(`Session ${selected.sessionId} now admits ${selected.admittedSelection?.selectedId ?? "deployment baseline"}; admission epoch ${selected.admissionEpoch}.${refreshRequired ? " The commit succeeded, but refresh is required before another profile action." : ""}`);
226
+ }
227
+ async function chooseProfile(authority, inventory) {
228
+ const available = inventory.profiles.filter(profile => profile.error === undefined && typeof profile.revision === "string");
229
+ const pageSize = 96;
230
+ let page = 0;
231
+ while (true) {
232
+ const start = page * pageSize;
233
+ const rows = available.slice(start, start + pageSize);
234
+ const options = [
235
+ { id: "baseline", label: "Deployment baseline", description: "Clear the named-profile selection" },
236
+ ...rows.map((profile, index) => ({ id: `profile:${start + index}`, label: bounded(profile.label?.trim() || profile.id, 120), description: `${profile.id}; revision ${profile.revision}` })),
237
+ ...(page > 0 ? [{ id: "previous", label: "Previous page" }] : []),
238
+ ...(start + pageSize < available.length ? [{ id: "next", label: "Next page" }] : [])
239
+ ];
240
+ const answer = await authority.select("Choose a saved profile", options);
241
+ if (answer === undefined)
242
+ return undefined;
243
+ authority.assertCurrent();
244
+ if (answer === "baseline")
245
+ return null;
246
+ if (answer === "previous") {
247
+ page--;
248
+ continue;
249
+ }
250
+ if (answer === "next") {
251
+ page++;
252
+ continue;
253
+ }
254
+ const match = /^profile:(\d+)$/u.exec(answer);
255
+ if (match === null)
256
+ return undefined;
257
+ const selected = available[Number(match[1])];
258
+ if (selected !== undefined)
259
+ return selected;
260
+ }
261
+ }
262
+ function formatProfileInventory(snapshot) {
263
+ const rows = snapshot.profiles.map(profile => `${profile.id} | ${bounded(profile.label?.trim() || "unlabelled", 80)} | ${profile.error?.code ?? profile.revision ?? "unavailable"}`);
264
+ return [
265
+ `Future default: ${snapshot.selectedId ?? "deployment baseline"}`,
266
+ `Selection revision: ${snapshot.selectionRevision}`,
267
+ `Store: ${snapshot.origin ?? "unknown"}; ${snapshot.readOnly ? "read-only" : "writable"}`,
268
+ ...(rows.length === 0 ? ["No saved named profiles."] : rows)
269
+ ].join("\n");
270
+ }
271
+ function getPath(value, path) {
272
+ let current = value;
273
+ for (const key of path) {
274
+ if (current === null || typeof current !== "object" || Array.isArray(current))
275
+ return undefined;
276
+ current = Reflect.get(current, key);
277
+ }
278
+ return current;
279
+ }
280
+ function displayValue(value) {
281
+ return value === undefined ? "inherit" : typeof value === "string" || typeof value === "boolean" ? String(value) : "configured";
282
+ }
283
+ function sessionIdentity(invocation) {
284
+ return bounded(invocation.agent.id ?? invocation.agent.session.id ?? "unknown", 80);
285
+ }
286
+ function authorityIdentity(authority) {
287
+ return bounded(authority.agent.id ?? authority.agent.session.id ?? "unknown", 80);
288
+ }
289
+ function bounded(value, limit) {
290
+ const clean = value.replace(/[\u0000-\u001F\u007F]/gu, " ").replace(/\s+/gu, " ").trim();
291
+ return clean.length <= limit ? clean : `${clean.slice(0, Math.max(0, limit - 1))}…`;
292
+ }
293
+ function success(text) { return { kind: "success", text }; }
294
+ function error(text) { return { kind: "error", text }; }
295
+ function actionError(cause) {
296
+ if (cause instanceof Error && cause.name === "AbortError")
297
+ return error("DSMM action cancelled; no new write was started.");
298
+ return error(cause instanceof Error ? bounded(cause.message, 400) : "The Host refused the DSMM action.");
299
+ }
300
+ export { DIALOG_TIMEOUT_MS };
301
+ //# sourceMappingURL=tui-actions.js.map
@@ -0,0 +1,25 @@
1
+ import type { DshContext } from "./dsh-types.js";
2
+ import type { DsmmSettingsGetter } from "./settings.js";
3
+ import type { DeepworkModeController } from "./state.js";
4
+ import type { DsmmProfileRuntime } from "./profile-runtime.js";
5
+ import type { DsmmDeploymentConfig } from "./deployment-config.js";
6
+ import type { TuiSettingsSection } from "./tui-types.js";
7
+ export interface DsmmTuiAdapterOptions {
8
+ controller: DeepworkModeController;
9
+ getSettings: DsmmSettingsGetter;
10
+ profiles: DsmmProfileRuntime;
11
+ deployment: DsmmDeploymentConfig;
12
+ clock?: DsmmTuiClock;
13
+ }
14
+ export interface DsmmTuiClock {
15
+ setTimeout(callback: () => void, delayMs: number): unknown;
16
+ clearTimeout(handle: unknown): void;
17
+ }
18
+ export interface DsmmTuiAdapterHandle {
19
+ readonly managed: boolean;
20
+ settled(): Promise<void>;
21
+ dispose(): void;
22
+ }
23
+ export declare function createDsmmTuiSettingsSection(namespace: string): TuiSettingsSection;
24
+ export declare function registerDsmmTuiAdapter(ctx: DshContext, options: DsmmTuiAdapterOptions): DsmmTuiAdapterHandle;
25
+ //# sourceMappingURL=tui-adapter.d.ts.map