@exagone313/dsh-podman 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/cordis.patch.yml +3 -1
  2. package/dist/approval-reasons.d.ts +37 -0
  3. package/dist/approval-reasons.js +128 -0
  4. package/dist/approval-template-summary.d.ts +8 -0
  5. package/dist/approval-template-summary.js +163 -0
  6. package/dist/approval.d.ts +8 -4
  7. package/dist/approval.js +104 -10
  8. package/dist/client/ContainerCard.js +8 -2
  9. package/dist/client/container-card-controller.d.ts +13 -5
  10. package/dist/client/container-card-controller.js +60 -24
  11. package/dist/client/container-card-create-config.d.ts +23 -0
  12. package/dist/client/container-card-create-config.js +48 -0
  13. package/dist/client/container-card-create-modal.d.ts +9 -1
  14. package/dist/client/container-card-create-modal.js +37 -41
  15. package/dist/client/container-card-create-volume.d.ts +10 -0
  16. package/dist/client/container-card-create-volume.js +34 -0
  17. package/dist/client/container-card-dialog-styles.d.ts +4 -2
  18. package/dist/client/container-card-dialog-styles.js +47 -4
  19. package/dist/client/container-card-edit-modal.d.ts +5 -1
  20. package/dist/client/container-card-edit-modal.js +55 -19
  21. package/dist/client/container-card-editors.d.ts +9 -0
  22. package/dist/client/container-card-editors.js +300 -43
  23. package/dist/client/container-card-form.d.ts +2 -1
  24. package/dist/client/container-card-form.js +26 -8
  25. package/dist/client/container-card-images.js +9 -31
  26. package/dist/client/container-card-mount-actions.d.ts +12 -0
  27. package/dist/client/container-card-mount-actions.js +35 -0
  28. package/dist/client/container-card-mount-sources.d.ts +34 -0
  29. package/dist/client/container-card-mount-sources.js +180 -0
  30. package/dist/client/container-card-names.d.ts +2 -0
  31. package/dist/client/container-card-names.js +12 -0
  32. package/dist/client/container-card-row.d.ts +16 -1
  33. package/dist/client/container-card-row.js +69 -25
  34. package/dist/client/container-card-secrets.d.ts +2 -0
  35. package/dist/client/container-card-secrets.js +60 -17
  36. package/dist/client/container-card-shared.d.ts +17 -9
  37. package/dist/client/container-card-shared.js +122 -93
  38. package/dist/client/container-card-styles.d.ts +6 -0
  39. package/dist/client/container-card-styles.js +22 -0
  40. package/dist/client/container-card-table-styles.d.ts +2 -1
  41. package/dist/client/container-card-table-styles.js +14 -0
  42. package/dist/client/container-card-templates.d.ts +81 -0
  43. package/dist/client/container-card-templates.js +1004 -0
  44. package/dist/client/container-card-toast.js +1 -1
  45. package/dist/client/container-card-volumes.js +6 -20
  46. package/dist/client/container-card-workspace.d.ts +10 -2
  47. package/dist/client/container-card-workspace.js +98 -5
  48. package/dist/client/container-template-ui.d.ts +163 -0
  49. package/dist/client/container-template-ui.js +579 -0
  50. package/dist/client/download.d.ts +1 -0
  51. package/dist/client/download.js +23 -0
  52. package/dist/client/image-facts.d.ts +18 -0
  53. package/dist/client/image-facts.js +44 -0
  54. package/dist/client/index.js +13478 -3438
  55. package/dist/client/locales.d.ts +1 -1
  56. package/dist/client/locales.js +120 -0
  57. package/dist/client/podman-containers.js +47 -18
  58. package/dist/client/podman-terminal-guide.js +4 -2
  59. package/dist/client/podman-terminal.js +4 -2
  60. package/dist/client/template-client.d.ts +9 -0
  61. package/dist/client/template-client.js +52 -0
  62. package/dist/client/template-protocol.d.ts +60 -0
  63. package/dist/client/template-protocol.js +4 -0
  64. package/dist/client/terminal-errors.d.ts +11 -0
  65. package/dist/client/terminal-errors.js +26 -0
  66. package/dist/client/terminal-protocol.d.ts +5 -0
  67. package/dist/client/terminal-protocol.js +5 -0
  68. package/dist/client/terminal-styles.d.ts +2 -1
  69. package/dist/client/terminal-styles.js +9 -1
  70. package/dist/client/terminal-transport.d.ts +17 -2
  71. package/dist/client/terminal-transport.js +31 -8
  72. package/dist/client/tool-presentations.d.ts +32 -0
  73. package/dist/client/tool-presentations.js +33 -0
  74. package/dist/client/tool-views.js +17 -7
  75. package/dist/client/workspace-target.d.ts +54 -0
  76. package/dist/client/workspace-target.js +86 -0
  77. package/dist/container-template.d.ts +153 -0
  78. package/dist/container-template.js +1058 -0
  79. package/dist/generated/version.d.ts +2 -2
  80. package/dist/generated/version.js +2 -2
  81. package/dist/grpc/proto/dshguest/v1/guest.proto +11 -0
  82. package/dist/guest-rpc.d.ts +1 -0
  83. package/dist/guest-rpc.js +12 -0
  84. package/dist/index.js +7 -1
  85. package/dist/mount-enums.d.ts +2 -0
  86. package/dist/mount-enums.js +17 -0
  87. package/dist/mount-order.d.ts +14 -0
  88. package/dist/mount-order.js +49 -0
  89. package/dist/project-path.d.ts +14 -0
  90. package/dist/project-path.js +25 -0
  91. package/dist/template-apply.d.ts +21 -0
  92. package/dist/template-apply.js +102 -0
  93. package/dist/template-files.d.ts +23 -0
  94. package/dist/template-files.js +186 -0
  95. package/dist/template-image.d.ts +22 -0
  96. package/dist/template-image.js +80 -0
  97. package/dist/template-route.d.ts +9 -0
  98. package/dist/template-route.js +278 -0
  99. package/dist/terminal-route.js +49 -7
  100. package/dist/tool-defs.js +27 -1
  101. package/dist/tool-handlers.js +69 -1
  102. package/dist/tool-params.d.ts +38 -0
  103. package/dist/tool-params.js +30 -0
  104. package/docs/README.md +4 -3
  105. package/docs/architecture.md +42 -12
  106. package/docs/architecture.zh.md +22 -8
  107. package/docs/configuration.md +19 -20
  108. package/docs/configuration.zh.md +3 -4
  109. package/docs/development-prompt.md +49 -45
  110. package/docs/development-prompt.zh.md +47 -43
  111. package/docs/development.md +46 -28
  112. package/docs/development.zh.md +60 -46
  113. package/docs/uninstall.md +3 -3
  114. package/docs/uninstall.zh.md +2 -2
  115. package/docs/usage.md +155 -23
  116. package/docs/usage.zh.md +104 -14
  117. package/package.json +6 -5
@@ -0,0 +1,80 @@
1
+ // SPDX-FileCopyrightText: 2026 Elouan Martinet <exa@elou.world>
2
+ //
3
+ // SPDX-License-Identifier: MIT
4
+ // Template images: a loaded template either refers to one of the fixed base
5
+ // images or to a deterministic custom image built from it. This module is the
6
+ // one place that turns that plan into orchestrator calls, so the load popup, the
7
+ // agent tool and the export path agree on when a build runs and which image a
8
+ // container names.
9
+ import { effectiveImage, templateImageId, templateImagePlan, } from "./container-template.js";
10
+ // ensureTemplateImage makes the image a template needs available:
11
+ //
12
+ // - a base-only template names the base and provisions it when the plan says
13
+ // it is missing, through the same control the settings image row uses;
14
+ // - a template image whose packages or parent differ from the listed image is
15
+ // rebuilt with the template's package list;
16
+ // - a matching image is reused, unless the caller forces a rebuild.
17
+ //
18
+ // A template that no longer needs its custom image (all of its packages turned
19
+ // out to be base built-ins) has that image removed once it is unreferenced. An
20
+ // image a container still uses is left alone: removeImage refuses it, and that
21
+ // refusal is the "still referenced" signal rather than a load failure.
22
+ export async function ensureTemplateImage(resolver, options) {
23
+ const effective = effectiveImage(options.template);
24
+ const templateId = await templateImageId(options.name, options.path);
25
+ const images = options.images ??
26
+ ((await resolver.control("listImages", {}))
27
+ .images ?? []);
28
+ const plan = templateImagePlan(effective, templateId, images);
29
+ if (effective.kind === "base") {
30
+ const listed = images.some((image) => image.imageId === templateId);
31
+ const removed = listed
32
+ ? await removeImageIfUnreferenced(resolver, templateId)
33
+ : false;
34
+ // The base itself is the image: a plan that finds it missing gets it built,
35
+ // and a Rebuild provisions it again. The control is the one the settings
36
+ // row would run, chosen the same way: a deployment that publishes bases
37
+ // pulls them, a local deployment rebuilds them. A refusal (for example a
38
+ // base still used by a container) propagates as the build failure.
39
+ const built = plan.needsBuild || options.force === true;
40
+ if (built) {
41
+ const baseRow = images.find((image) => image.imageId === effective.base);
42
+ if (baseRow?.basePublic === true) {
43
+ await resolver.control("pullBaseImage", { name: effective.base });
44
+ }
45
+ else {
46
+ await resolver.control("rebuildBaseImage", { name: effective.base });
47
+ }
48
+ }
49
+ return {
50
+ imageId: effective.base,
51
+ plan,
52
+ built,
53
+ removed,
54
+ ...(listed ? { supersededImageId: templateId } : {}),
55
+ };
56
+ }
57
+ // A current image is reused unless the caller asked for a forced rebuild;
58
+ // an image the plan already says must be built is built either way.
59
+ if (!plan.needsBuild && options.force !== true) {
60
+ return { imageId: templateId, plan, built: false, removed: false };
61
+ }
62
+ await resolver.control("buildImage", {
63
+ imageId: templateId,
64
+ parent: effective.base,
65
+ packages: effective.packages,
66
+ });
67
+ return { imageId: templateId, plan, built: true, removed: false };
68
+ }
69
+ // removeImageIfUnreferenced deletes an image whose template no longer needs it.
70
+ // A refusal means a container (or another image) still references it, which is
71
+ // not an error: the image is simply kept until the reference goes away.
72
+ async function removeImageIfUnreferenced(resolver, imageId) {
73
+ try {
74
+ await resolver.control("removeImage", { imageId });
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
@@ -0,0 +1,9 @@
1
+ import { type TemplateApplyView, type TemplateBuildView, type TemplateInspectionView, type TemplatePublishView } from "./client/template-protocol.js";
2
+ import type { WorkspaceResolver } from "./workspace-binding.js";
3
+ export declare function runTemplateRequest(resolver: WorkspaceResolver, workspaceRegistry: any, raw: Record<string, unknown>): Promise<TemplateInspectionView | TemplateBuildView | TemplateApplyView | TemplatePublishView>;
4
+ export declare function handleTemplateRequest(request: Request, resolver: WorkspaceResolver, workspaceRegistry: any): Promise<Response>;
5
+ /**
6
+ * Register the template route. It is served below the harness API path, so the
7
+ * carrier applies its Host/Origin fence and browser authentication first.
8
+ */
9
+ export declare function registerTemplateRoute(ctx: any, resolver: WorkspaceResolver, workspaceRegistry: any): void;
@@ -0,0 +1,278 @@
1
+ // SPDX-FileCopyrightText: 2026 Elouan Martinet <exa@elou.world>
2
+ //
3
+ // SPDX-License-Identifier: MIT
4
+ // The load-template popup's host half: one authenticated route below the
5
+ // harness API path that lists a project's templates, inspects one (including an
6
+ // upload), builds the image it needs, creates a container from it, and
7
+ // publishes the ports of a template whose replace the edit editor applied.
8
+ //
9
+ // Listing and reading happen on the dsh host, from the read-only view of the
10
+ // projects root the same way dsh's own directory picker reads a workspace
11
+ // directory; saving a template goes through the workspace's guest agent
12
+ // instead, because the host view is read-only.
13
+ import { effectiveImage, parseContainerTemplate, renderContainerTemplate, templateImageId, templateImagePlan, templateRequirements, } from "./container-template.js";
14
+ import { TEMPLATES_PATH, } from "./client/template-protocol.js";
15
+ import { containerMountView } from "./card-route.js";
16
+ import { ensureTemplateImage } from "./template-image.js";
17
+ import { applyContainerTemplate, publishTemplatePorts, } from "./template-apply.js";
18
+ import { listProjectTemplates, MAX_TEMPLATE_BYTES, projectDirectoryExists, readProjectTemplate, TemplateFileError, templateFileName, templatePathForName, workspaceForSlug, } from "./template-files.js";
19
+ import { TemplateError } from "./container-template.js";
20
+ import { portProtocolFromProto } from "./publish-port.js";
21
+ function jsonResponse(status, body) {
22
+ return new Response(JSON.stringify(body), {
23
+ status,
24
+ headers: { "content-type": "application/json" },
25
+ });
26
+ }
27
+ function stringField(value) {
28
+ return typeof value === "string" ? value : "";
29
+ }
30
+ async function listImages(resolver) {
31
+ const result = (await resolver.control("listImages", {}));
32
+ return result.images ?? [];
33
+ }
34
+ async function listSecrets(resolver) {
35
+ const result = (await resolver.control("listSecrets", {}));
36
+ return (result.secrets ?? []).map((secret) => secret.name ?? "");
37
+ }
38
+ async function listVolumes(resolver) {
39
+ const result = (await resolver.control("listVolumes", {}));
40
+ return (result.volumes ?? []).map((volume) => volume.name ?? "");
41
+ }
42
+ // resolveTemplate turns a request into the template document to inspect: an
43
+ // uploaded YAML string, or the project's own file. The path is the absolute
44
+ // host path the template has (or would have once saved), which is what its
45
+ // image id hashes.
46
+ async function resolveTemplate(workspace, request) {
47
+ if (typeof request.yaml === "string") {
48
+ const name = templateFileName(request.name);
49
+ return {
50
+ name,
51
+ path: templatePathForName(workspace.projectPath, name),
52
+ yaml: request.yaml,
53
+ };
54
+ }
55
+ return await readProjectTemplate(workspace.projectPath, request.name);
56
+ }
57
+ // loadTemplate reads and parses the requested document, enforcing the size
58
+ // limit every operation shares.
59
+ async function loadTemplate(workspace, request) {
60
+ const file = await resolveTemplate(workspace, request);
61
+ if (Buffer.byteLength(file.yaml, "utf8") > MAX_TEMPLATE_BYTES) {
62
+ throw new TemplateError("the template is too large");
63
+ }
64
+ return { file, template: parseContainerTemplate(file.yaml) };
65
+ }
66
+ // inspectTemplate parses one template and computes everything the popup shows:
67
+ // its effective image, whether a build is needed, and the workspace
68
+ // requirements (missing project directories, volumes and secrets). The image
69
+ // and volume lists are read here, on every call: a plan is never computed from
70
+ // a list the caller kept from an earlier snapshot, so an image or volume the
71
+ // maintainer removed is missing from this plan immediately.
72
+ async function inspectTemplate(resolver, workspace, request) {
73
+ const { file, template } = await loadTemplate(workspace, request);
74
+ const imageId = await templateImageId(file.name, file.path);
75
+ const effective = effectiveImage(template);
76
+ const [listed, volumes] = await Promise.all([
77
+ listImages(resolver),
78
+ listVolumes(resolver),
79
+ ]);
80
+ const plan = templateImagePlan(effective, imageId, listed);
81
+ const warnings = await requirements(resolver, workspace, template, volumes);
82
+ const inspection = {
83
+ name: file.name,
84
+ path: file.path,
85
+ yaml: renderContainerTemplate(template),
86
+ template,
87
+ imageId: plan.imageId,
88
+ image: plan,
89
+ warnings,
90
+ };
91
+ return { inspection, template, file };
92
+ }
93
+ async function requirements(resolver, workspace, template, volumes) {
94
+ const projectsRoot = resolver.getConfig().projectsRoot;
95
+ const projects = new Map();
96
+ for (const mount of template.spec.mounts) {
97
+ if (mount.kind !== "project" || projects.has(mount.project))
98
+ continue;
99
+ projects.set(mount.project, await projectDirectoryExists(projectsRoot, mount.project));
100
+ }
101
+ const secrets = await listSecrets(resolver);
102
+ return templateRequirements(template, {
103
+ projectExists: (project) => projects.get(project) === true,
104
+ secrets,
105
+ volumes,
106
+ });
107
+ }
108
+ // containerView is the snapshot shape for one container; it mirrors the card's
109
+ // own projection so the popup's reload and the card agree.
110
+ function containerView(row, projectsRoot) {
111
+ const published = (row?.publishedPorts ?? []);
112
+ return {
113
+ containerName: stringField(row?.containerName),
114
+ workspaceSlug: stringField(row?.workspaceSlug),
115
+ imageId: stringField(row?.imageId),
116
+ status: stringField(row?.status),
117
+ createdAt: stringField(row?.createdAt),
118
+ mounts: (row?.mounts ?? []).map((mount) => containerMountView(mount, projectsRoot)),
119
+ paths: Array.isArray(row?.paths) ? row.paths.map(String) : [],
120
+ env: (row?.env ?? {}),
121
+ secretEnv: (row?.secretEnv ?? {}),
122
+ publishedPorts: published.map((port) => ({
123
+ protocol: portProtocolFromProto(stringField(port?.protocol)) ??
124
+ stringField(port?.protocol),
125
+ port: Number(port?.port ?? 0),
126
+ address: stringField(port?.address),
127
+ hostPort: Number(port?.hostPort ?? 0),
128
+ endpoint: stringField(port?.endpoint),
129
+ })),
130
+ };
131
+ }
132
+ export async function runTemplateRequest(resolver, workspaceRegistry, raw) {
133
+ const op = stringField(raw.op);
134
+ const workspace = workspaceForSlug(workspaceRegistry, resolver.getConfig().projectsRoot, stringField(raw.workspace));
135
+ if (op === "inspect") {
136
+ const { inspection } = await inspectTemplate(resolver, workspace, {
137
+ name: stringField(raw.name),
138
+ ...(typeof raw.yaml === "string" ? { yaml: raw.yaml } : {}),
139
+ });
140
+ return inspection;
141
+ }
142
+ if (op === "build") {
143
+ const { inspection, template, file } = await inspectTemplate(resolver, workspace, {
144
+ name: stringField(raw.name),
145
+ ...(typeof raw.yaml === "string" ? { yaml: raw.yaml } : {}),
146
+ });
147
+ // No pre-fetched list: the build decides from the images present when it
148
+ // runs, then the plan is re-read once the build finished so a failed or
149
+ // removed image is reported as missing rather than ready. `force` is the
150
+ // Rebuild action: it rebuilds a current image instead of reusing it.
151
+ const ensured = await ensureTemplateImage(resolver, {
152
+ name: file.name,
153
+ path: file.path,
154
+ template,
155
+ force: raw.force === true,
156
+ });
157
+ const refreshed = await listImages(resolver);
158
+ const plan = templateImagePlan(effectiveImage(template), ensured.imageId, refreshed);
159
+ return {
160
+ ...inspection,
161
+ imageId: ensured.imageId,
162
+ image: plan,
163
+ built: ensured.built,
164
+ removed: ensured.removed,
165
+ };
166
+ }
167
+ if (op === "apply") {
168
+ const { inspection, template, file } = await inspectTemplate(resolver, workspace, {
169
+ name: stringField(raw.name),
170
+ ...(typeof raw.yaml === "string" ? { yaml: raw.yaml } : {}),
171
+ });
172
+ const ensured = await ensureTemplateImage(resolver, {
173
+ name: file.name,
174
+ path: file.path,
175
+ template,
176
+ });
177
+ const container = stringField(raw.container);
178
+ const result = await applyContainerTemplate(resolver, {
179
+ workspaceSlug: workspace.workspaceSlug,
180
+ projectName: workspace.projectName,
181
+ template,
182
+ imageId: ensured.imageId,
183
+ ...(container === "" ? {} : { container }),
184
+ });
185
+ return {
186
+ container: containerView(result.row, resolver.getConfig().projectsRoot),
187
+ imageId: ensured.imageId,
188
+ warnings: [
189
+ ...inspection.warnings.map(warningText).filter((text) => text !== ""),
190
+ ...result.warnings,
191
+ ],
192
+ };
193
+ }
194
+ if (op === "publish") {
195
+ // A template-sourced replace publishes its ports after the edit editor's
196
+ // Apply updated the container; nothing else happens here.
197
+ const container = stringField(raw.container);
198
+ if (container === "") {
199
+ throw new TemplateFileError("a container is required to publish a template's ports");
200
+ }
201
+ const { template } = await loadTemplate(workspace, {
202
+ name: stringField(raw.name),
203
+ ...(typeof raw.yaml === "string" ? { yaml: raw.yaml } : {}),
204
+ });
205
+ return {
206
+ warnings: await publishTemplatePorts(resolver, {
207
+ workspaceSlug: workspace.workspaceSlug,
208
+ container,
209
+ template,
210
+ }),
211
+ };
212
+ }
213
+ throw new TemplateFileError(`unknown template operation ${JSON.stringify(op)}`);
214
+ }
215
+ function warningText(warning) {
216
+ switch (warning.kind) {
217
+ case "project_missing":
218
+ return `project mount ${JSON.stringify(warning.project)}: directory not found`;
219
+ case "secret_missing":
220
+ return `secret ${JSON.stringify(warning.secret)}: not found`;
221
+ case "secret_env_missing":
222
+ return `secret ${JSON.stringify(warning.secret)} for ${warning.env}: not found`;
223
+ case "volume_missing":
224
+ return `volume ${JSON.stringify(warning.volume)}: not found`;
225
+ }
226
+ }
227
+ export async function handleTemplateRequest(request, resolver, workspaceRegistry) {
228
+ try {
229
+ if (request.method === "GET") {
230
+ const url = new URL(request.url);
231
+ const workspace = workspaceForSlug(workspaceRegistry, resolver.getConfig().projectsRoot, url.searchParams.get("workspace") ?? "");
232
+ const templates = (await listProjectTemplates(workspace.projectPath)).map((template) => ({
233
+ name: template.name,
234
+ path: template.path,
235
+ yaml: template.yaml,
236
+ }));
237
+ const listing = { templates };
238
+ return jsonResponse(200, listing);
239
+ }
240
+ if (request.method !== "POST") {
241
+ return new Response("method not allowed", { status: 405 });
242
+ }
243
+ let body;
244
+ try {
245
+ body = await request.json();
246
+ }
247
+ catch {
248
+ return jsonResponse(400, { error: "invalid JSON body" });
249
+ }
250
+ if (body === null || typeof body !== "object") {
251
+ return jsonResponse(400, { error: "a template request is required" });
252
+ }
253
+ const result = await runTemplateRequest(resolver, workspaceRegistry, body);
254
+ return jsonResponse(200, result);
255
+ }
256
+ catch (error) {
257
+ if (error instanceof TemplateError || error instanceof TemplateFileError) {
258
+ return jsonResponse(400, { error: error.message });
259
+ }
260
+ return jsonResponse(500, {
261
+ error: error instanceof Error ? error.message : String(error),
262
+ });
263
+ }
264
+ }
265
+ /**
266
+ * Register the template route. It is served below the harness API path, so the
267
+ * carrier applies its Host/Origin fence and browser authentication first.
268
+ */
269
+ export function registerTemplateRoute(ctx, resolver, workspaceRegistry) {
270
+ ctx.inject(["connection"], (connectionCtx) => {
271
+ connectionCtx.connection.fetch.register({
272
+ path: TEMPLATES_PATH,
273
+ methods: ["GET", "POST"],
274
+ requestBody: "buffered",
275
+ fetch: (request) => handleTemplateRequest(request, resolver, workspaceRegistry),
276
+ });
277
+ });
278
+ }
@@ -5,13 +5,18 @@
5
5
  // path, so the carrier applies its Host/Origin fence and browser authentication
6
6
  // before any handler runs; the handlers themselves only speak the terminal
7
7
  // protocol declared in client/terminal-protocol.ts.
8
- import { TERMINAL_PATH, TERMINAL_RETAINED_PATH, TERMINAL_SHELLS_PATH, TERMINAL_TARGET_PATH, } from "./client/terminal-protocol.js";
8
+ import { TERMINAL_PATH, TERMINAL_RETAINED_PATH, TERMINAL_SHELLS_PATH, TERMINAL_TARGET_PATH, WORKSPACE_PENDING_CODE, } from "./client/terminal-protocol.js";
9
9
  import { discoverShells } from "./terminal-shells.js";
10
10
  import { workspaceSlug } from "./workspace-binding.js";
11
11
  const MIN_COLS = 2;
12
12
  const MAX_COLS = 500;
13
13
  const MIN_ROWS = 1;
14
14
  const MAX_ROWS = 200;
15
+ // A page load may ask before the session or its workspace has registered: the
16
+ // target route can wait for it, but only within this budget and by polling at
17
+ // this interval.
18
+ const MAX_TARGET_WAIT_MS = 5_000;
19
+ const TARGET_POLL_INTERVAL_MS = 100;
15
20
  function json(status, body) {
16
21
  return new Response(JSON.stringify(body), {
17
22
  status,
@@ -29,6 +34,30 @@ function integer(raw, min, max) {
29
34
  return undefined;
30
35
  return value;
31
36
  }
37
+ // How long the target route may wait for the session's workspace. Absent or
38
+ // malformed means no wait; the maximum bounds one browser request.
39
+ function targetWait(raw) {
40
+ if (raw === null || raw === "")
41
+ return 0;
42
+ const value = Number(raw);
43
+ if (!Number.isFinite(value) || value <= 0)
44
+ return 0;
45
+ return Math.min(Math.floor(value), MAX_TARGET_WAIT_MS);
46
+ }
47
+ // Sleep between polls, cut short when the browser goes away.
48
+ function targetDelay(ms, signal) {
49
+ if (ms <= 0)
50
+ return Promise.resolve();
51
+ return new Promise((resolve) => {
52
+ const timer = setTimeout(done, ms);
53
+ function done() {
54
+ clearTimeout(timer);
55
+ signal.removeEventListener("abort", done);
56
+ resolve();
57
+ }
58
+ signal.addEventListener("abort", done, { once: true });
59
+ });
60
+ }
32
61
  // The workspace's mirrored path under the projects root, or the session's own
33
62
  // working directory when the request names no workspace.
34
63
  function workspaceCwd(ctx, workspaceRegistry, projectsRoot, projectName, sessionId) {
@@ -72,15 +101,28 @@ function sessionWorkspace(ctx, workspaceRegistry, projectsRoot, sessionId) {
72
101
  ? undefined
73
102
  : { workspace: best.projectName, workspaceSlug: best.slug };
74
103
  }
75
- function handleTarget(request, ctx, resolver, workspaceRegistry) {
76
- const sessionId = new URL(request.url).searchParams.get("sessionId") ?? "";
104
+ async function handleTarget(request, ctx, resolver, workspaceRegistry) {
105
+ const url = new URL(request.url);
106
+ const sessionId = url.searchParams.get("sessionId") ?? "";
107
+ // Missing ids are misuse, never retried; an unresolvable session may only be
108
+ // one that is still registering.
77
109
  if (sessionId === "")
78
110
  return json(400, { error: "sessionId is required" });
79
- const target = sessionWorkspace(ctx, workspaceRegistry, resolver.getConfig().projectsRoot, sessionId);
80
- if (target === undefined) {
81
- return json(400, { error: "Cannot determine this session's workspace" });
111
+ const projectsRoot = resolver.getConfig().projectsRoot;
112
+ const deadline = Date.now() + targetWait(url.searchParams.get("wait"));
113
+ for (;;) {
114
+ const target = sessionWorkspace(ctx, workspaceRegistry, projectsRoot, sessionId);
115
+ if (target !== undefined)
116
+ return json(200, target);
117
+ const remaining = deadline - Date.now();
118
+ if (remaining <= 0 || request.signal.aborted)
119
+ break;
120
+ await targetDelay(Math.min(TARGET_POLL_INTERVAL_MS, remaining), request.signal);
82
121
  }
83
- return json(200, target);
122
+ return json(409, {
123
+ error: "Cannot determine this session's workspace",
124
+ code: WORKSPACE_PENDING_CODE,
125
+ });
84
126
  }
85
127
  function controlOf(body) {
86
128
  if (typeof body?.terminalId !== "string" || body.terminalId === "") {
package/dist/tool-defs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Elouan Martinet <exa@elou.world>
2
2
  //
3
3
  // SPDX-License-Identifier: MIT
4
- import { containerBashParameters, containerEditParameters, containerExecParameters, containerGlobParameters, containerGrepParameters, containerListParameters, containerMountAddParameters, containerMountListParameters, containerMountRemoveParameters, containerMountUpdateParameters, containerPathAddParameters, containerPathRemoveParameters, containerPathSetParameters, containerPublishPortParameters, containerReadParameters, containerRecreateParameters, containerRemoveParameters, containerSecretAddParameters, containerSecretRemoveParameters, containerStartParameters, containerUnpublishPortParameters, containerWriteParameters, daemonListParameters, daemonLogsParameters, daemonRestartParameters, daemonStartParameters, daemonStopParameters, imageBuildParameters, imageGetParameters, imageListParameters, imageRebuildAllParameters, imageRebuildParameters, imageRemoveParameters, secretCreateParameters, secretListParameters, secretRemoveParameters, volumeCreateParameters, volumeListParameters, volumeRemoveParameters, } from "./tool-params.js";
4
+ import { containerBashParameters, containerEditParameters, containerExecParameters, containerGlobParameters, containerGrepParameters, containerListParameters, containerMountAddParameters, containerMountListParameters, containerMountRemoveParameters, containerMountUpdateParameters, containerPathAddParameters, containerPathRemoveParameters, containerPathSetParameters, containerPublishPortParameters, containerReadParameters, containerRecreateParameters, containerRemoveParameters, containerSecretAddParameters, containerSecretRemoveParameters, containerStartParameters, containerTemplateExportParameters, containerTemplateLoadParameters, containerTemplateSaveParameters, containerUnpublishPortParameters, containerWriteParameters, daemonListParameters, daemonLogsParameters, daemonRestartParameters, daemonStartParameters, daemonStopParameters, imageBuildParameters, imageGetParameters, imageListParameters, imageRebuildAllParameters, imageRebuildParameters, imageRemoveParameters, secretCreateParameters, secretListParameters, secretRemoveParameters, volumeCreateParameters, volumeListParameters, volumeRemoveParameters, } from "./tool-params.js";
5
5
  export function defineTool(definition) {
6
6
  return definition;
7
7
  }
@@ -35,6 +35,20 @@ export const TOOLS = [
35
35
  },
36
36
  { name: "image_remove", parameters: imageRemoveParameters, approval: true },
37
37
  { name: "container_list", parameters: containerListParameters },
38
+ {
39
+ name: "container_template_load",
40
+ parameters: containerTemplateLoadParameters,
41
+ approval: true,
42
+ },
43
+ {
44
+ name: "container_template_export",
45
+ parameters: containerTemplateExportParameters,
46
+ },
47
+ {
48
+ name: "container_template_save",
49
+ parameters: containerTemplateSaveParameters,
50
+ approval: true,
51
+ },
38
52
  {
39
53
  name: "container_start",
40
54
  parameters: containerStartParameters,
@@ -139,6 +153,9 @@ export const TOOL_DESCRIPTIONS = {
139
153
  image_rebuild_all: "Rebuild every stored image in dependency order (base first), skipping any image whose rebuild fails and its dependents. Requires approval: rebuilding replaces the images' contents.",
140
154
  image_remove: "Remove a built custom image by short name. Base images are managed from the settings. Requires approval: removing deletes the image so containers using it must be recreated from another image.",
141
155
  container_list: "List the containers of the current workspace, including the default container that is started on demand.",
156
+ container_template_load: "Load a container template from the project's .dsh-podman directory: build its image when needed, then create the container or replace an existing one. The workspace project mount is always added read-write. The template's mounts replace the container's mounts; the environment, secret environment and PATH additions it declares replace those groups, and groups it leaves undeclared keep their current values. Requires approval: creating or replacing a container changes what runs in the workspace.",
157
+ container_template_export: "Export a container of the current workspace as a container-template YAML document (its root base image, recursive package union, mounts, environment, secrets, PATH additions and ports). Returns the YAML string and changes nothing.",
158
+ container_template_save: "Validate a container-template YAML document and save it through the workspace container's guest agent into the project's .dsh-podman directory, creating the directory when missing. Requires approval: it writes a file into the project.",
142
159
  container_start: "Start a container in the current workspace. Named containers are created with exactly the mounts you pass — the project directory is not mounted automatically. The default container always keeps its workspace project mount. Pass paths to replace the container's PATH additions.",
143
160
  container_recreate: "Recreate a container in the current workspace, keeping its current image when no image is given, optionally with new project mounts. Pass paths to replace the container's PATH additions. Requires approval: recreating replaces the running container.",
144
161
  container_remove: "Remove a container from the current workspace.",
@@ -182,6 +199,15 @@ export const TOOL_UI = {
182
199
  image_rebuild_all: { title: "Rebuild all images", kind: "execute" },
183
200
  image_remove: { title: "Remove image", kind: "delete" },
184
201
  container_list: { title: "List containers", kind: "search" },
202
+ container_template_load: {
203
+ title: "Load container template",
204
+ kind: "execute",
205
+ },
206
+ container_template_export: {
207
+ title: "Export container template",
208
+ kind: "read",
209
+ },
210
+ container_template_save: { title: "Save container template", kind: "edit" },
185
211
  container_start: { title: "Start container", kind: "execute" },
186
212
  container_recreate: { title: "Recreate container", kind: "execute" },
187
213
  container_remove: { title: "Remove container", kind: "delete" },
@@ -1,8 +1,12 @@
1
1
  // SPDX-FileCopyrightText: 2026 Elouan Martinet <exa@elou.world>
2
2
  //
3
3
  // SPDX-License-Identifier: MIT
4
- import { bytesText, currentCwd, fsError, guestCwd, outputLines, resolveToolBinding, runExec, sessionWorkspaceSlug, streamLines, unaryGuest, } from "./guest-rpc.js";
4
+ import { bytesText, currentCwd, fsError, guestCwd, outputLines, resolveToolBinding, runExec, sessionWorkspaceSlug, streamLines, unaryGuest, writeGuestTemplate, } from "./guest-rpc.js";
5
5
  import { inferMountKind, mountsFromInput, projectMountDestinationReason, } from "./mount-input.js";
6
+ import { exportContainerTemplate, parseContainerTemplate, renderContainerTemplate, } from "./container-template.js";
7
+ import { applyContainerTemplate } from "./template-apply.js";
8
+ import { readProjectTemplate, TemplateFileError, templateFileName, workspaceForCwd, } from "./template-files.js";
9
+ import { ensureTemplateImage } from "./template-image.js";
6
10
  import { mergeDefaultEnv } from "./container-env.js";
7
11
  import { isPtcContainer } from "./container-kind.js";
8
12
  import { publicContainerResult, publicContainers, publicDaemon, publicImage, publicMount, publicPublishedPort, } from "./public.js";
@@ -16,6 +20,21 @@ const GLOB_MAX_RESULTS = 100;
16
20
  // VCS metadata directories ripgrep must never descend into for a discovery
17
21
  // listing (`--no-ignore --hidden` would otherwise surface them).
18
22
  const GLOB_VCS_EXCLUDES = [".git", ".svn", ".hg", ".bzr", ".jj", ".sl"];
23
+ // templateFromContainer exports one container of a workspace as a template,
24
+ // refusing a name that does not belong to the workspace (or the reserved PTC
25
+ // container). The export and save tools share this lookup.
26
+ async function templateFromContainer(resolver, workspace, container) {
27
+ const [containers, images] = await Promise.all([
28
+ resolver.control("listContainers", {}),
29
+ resolver.control("listImages", {}),
30
+ ]);
31
+ const row = (containers.containers ?? []).find((candidate) => candidate.workspaceSlug === workspace.workspaceSlug &&
32
+ candidate.containerName === container);
33
+ if (row === undefined || isPtcContainer(row)) {
34
+ throw containerNotFound(container, workspace.workspaceSlug);
35
+ }
36
+ return exportContainerTemplate(row, images.images ?? [], workspace.projectName);
37
+ }
19
38
  // failOnSearchError turns a ripgrep failure into a tool error: exit code 2 means
20
39
  // ripgrep rejected the pattern or could not read the tree, and returning an
21
40
  // empty result would present that as a successful search.
@@ -159,6 +178,55 @@ export const toolHandlers = {
159
178
  ...publicContainers(rows.filter((row) => row.containerName !== "default")),
160
179
  ];
161
180
  },
181
+ container_template_load: async (resolver, input, exec) => {
182
+ const workspace = await workspaceForCwd(resolver.registry, resolver.getConfig().projectsRoot, currentCwd(exec));
183
+ const file = await readProjectTemplate(workspace.projectPath, input.template);
184
+ const template = parseContainerTemplate(file.yaml);
185
+ const ensured = await ensureTemplateImage(resolver, {
186
+ name: file.name,
187
+ path: file.path,
188
+ template,
189
+ });
190
+ const container = typeof input.container === "string"
191
+ ? input.container
192
+ : undefined;
193
+ const applied = await applyContainerTemplate(resolver, {
194
+ workspaceSlug: workspace.workspaceSlug,
195
+ projectName: workspace.projectName,
196
+ template,
197
+ imageId: ensured.imageId,
198
+ ...(container === undefined || container === "" ? {} : { container }),
199
+ });
200
+ return {
201
+ ...publicContainerResult(applied.row),
202
+ template: file.name,
203
+ imageId: ensured.imageId,
204
+ ...(ensured.built ? { built: true } : {}),
205
+ ...(applied.warnings.length > 0 ? { warnings: applied.warnings } : {}),
206
+ };
207
+ },
208
+ container_template_export: async (resolver, input, exec) => {
209
+ const workspace = await workspaceForCwd(resolver.registry, resolver.getConfig().projectsRoot, currentCwd(exec));
210
+ return (await templateFromContainer(resolver, workspace, input.container))
211
+ .yaml;
212
+ },
213
+ container_template_save: async (resolver, input, exec) => {
214
+ const name = templateFileName(input.name);
215
+ // `container` is required in the tool schema, but the harness does not
216
+ // validate raw JSON-schema arguments, so name the missing source instead of
217
+ // letting an empty string fall through to a lookup that cannot match it.
218
+ if (typeof input.container !== "string" || input.container === "") {
219
+ throw new TemplateFileError('the "container" parameter is required: pass the source container name');
220
+ }
221
+ const workspace = await workspaceForCwd(resolver.registry, resolver.getConfig().projectsRoot, currentCwd(exec));
222
+ // Saving no longer takes a document: export the named container here, then
223
+ // write that canonical YAML through the default container's guest agent,
224
+ // which is the one that always has the project mounted.
225
+ const exported = await templateFromContainer(resolver, workspace, input.container);
226
+ const binding = await resolver.resolve(currentCwd(exec), exec?.signal);
227
+ const path = await writeGuestTemplate(binding, workspace.projectPath, name, renderContainerTemplate(exported.template));
228
+ return { container: input.container, name, path };
229
+ },
162
230
  container_start: async (resolver, input, exec) => {
163
231
  const mounts = mountsFromInput(input.mounts, resolver.getConfig().projectsRoot);
164
232
  const slug = await sessionWorkspaceSlug(resolver, currentCwd(exec));
@@ -849,3 +849,41 @@ export declare const daemonLogsParameters: {
849
849
  };
850
850
  required: string[];
851
851
  };
852
+ export declare const containerTemplateLoadParameters: {
853
+ type: string;
854
+ properties: {
855
+ template: {
856
+ type: string;
857
+ description: string;
858
+ };
859
+ container: {
860
+ type: string;
861
+ description: string;
862
+ };
863
+ };
864
+ required: string[];
865
+ };
866
+ export declare const containerTemplateExportParameters: {
867
+ type: string;
868
+ properties: {
869
+ container: {
870
+ type: string;
871
+ description: string;
872
+ };
873
+ };
874
+ required: string[];
875
+ };
876
+ export declare const containerTemplateSaveParameters: {
877
+ type: string;
878
+ properties: {
879
+ container: {
880
+ type: string;
881
+ description: string;
882
+ };
883
+ name: {
884
+ type: string;
885
+ description: string;
886
+ };
887
+ };
888
+ required: string[];
889
+ };