dsh-plugin-wsl-env 0.24.0 → 0.26.0

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 (94) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/CODE_OF_CONDUCT.md +85 -0
  3. package/CODE_OF_CONDUCT.zh.md +85 -0
  4. package/CONTRIBUTING.md +19 -3
  5. package/CONTRIBUTING.zh.md +200 -0
  6. package/README.md +18 -6
  7. package/SECURITY.md +12 -0
  8. package/SECURITY.zh.md +108 -0
  9. package/SUPPORT.md +2 -0
  10. package/SUPPORT.zh.md +99 -0
  11. package/client.js +409 -8
  12. package/cordis.patch.yml +17 -0
  13. package/docs/AGENT-PROTOCOL-V7.md +2 -2
  14. package/docs/API.md +2 -0
  15. package/docs/API.zh.md +38 -0
  16. package/docs/ARCHITECTURE.md +30 -9
  17. package/docs/ARCHITECTURE.zh.md +511 -0
  18. package/docs/COMPATIBILITY.md +2 -0
  19. package/docs/COMPATIBILITY.zh.md +117 -0
  20. package/docs/CONFIGURATION.md +45 -2
  21. package/docs/CONFIGURATION.zh.md +39 -3
  22. package/docs/DIAGNOSTICS.md +12 -2
  23. package/docs/DIAGNOSTICS.zh.md +5 -1
  24. package/docs/LIMITATIONS.md +60 -9
  25. package/docs/LIMITATIONS.zh.md +45 -9
  26. package/docs/MIGRATION.md +6 -3
  27. package/docs/MIGRATION.zh.md +91 -0
  28. package/docs/PEER-PARITY.md +63 -51
  29. package/docs/PERFORMANCE.md +2 -0
  30. package/docs/PERFORMANCE.zh.md +59 -0
  31. package/docs/QUICKSTART.md +21 -6
  32. package/docs/QUICKSTART.zh.md +16 -4
  33. package/docs/README.zh.md +28 -19
  34. package/docs/RELEASING.md +19 -14
  35. package/docs/REQUIREMENTS.zh.md +6 -3
  36. package/docs/ROADMAP-1.0.md +1 -1
  37. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +1 -1
  38. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  39. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -11
  40. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  41. package/docs/UPSTREAM-SESSION-NOTICE.md +7 -0
  42. package/docs/VALUE.md +146 -0
  43. package/docs/VALUE.zh.md +15 -13
  44. package/docs/root-fs-routing.md +1 -1
  45. package/lib/agent-confined.d.ts +7 -1
  46. package/lib/agent-confined.js +3 -3
  47. package/lib/auto-preset-seam.d.ts +45 -0
  48. package/lib/auto-preset-seam.js +47 -0
  49. package/lib/auto-preset.d.ts +33 -10
  50. package/lib/auto-preset.js +148 -44
  51. package/lib/bwrap.d.ts +14 -0
  52. package/lib/bwrap.js +11 -0
  53. package/lib/cwd-prompt.d.ts +41 -3
  54. package/lib/cwd-prompt.js +125 -8
  55. package/lib/doctor-live.d.ts +30 -0
  56. package/lib/doctor-live.js +37 -0
  57. package/lib/doctor-report.d.ts +50 -0
  58. package/lib/doctor-report.js +172 -0
  59. package/lib/fs-routing.d.ts +1 -1
  60. package/lib/fs-routing.js +1 -1
  61. package/lib/fs.d.ts +1 -1
  62. package/lib/fs.js +1 -1
  63. package/lib/index.d.ts +6 -1464
  64. package/lib/index.js +5 -2120
  65. package/lib/messages.d.ts +20 -1
  66. package/lib/messages.js +31 -3
  67. package/lib/open-in-app.d.ts +206 -0
  68. package/lib/open-in-app.js +300 -0
  69. package/lib/preflight.d.ts +7 -4
  70. package/lib/preflight.js +27 -13
  71. package/lib/preset-choice.d.ts +13 -0
  72. package/lib/preset-choice.js +18 -1
  73. package/lib/provider-common.d.ts +58 -0
  74. package/lib/provider-common.js +123 -0
  75. package/lib/sandbox-core.d.ts +1 -0
  76. package/lib/sandbox-core.js +4 -2
  77. package/lib/session-runtime.d.ts +7 -1
  78. package/lib/session-runtime.js +9 -2
  79. package/lib/shell.d.ts +1 -1
  80. package/lib/shell.js +1 -1
  81. package/lib/status.js +2 -1
  82. package/lib/writable-roots.d.ts +109 -0
  83. package/lib/writable-roots.js +257 -0
  84. package/lib/wsl-doctor-command.js +2 -1
  85. package/lib/wsl-doctor-tool.js +2 -2
  86. package/lib/wsl-filesystem.d.ts +692 -0
  87. package/lib/wsl-filesystem.js +897 -0
  88. package/lib/wsl-shell.d.ts +742 -0
  89. package/lib/wsl-shell.js +965 -0
  90. package/lib/wsl.d.ts +1 -1
  91. package/lib/wsl.js +1 -1
  92. package/package.json +48 -24
  93. package/scripts/doctor.mjs +1 -1
  94. package/scripts/profile-preset.mjs +17 -5
@@ -65,6 +65,12 @@ interface ConfinedAgentRequest {
65
65
  * exists to prevent.
66
66
  */
67
67
  realTmp?: boolean;
68
+ /**
69
+ * Extra Linux roots to bind read-write in the resident's profile. The
70
+ * provider resolved, filtered and checked them; they are part of the cache
71
+ * key because the mount table is fixed for the resident's lifetime.
72
+ */
73
+ writableRoots?: readonly string[];
68
74
  }
69
75
  /**
70
76
  * The confined agent for one distro and one resolved policy, created on first
@@ -74,7 +80,7 @@ interface ConfinedAgentRequest {
74
80
  * @param request - the confinement request.
75
81
  * @returns the confined resident for this key.
76
82
  */
77
- export declare function confinedAgent({ distro, wslPath, policy, maskWindowsDrive, realTmp }: ConfinedAgentRequest): WslAgent;
83
+ export declare function confinedAgent({ distro, wslPath, policy, maskWindowsDrive, realTmp, writableRoots }: ConfinedAgentRequest): WslAgent;
78
84
  /** Test hook: forget every confined resident (the plain agent has no factory state). */
79
85
  export declare function resetConfinedAgents(): void;
80
86
  export {};
@@ -105,8 +105,8 @@ export async function runSpawnChecklist({ wslPath, distro, root, runFn }) {
105
105
  * @param request - the confinement request.
106
106
  * @returns the confined resident for this key.
107
107
  */
108
- export function confinedAgent({ distro, wslPath = "wsl.exe", policy, maskWindowsDrive = false, realTmp = true }) {
109
- const key = `${wslPath}\0${distro}\0${policy.mode}\0${policy.workspaceRoot}\0${maskWindowsDrive ? "masked" : "visible"}\0${realTmp ? "real" : "ephemeral"}`;
108
+ export function confinedAgent({ distro, wslPath = "wsl.exe", policy, maskWindowsDrive = false, realTmp = true, writableRoots = [] }) {
109
+ const key = `${wslPath}\0${distro}\0${policy.mode}\0${policy.workspaceRoot}\0${maskWindowsDrive ? "masked" : "visible"}\0${realTmp ? "real" : "ephemeral"}\0${writableRoots.join("\0")}`;
110
110
  let agent = confinedAgents.get(key);
111
111
  if (agent === undefined) {
112
112
  const linuxRoot = toLinuxPath(policy.workspaceRoot);
@@ -120,7 +120,7 @@ export function confinedAgent({ distro, wslPath = "wsl.exe", policy, maskWindows
120
120
  // `wsl.exe --exec` and the `sh <script>` pair (`lib/agent.js`'s
121
121
  // `spawnDefault`). Both confinement sites share that assembly in
122
122
  // `lib/bwrap.js`, whose module doc records what happened when they did not.
123
- argvPrefix: bwrapArgvPrefix({ mode: policy.mode, workspaceRoot: linuxRoot }, { maskWindowsDrive, realTmp }),
123
+ argvPrefix: bwrapArgvPrefix({ mode: policy.mode, workspaceRoot: linuxRoot }, { maskWindowsDrive, realTmp, writableRoots }),
124
124
  // workspace-write is the only mode that binds the workspace root, and
125
125
  // bwrap refuses a missing bind source (WSL-305): on a freshly imported
126
126
  // distro the first write's workspace may not exist yet, and the resident
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The live state of auto-preset's creation-time preset seam.
3
+ *
4
+ * The seam is host-process state: `auto-preset` wraps
5
+ * `sessionController.agents.createSession(request)` so a distro workspace's
6
+ * very first mount is the WSL preset. Whether that method exists is a property
7
+ * of the running host, not of any file on disk — the standalone doctor CLI
8
+ * cannot see it, exactly as it cannot see a live resident's `deaths` or
9
+ * `lastError` (see doctor-live). The in-app doctor surfaces therefore read this
10
+ * module singleton and merge the state into their reports.
11
+ *
12
+ * `unknown` means the row has not mounted in this process yet (or this is a
13
+ * composition without it); `inactive` means the row mounted but the host's
14
+ * controller exposed no `agents.createSession` — the case that must not stay
15
+ * silent.
16
+ *
17
+ * @module dsh-plugin-wsl-env/auto-preset-seam
18
+ */
19
+ /** Whether the creation-time seam is available in this process. */
20
+ export type AutoPresetSeamState = "active" | "inactive" | "unknown";
21
+ /** One publication of the seam state. */
22
+ export interface AutoPresetSeam {
23
+ /** The seam's availability. */
24
+ readonly state: AutoPresetSeamState;
25
+ /** The wrapped method, when the seam is active. */
26
+ readonly method?: string;
27
+ /** Why the state is what it is, in one line. */
28
+ readonly reason: string;
29
+ /** When the state was published, in epoch milliseconds. */
30
+ readonly at: number;
31
+ }
32
+ /**
33
+ * Publish the seam state for the in-app doctor surfaces.
34
+ *
35
+ * @param state - the availability to record.
36
+ * @param reason - one line explaining the state.
37
+ * @param method - the wrapped method, when active.
38
+ */
39
+ export declare function publishAutoPresetSeam(state: AutoPresetSeamState, reason: string, method?: string): void;
40
+ /**
41
+ * Read the current seam state.
42
+ *
43
+ * @returns the last published state.
44
+ */
45
+ export declare function autoPresetSeam(): AutoPresetSeam;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The live state of auto-preset's creation-time preset seam.
3
+ *
4
+ * The seam is host-process state: `auto-preset` wraps
5
+ * `sessionController.agents.createSession(request)` so a distro workspace's
6
+ * very first mount is the WSL preset. Whether that method exists is a property
7
+ * of the running host, not of any file on disk — the standalone doctor CLI
8
+ * cannot see it, exactly as it cannot see a live resident's `deaths` or
9
+ * `lastError` (see doctor-live). The in-app doctor surfaces therefore read this
10
+ * module singleton and merge the state into their reports.
11
+ *
12
+ * `unknown` means the row has not mounted in this process yet (or this is a
13
+ * composition without it); `inactive` means the row mounted but the host's
14
+ * controller exposed no `agents.createSession` — the case that must not stay
15
+ * silent.
16
+ *
17
+ * @module dsh-plugin-wsl-env/auto-preset-seam
18
+ */
19
+ /** The state before the row mounts; a report that sees it says so instead of guessing. */
20
+ let seam = {
21
+ state: "unknown",
22
+ reason: "the auto-preset row has not mounted in this process",
23
+ at: 0,
24
+ };
25
+ /**
26
+ * Publish the seam state for the in-app doctor surfaces.
27
+ *
28
+ * @param state - the availability to record.
29
+ * @param reason - one line explaining the state.
30
+ * @param method - the wrapped method, when active.
31
+ */
32
+ export function publishAutoPresetSeam(state, reason, method) {
33
+ seam = {
34
+ state,
35
+ reason,
36
+ at: Date.now(),
37
+ ...(method === undefined ? {} : { method }),
38
+ };
39
+ }
40
+ /**
41
+ * Read the current seam state.
42
+ *
43
+ * @returns the last published state.
44
+ */
45
+ export function autoPresetSeam() {
46
+ return seam;
47
+ }
@@ -4,9 +4,10 @@
4
4
  *
5
5
  * Why an event hook and not configuration: the environment is chosen in
6
6
  * `dsh-api-session-controller`'s `composeAgent(presetId)`, whose signature has no
7
- * working directory — the cwd only exists one frame up in
8
- * `ensureSession(sessionId, cwd, ...)`. So the path-aware decision has to be made
9
- * where the path IS available. `agent/created` carries it:
7
+ * working directory. The creation API above it — `createSession({ cwd,
8
+ * agentPreset, ... })` — holds both, so this row wraps that frame to fill the
9
+ * preset before the first mount; the `agent/created` event below is the
10
+ * fallback for flows that do not pass through it:
10
11
  *
11
12
  * ctx.serial(carrier, "agent/created", { agent, source, signal })
12
13
  *
@@ -16,9 +17,10 @@
16
17
  *
17
18
  * 1. **Respect an explicit choice.** By the time the event fires, the resolved
18
19
  * preset is already mounted (`composeAgent` mounts request-or-default in
19
- * `setup`). We cannot tell which of the two it was — so we only ever rewrite
20
- * when the mounted preset equals the registry default, which means the client
21
- * omitted it. An operator's pick is never overridden.
20
+ * `setup`). A non-default preset id is an operator's pick and is never
21
+ * overridden. The default id (or no id at all) is not a pick of another
22
+ * environment: the client may send it explicitly, so the creation-time hook
23
+ * treats it as automatic for a distro workspace.
22
24
  *
23
25
  * 2. **Switch after creation, not during.** Switching inside the listener
24
26
  * collides with the previous generation's tools:
@@ -99,11 +101,34 @@ interface CreatedAgentView {
99
101
  session?: {
100
102
  header?: {
101
103
  cwd?: string | undefined;
102
- };
104
+ /** A subagent session inherits its parent's environment; it gets no advisory of its own. */
105
+ origin?: string | undefined;
106
+ parentSession?: string | undefined;
107
+ } | undefined;
103
108
  } | undefined;
104
109
  /** The agent's own context. */
105
110
  ctx: Context;
106
111
  }
112
+ /**
113
+ * The create request the host's session-agent controller accepts (0.2.2+).
114
+ * Only the fields this row reads are spelled here; the wrapper forwards the
115
+ * whole object, so a newer host field survives untouched.
116
+ */
117
+ interface SessionCreateRequestLike {
118
+ /** The blank session to reuse, when the caller named one. */
119
+ readonly sessionId?: string;
120
+ /** The workspace the session owns. */
121
+ readonly cwd: string;
122
+ /** The preset the caller requested, or undefined for the default. */
123
+ readonly agentPreset?: string;
124
+ /** The caller's reuse policy, forwarded untouched. */
125
+ readonly reusable: (sessionId: string) => boolean;
126
+ }
127
+ /** The controller slice this row wraps. */
128
+ interface SessionAgentFacade {
129
+ /** Create or reuse the session for one request; the creation-time seam. */
130
+ createSession?: (request: SessionCreateRequestLike) => Promise<unknown>;
131
+ }
107
132
  /**
108
133
  * The cordis context extended with the agent-service slices this plugin
109
134
  * consumes. `agents` and `agentPresets` come from the harness's agent
@@ -123,9 +148,7 @@ type AutoPresetContext = Context & {
123
148
  agent?: CreatedAgentView;
124
149
  } | undefined) => void) => () => boolean;
125
150
  sessionController?: {
126
- agents?: {
127
- ensureSession: (this: unknown, sessionId: string, cwd: string | undefined, checkPersistedIdentity: boolean, presetId: string | undefined) => Promise<unknown>;
128
- };
151
+ agents?: SessionAgentFacade;
129
152
  };
130
153
  };
131
154
  /**
@@ -4,9 +4,10 @@
4
4
  *
5
5
  * Why an event hook and not configuration: the environment is chosen in
6
6
  * `dsh-api-session-controller`'s `composeAgent(presetId)`, whose signature has no
7
- * working directory — the cwd only exists one frame up in
8
- * `ensureSession(sessionId, cwd, ...)`. So the path-aware decision has to be made
9
- * where the path IS available. `agent/created` carries it:
7
+ * working directory. The creation API above it — `createSession({ cwd,
8
+ * agentPreset, ... })` — holds both, so this row wraps that frame to fill the
9
+ * preset before the first mount; the `agent/created` event below is the
10
+ * fallback for flows that do not pass through it:
10
11
  *
11
12
  * ctx.serial(carrier, "agent/created", { agent, source, signal })
12
13
  *
@@ -16,9 +17,10 @@
16
17
  *
17
18
  * 1. **Respect an explicit choice.** By the time the event fires, the resolved
18
19
  * preset is already mounted (`composeAgent` mounts request-or-default in
19
- * `setup`). We cannot tell which of the two it was — so we only ever rewrite
20
- * when the mounted preset equals the registry default, which means the client
21
- * omitted it. An operator's pick is never overridden.
20
+ * `setup`). A non-default preset id is an operator's pick and is never
21
+ * overridden. The default id (or no id at all) is not a pick of another
22
+ * environment: the client may send it explicitly, so the creation-time hook
23
+ * treats it as automatic for a distro workspace.
22
24
  *
23
25
  * 2. **Switch after creation, not during.** Switching inside the listener
24
26
  * collides with the previous generation's tools:
@@ -35,8 +37,11 @@
35
37
  */
36
38
  import { appendFileSync } from "node:fs";
37
39
  import z from "@deepseek-ai/schemastery";
40
+ import { distroOfUnc } from "./distro-route.js";
41
+ import { installMessagesLocale, t } from "./messages.js";
38
42
  import { isWslUnc } from "./paths.js";
39
- import { isWindowsAccessWorkspace, shouldAdoptWslPreset } from "./preset-choice.js";
43
+ import { publishAutoPresetSeam } from "./auto-preset-seam.js";
44
+ import { isDefaultPresetChoice, isWindowsAccessWorkspace, shouldAdoptWslPreset } from "./preset-choice.js";
40
45
  /**
41
46
  * Set `DSH_WSL_TRACE` to a file path to record every decision this plugin makes.
42
47
  *
@@ -60,6 +65,35 @@ function trace(message) {
60
65
  /* a trace is never worth failing a session over */
61
66
  }
62
67
  }
68
+ /**
69
+ * Read the registry's default preset id, tolerating a service without one.
70
+ *
71
+ * @param ctx - the plugin context.
72
+ * @returns the default id, or undefined when the registry cannot name one.
73
+ */
74
+ function defaultPresetId(ctx) {
75
+ try {
76
+ return ctx.agentPresets.defaultId;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ /**
83
+ * Whether a create failure is the preset registry refusing the target — the
84
+ * one error class adoption may fall back on. A failed adoption must not turn
85
+ * into a failed session creation; anything else still propagates.
86
+ *
87
+ * @param error - the rejection from the host's create call.
88
+ * @returns true when the caller may retry with the recorded preset.
89
+ */
90
+ function isPresetAdoptionError(error) {
91
+ const code = error?.code;
92
+ if (typeof code === "string" && code.startsWith("agent-preset/"))
93
+ return true;
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ return message.toLowerCase().includes("agent preset");
96
+ }
63
97
  export const name = "auto-preset";
64
98
  export const inject = ["agents", "agentPresets"];
65
99
  export const Config = z.object({
@@ -93,8 +127,16 @@ function windowsAccessList(value) {
93
127
  if (value === undefined)
94
128
  return [];
95
129
  if (typeof value.get === "function") {
96
- const current = value.get();
97
- return Array.isArray(current) ? current : [];
130
+ try {
131
+ const current = value.get();
132
+ return Array.isArray(current) ? current : [];
133
+ }
134
+ catch {
135
+ // A volatile read is config, not session state: a throwing field must not
136
+ // fail a session creation or an adoption decision. An unreadable record
137
+ // means "no recorded Windows-access directory".
138
+ return [];
139
+ }
98
140
  }
99
141
  return Array.isArray(value) ? value : [];
100
142
  }
@@ -108,6 +150,9 @@ export async function apply(ctx, config = {}) {
108
150
  const target = config.preset ?? "wsl";
109
151
  const attempts = config.attempts ?? 6;
110
152
  const retryMs = config.retryMs ?? 150;
153
+ // The advisory below is model-facing text; follow the app's language like the
154
+ // other rows do (a profile without `settings` keeps English).
155
+ installMessagesLocale(ctx);
111
156
  const warn = (message) => {
112
157
  trace(`WARN ${message}`);
113
158
  // `logger` is not injectable here, so an unavailable or throwing logger must
@@ -129,6 +174,47 @@ export async function apply(ctx, config = {}) {
129
174
  }
130
175
  }
131
176
  };
177
+ /**
178
+ * Say, once, that a distro workspace is running the host environment.
179
+ *
180
+ * The model gets a runtime-context entry because otherwise it believes its
181
+ * commands run in the distro (they run in Windows PowerShell, and file access
182
+ * crosses the 9p share). The operator gets the log line; the web client's
183
+ * banner is the human-facing half of the same fact. Nothing here can fail a
184
+ * session: the whole plugin is advisory at this point.
185
+ *
186
+ * @param agent - the session that just opened.
187
+ * @param cwd - its workspace, a `\\wsl.localhost\…` path.
188
+ * @param message - the already-localized advisory.
189
+ */
190
+ const advised = new Set();
191
+ const adviseHostMode = (agent, cwd, message) => {
192
+ if (advised.has(agent.id) || !isWslUnc(cwd))
193
+ return;
194
+ // A subagent inherits the environment its parent was told about; repeating
195
+ // the advisory in every child context is noise, not information.
196
+ const header = agent.session?.header;
197
+ if (header?.origin === "subagent" || header?.parentSession !== undefined)
198
+ return;
199
+ advised.add(agent.id);
200
+ warn(`"${cwd}" runs the host (Windows) environment: commands use PowerShell and file access crosses the 9p share`);
201
+ // The harness's agent context carries `systemPrompt`; the service is not in
202
+ // this plugin's typings, so the injection is spelled structurally. A host
203
+ // payload without a context still gets the log line, not a crash.
204
+ const context = agent.ctx;
205
+ const inject = context?.inject;
206
+ if (typeof inject !== "function" || context === undefined)
207
+ return;
208
+ try {
209
+ inject.call(context, ["systemPrompt"], (scope) => {
210
+ scope.systemPrompt.context({ name: "wsl-access-mode", order: 200, text: () => message });
211
+ });
212
+ }
213
+ catch (error) {
214
+ // A missing seam degrades to the log line above, never to a failed session.
215
+ trace(` -> could not publish the host-mode advisory: ${error?.message ?? error}`);
216
+ }
217
+ };
132
218
  const consider = (agent) => {
133
219
  if (agent === void 0)
134
220
  return;
@@ -147,27 +233,25 @@ export async function apply(ctx, config = {}) {
147
233
  // registry default (i.e. the operator did not ask for one). `undefined` means
148
234
  // the creating caller mounted nothing at all — the headless runner does this
149
235
  // — which is likewise "no explicit choice".
150
- let fallback;
151
- try {
152
- fallback = ctx.agentPresets.defaultId;
153
- }
154
- catch {
155
- fallback = void 0;
156
- }
236
+ const fallback = defaultPresetId(ctx);
157
237
  const windowsAccess = windowsAccessList(config.windowsWorkspaces);
158
238
  if (!shouldAdoptWslPreset({ cwd, current, fallback, windowsAccess })) {
159
- if (cwd !== undefined && windowsAccess.length > 0) {
239
+ if (cwd !== undefined && isWindowsAccessWorkspace(cwd, windowsAccess)) {
160
240
  trace(` -> skipped: Windows-access workspace ${JSON.stringify(cwd)}`);
241
+ adviseHostMode(agent, cwd, t("hostModeWindowsAccess", { cwd, distro: distroOfUnc(cwd) ?? "WSL" }));
161
242
  }
162
243
  return;
163
244
  }
164
- trace(` -> acting: fallback=${String(fallback)} isWsl=${isWslUnc(cwd)}`);
245
+ if (cwd === undefined)
246
+ return;
247
+ const workspace = cwd;
248
+ trace(` -> acting: fallback=${String(fallback)} isWsl=${isWslUnc(workspace)}`);
165
249
  // Deferred on purpose — see the module comment.
166
250
  void (async () => {
167
251
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
168
252
  try {
169
253
  const chosen = await ctx.agentPresets.select(agent, target);
170
- ctx.logger?.debug?.(`auto-preset: "${cwd}" -> preset "${chosen}"`);
254
+ ctx.logger?.debug?.(`auto-preset: "${workspace}" -> preset "${chosen}"`);
171
255
  return;
172
256
  }
173
257
  catch (error) {
@@ -175,15 +259,17 @@ export async function apply(ctx, config = {}) {
175
259
  // The session already started a turn: its preset is fixed, and that is
176
260
  // a legitimate outcome (the operator drove it before we got here).
177
261
  if (code === "agent-preset/locked") {
178
- warn(`"${cwd}" already began its first turn; leaving the preset as "${String(current)}"`);
262
+ warn(`"${workspace}" already began its first turn; leaving the preset as "${String(current)}"`);
263
+ adviseHostMode(agent, workspace, t("hostModeLocked", { cwd: workspace, distro: distroOfUnc(workspace) ?? "WSL" }));
179
264
  return;
180
265
  }
181
266
  if (code === "agent-preset/not-found") {
182
- warn(`preset "${target}" is not composed in this profile; skipping "${cwd}"`);
267
+ warn(`preset "${target}" is not composed in this profile; skipping "${workspace}"`);
268
+ adviseHostMode(agent, workspace, t("hostModePresetUnavailable", { cwd: workspace, distro: distroOfUnc(workspace) ?? "WSL" }));
183
269
  return;
184
270
  }
185
271
  if (attempt === attempts) {
186
- warn(`could not bind preset "${target}" for "${cwd}": ${code ?? error?.name}: ${error?.message}`);
272
+ warn(`could not bind preset "${target}" for "${workspace}": ${code ?? error?.name}: ${error?.message}`);
187
273
  return;
188
274
  }
189
275
  await new Promise((resolve) => setTimeout(resolve, retryMs));
@@ -200,41 +286,59 @@ export async function apply(ctx, config = {}) {
200
286
  // failed (Win32 1)`) and the workspace is unusable — not merely mis-labelled.
201
287
  // Correcting the preset after creation loses whenever the first turn does not
202
288
  // wait, so the choice is made where the cwd still exists: the controller
203
- // resolves the preset in `composeAgent(presetId)`, which has no cwd, but it
204
- // calls `agents.ensureSession(sessionId, cwd, …, presetId)` — and that frame
205
- // holds both. Filling the preset there makes the very first mount already
206
- // correct, so the host sandbox never meets the distro path at all.
289
+ // resolves the preset in `composeAgent(presetId)`, which has no cwd, but its
290
+ // caller `createSession({ cwd, agentPreset, … })` holds both. Filling the
291
+ // preset there makes the very first mount already correct, so the host sandbox
292
+ // never meets the distro path at all.
293
+ //
294
+ // The host renamed this frame: 0.2.0-rc.2 exposed
295
+ // `ensureSession(sessionId, cwd, …, presetId)`; 0.2.1 replaced it with the
296
+ // request object below. Wrapping the request keeps any field a newer host adds
297
+ // intact, and a missing method is reported through the warning and the
298
+ // doctor's `session.preset-seam` check instead of failing silently.
207
299
  ctx.inject(["sessionController"], (controllerCtx) => {
208
300
  const facade = controllerCtx.sessionController?.agents;
209
- if (facade === void 0 || typeof facade.ensureSession !== "function") {
210
- warn("sessionController exposes no agents.ensureSession(); the creation-time preset fix is inactive");
301
+ if (facade === void 0 || typeof facade.createSession !== "function") {
302
+ publishAutoPresetSeam("inactive", "the host's sessionController exposes no agents.createSession()");
303
+ warn("sessionController exposes no agents.createSession(); the creation-time preset fix is inactive");
211
304
  return;
212
305
  }
213
- const original = facade.ensureSession;
214
- facade.ensureSession = async function (sessionId, cwd, checkPersistedIdentity, presetId) {
215
- // An explicit choice always wins, and only a distro workspace is affected.
216
- // A workspace the operator opened for Windows access keeps the host
217
- // preset even here: this is the frame that makes the first mount correct,
218
- // so skipping it is what the choice means.
219
- if (presetId !== void 0 || cwd === undefined || !isWslUnc(cwd)
220
- || isWindowsAccessWorkspace(cwd, windowsAccessList(config.windowsWorkspaces))) {
221
- return original.call(this, sessionId, cwd, checkPersistedIdentity, presetId);
306
+ const original = facade.createSession;
307
+ facade.createSession = async function (request) {
308
+ // A non-default preset id always wins; the default id (or no id) is
309
+ // automatic. Only a distro workspace is affected. A workspace the operator
310
+ // opened for Windows access keeps the host preset even here: this is the
311
+ // frame that makes the first mount correct, so skipping it is what the
312
+ // choice means.
313
+ const candidate = request;
314
+ if (candidate === null || typeof candidate !== "object" || typeof candidate.cwd !== "string") {
315
+ return original.call(this, request);
316
+ }
317
+ const requested = typeof candidate.agentPreset === "string" ? candidate.agentPreset : undefined;
318
+ const fallback = defaultPresetId(ctx);
319
+ if (!isDefaultPresetChoice(requested, fallback) || !isWslUnc(candidate.cwd)
320
+ || isWindowsAccessWorkspace(candidate.cwd, windowsAccessList(config.windowsWorkspaces))) {
321
+ return original.call(this, request);
222
322
  }
223
323
  try {
224
- return await original.call(this, sessionId, cwd, checkPersistedIdentity, target);
324
+ return await original.call(this, { ...request, agentPreset: target });
225
325
  }
226
326
  catch (error) {
227
- // A session already stored under another preset rejects a different one.
228
- // Fall back rather than turn adoption into a new failure mode.
229
- if (!String(error?.message ?? "").includes("agent preset"))
327
+ // A session already stored under another preset, or a profile without
328
+ // the WSL preset, must not turn adoption into a failed creation: retry
329
+ // with the caller's own choice and let the event path report the state.
330
+ if (!isPresetAdoptionError(error))
230
331
  throw error;
231
- trace(`creation-time preset "${target}" refused for ${sessionId}; falling back to the recorded one`);
232
- return original.call(this, sessionId, cwd, checkPersistedIdentity, presetId);
332
+ const named = typeof candidate.sessionId === "string" ? candidate.sessionId : "(new session)";
333
+ trace(`creation-time preset "${target}" refused for ${named}; falling back to the recorded one`);
334
+ return original.call(this, request);
233
335
  }
234
336
  };
337
+ publishAutoPresetSeam("active", "agents.createSession is wrapped; distro sessions mount the WSL preset first", "createSession");
235
338
  trace("creation-time preset fix installed");
236
339
  controllerCtx.effect(() => () => {
237
- facade.ensureSession = original;
340
+ facade.createSession = original;
341
+ publishAutoPresetSeam("inactive", "the auto-preset row was disposed");
238
342
  });
239
343
  });
240
344
  // Mount order is not a guarantee: a runner that creates its session during
package/lib/bwrap.d.ts CHANGED
@@ -40,6 +40,14 @@ interface BwrapProfileOptions {
40
40
  * is then the cleanup boundary (ADR 0001).
41
41
  */
42
42
  pidNamespace?: boolean;
43
+ /**
44
+ * Extra Linux directories to bind read-write under `workspace-write` — the
45
+ * toolchain caches and linked-worktree grants the operator configured. The
46
+ * caller has already resolved, filtered and physically checked them
47
+ * (`lib/writable-roots.js`); this module only turns them into mounts.
48
+ * Inert under `read-only`: the mode grants no write outside `/`.
49
+ */
50
+ writableRoots?: readonly string[];
43
51
  }
44
52
  /**
45
53
  * Build the bwrap profile arguments for one file-effect policy, exactly as
@@ -72,6 +80,12 @@ interface BwrapProfileOptions {
72
80
  * resident. Read-only mode mounts no `/tmp` at all, so the option is inert
73
81
  * there.
74
82
  *
83
+ * `options.writableRoots` adds the operator's toolchain grants after the
84
+ * workspace bind. The caller owns their resolution, filtering and physical
85
+ * check (`lib/writable-roots.js`); binding a raw configured string here would
86
+ * let a model-written symlink redirect the grant, so this module never does
87
+ * that itself.
88
+ *
75
89
  * @param policy - the policy to express as bwrap mounts.
76
90
  * @param options - profile options.
77
91
  * @returns profile arguments, before the `--` separator and the command argv.
package/lib/bwrap.js CHANGED
@@ -54,6 +54,12 @@
54
54
  * resident. Read-only mode mounts no `/tmp` at all, so the option is inert
55
55
  * there.
56
56
  *
57
+ * `options.writableRoots` adds the operator's toolchain grants after the
58
+ * workspace bind. The caller owns their resolution, filtering and physical
59
+ * check (`lib/writable-roots.js`); binding a raw configured string here would
60
+ * let a model-written symlink redirect the grant, so this module never does
61
+ * that itself.
62
+ *
57
63
  * @param policy - the policy to express as bwrap mounts.
58
64
  * @param options - profile options.
59
65
  * @returns profile arguments, before the `--` separator and the command argv.
@@ -71,6 +77,11 @@ export function bwrapProfileArgs(policy, options = {}) {
71
77
  args.push("--tmpfs", "/tmp");
72
78
  }
73
79
  args.push("--bind", policy.workspaceRoot, policy.workspaceRoot);
80
+ // The operator's toolchain grants come after the workspace bind, in the
81
+ // deterministic order the resolver returned. They are already filtered to
82
+ // roots with a read-only parent and checked to be physical directories.
83
+ for (const root of options.writableRoots ?? [])
84
+ args.push("--bind", root, root);
74
85
  }
75
86
  if (options.maskWindowsDrive) {
76
87
  args.push("--tmpfs", "/mnt");
@@ -1,7 +1,12 @@
1
1
  /**
2
- * Distro-native working directory in the model's runtime context: rewrite the
3
- * `working-directory:current` entry so a distro session reads its directory as
4
- * the POSIX path its own commands use, not the host UNC spelling.
2
+ * Distro-native model context: rewrite the `working-directory:current` entry so
3
+ * a distro session reads its directory as the POSIX path its own commands use,
4
+ * and adapt the host prompt facts that are wrong or unnecessarily Windows-shaped
5
+ * in a WSL session. The adaptations are deliberately narrow and replaceable:
6
+ * a one-sentence shell note, a POSIX-only replacement for `sandbox:policy`, and
7
+ * suppression of the host's `harness:source` value (its `app.asar`/Windows path
8
+ * is not a readable source checkout from the distro). See
9
+ * docs/UPSTREAM-PROMPT-ADAPTERS.md for the upstream issues that remove them.
5
10
  *
6
11
  * The harness's `working-directory` service prints the session cwd verbatim,
7
12
  * which on this deployment is `\\wsl.localhost\<distro>\...` — the coordinate
@@ -84,8 +89,17 @@ interface CwdPromptScope {
84
89
  interpolate: boolean;
85
90
  text: (context: AssembleRequestContext) => string;
86
91
  }) => unknown;
92
+ /** Register one system-prompt section in this scope's layer, when the harness has the seam. */
93
+ section?: (entry: {
94
+ name: string;
95
+ order: number;
96
+ interpolate: boolean;
97
+ text: string;
98
+ }) => unknown;
87
99
  /** The order constant the harness assigned to a named context family. */
88
100
  getContextOrder?: (family: string) => number | undefined;
101
+ /** The order constant the harness assigned to a named system-prompt section family. */
102
+ getSectionOrder?: (family: string) => number | undefined;
89
103
  };
90
104
  }
91
105
  /** The assembly request context: what a provider's `text` receives. */
@@ -156,6 +170,30 @@ export declare function rewriteQuotedUnc(text: string): string;
156
170
  * @returns the entry text.
157
171
  */
158
172
  export declare function entryText(agent: AssembleRequestContext["agent"], workingDirectory: WorkingDirectorySlice | undefined): string;
173
+ /**
174
+ * One path in the only spelling a WSL model should see. A WSL UNC becomes its
175
+ * POSIX path; an already-POSIX path passes; every Windows spelling returns
176
+ * undefined, so a caller can omit it rather than leak it.
177
+ *
178
+ * @param value - a path from the host policy service or a session header.
179
+ * @returns the POSIX path, or undefined when no POSIX spelling is available.
180
+ */
181
+ export declare function posixPath(value: string | undefined): string | undefined;
182
+ /**
183
+ * The POSIX-only replacement for the host's `sandbox:policy` context. It keeps
184
+ * the host's mode and root (resolved through `ctx.sandboxPolicy`) but never
185
+ * prints a UNC or Windows path. The partial qualifier is conditional because
186
+ * the plugin can be configured with the sandbox off or in danger-full-access.
187
+ *
188
+ * @param policy - the host policy resolution, when the service is available.
189
+ * @param cwd - the session's workspace, used when the policy root is not POSIX.
190
+ * @returns the model-facing policy text.
191
+ */
192
+ export declare function policyText(policy: {
193
+ mode?: string;
194
+ workspaceRoot?: string;
195
+ additionalWritableRoots?: readonly string[];
196
+ } | undefined, cwd: string): string;
159
197
  /**
160
198
  * Mount the rewrite.
161
199
  *