@chopin-ai/workspace 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,26 @@
1
+ import { type Workspace, type WorkspaceProvider } from "./workspace.js";
2
+ /** Runs the container CLI with `args` and resolves with its standard output. */
3
+ export type ContainerCli = (args: readonly string[]) => Promise<string>;
4
+ export interface ContainerWorkspaceOptions {
5
+ /** Image every workspace boots from; it must keep running on its own. */
6
+ image: string;
7
+ /** Names containers and volumes; providers with different prefixes never see each other's workspaces. */
8
+ prefix?: string;
9
+ /** Where the volume is mounted, also the working directory. */
10
+ mountPath?: string;
11
+ limits?: {
12
+ cpus?: number;
13
+ memory?: string;
14
+ pids?: number;
15
+ };
16
+ binary?: string;
17
+ cli?: ContainerCli;
18
+ }
19
+ export declare function containerCli(binary: string): ContainerCli;
20
+ /** One container and one named volume per owner on the local container engine. */
21
+ export declare class ContainerWorkspaceProvider implements WorkspaceProvider {
22
+ #private;
23
+ constructor(options: ContainerWorkspaceOptions);
24
+ open(owner: string): Workspace;
25
+ list(): Promise<Workspace[]>;
26
+ }
@@ -0,0 +1,136 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { promisify } from "node:util";
4
+ import { carried } from "./workspace.js";
5
+ const OWNER_LABEL = "chopin.owner";
6
+ const PROVIDER_LABEL = "chopin.provider";
7
+ const execFileAsync = promisify(execFile);
8
+ export function containerCli(binary) {
9
+ return async (args) => (await execFileAsync(binary, args, { maxBuffer: 16 * 1024 * 1024 })).stdout;
10
+ }
11
+ /** One container and one named volume per owner on the local container engine. */
12
+ export class ContainerWorkspaceProvider {
13
+ #options;
14
+ #queues = new Map();
15
+ // Lifecycle steps check and then act; two at once on one container would both create it.
16
+ #serial = (name, work) => {
17
+ const run = (this.#queues.get(name) ?? Promise.resolve()).then(work, work);
18
+ const tail = run.then(() => { }, () => { }).finally(() => {
19
+ if (this.#queues.get(name) === tail)
20
+ this.#queues.delete(name);
21
+ });
22
+ this.#queues.set(name, tail);
23
+ return run;
24
+ };
25
+ constructor(options) {
26
+ const binary = options.binary ?? "docker";
27
+ this.#options = {
28
+ ...options,
29
+ prefix: options.prefix ?? "chopin",
30
+ mountPath: options.mountPath ?? "/workspace",
31
+ binary,
32
+ cli: options.cli ?? containerCli(binary),
33
+ };
34
+ }
35
+ open(owner) {
36
+ if (owner === "" || /[\r\n]/.test(owner))
37
+ throw new Error("a workspace owner is a non-empty single line");
38
+ return new ContainerWorkspace(owner, this.#options, this.#serial);
39
+ }
40
+ async list() {
41
+ const out = await this.#options.cli([
42
+ "ps", "--all", "--filter", `label=${PROVIDER_LABEL}=${this.#options.prefix}`,
43
+ "--format", `{{.Label "${OWNER_LABEL}"}}`,
44
+ ]);
45
+ // Owners exactly as labelled, spaces included.
46
+ return out.split("\n").filter((owner) => owner !== "").map((owner) => this.open(owner));
47
+ }
48
+ }
49
+ class ContainerWorkspace {
50
+ owner;
51
+ root;
52
+ #name;
53
+ #options;
54
+ #serial;
55
+ constructor(owner, options, serial) {
56
+ this.owner = owner;
57
+ this.root = options.mountPath;
58
+ this.#options = options;
59
+ this.#serial = serial;
60
+ this.#name = `${options.prefix}-${createHash("sha256").update(owner).digest("hex").slice(0, 16)}`;
61
+ }
62
+ async state() {
63
+ const out = await this.#options.cli(["ps", "--all", "--filter", `name=^${this.#name}$`, "--format", "{{.State}}"]);
64
+ const [state] = lines(out);
65
+ if (state === undefined)
66
+ return "absent";
67
+ if (state === "running" || state === "paused")
68
+ return state;
69
+ return "stopped";
70
+ }
71
+ start() {
72
+ return this.#serial(this.#name, () => this.#start());
73
+ }
74
+ async #start() {
75
+ const state = await this.state();
76
+ if (state === "running")
77
+ return;
78
+ if (state === "paused") {
79
+ await this.#cli("unpause", this.#name);
80
+ return;
81
+ }
82
+ if (state === "absent")
83
+ await this.#create();
84
+ await this.#cli("start", this.#name);
85
+ }
86
+ pause() {
87
+ return this.#serial(this.#name, () => this.#pause());
88
+ }
89
+ async #pause() {
90
+ if (await this.state() === "running")
91
+ await this.#cli("pause", this.#name);
92
+ }
93
+ stop() {
94
+ return this.#serial(this.#name, () => this.#stop());
95
+ }
96
+ async #stop() {
97
+ const state = await this.state();
98
+ if (state === "paused")
99
+ await this.#cli("unpause", this.#name);
100
+ if (state === "paused" || state === "running")
101
+ await this.#cli("stop", this.#name);
102
+ }
103
+ destroy() {
104
+ return this.#serial(this.#name, () => this.#destroy());
105
+ }
106
+ async #destroy() {
107
+ if (await this.state() !== "absent")
108
+ await this.#cli("rm", "--force", this.#name);
109
+ await this.#cli("volume", "rm", "--force", this.#name);
110
+ }
111
+ command(argv, env = {}) {
112
+ const carry = carried(argv, env);
113
+ const names = Object.keys(carry.env);
114
+ const inside = names.length === 0 ? argv : ["sh", "-c", carry.exec, "sh", ...argv];
115
+ return {
116
+ argv: [this.#options.binary, "exec", "--interactive", ...names.flatMap((name) => ["--env", name]), this.#name, ...inside],
117
+ env: carry.env,
118
+ };
119
+ }
120
+ async #create() {
121
+ const { prefix, mountPath, image, limits } = this.#options;
122
+ const labels = ["--label", `${PROVIDER_LABEL}=${prefix}`, "--label", `${OWNER_LABEL}=${this.owner}`];
123
+ await this.#cli("volume", "create", ...labels, this.#name);
124
+ await this.#cli("create", "--name", this.#name, ...labels, "--hostname", "workspace", "--mount", `type=volume,src=${this.#name},dst=${mountPath}`, "--workdir", mountPath, "--init", "--security-opt", "no-new-privileges", ...flag("--cpus", limits?.cpus), ...flag("--memory", limits?.memory), ...flag("--pids-limit", limits?.pids), image);
125
+ }
126
+ async #cli(...args) {
127
+ await this.#options.cli(args);
128
+ }
129
+ }
130
+ function flag(name, value) {
131
+ return value === undefined ? [] : [name, String(value)];
132
+ }
133
+ function lines(out) {
134
+ return out.split("\n").map((line) => line.trim()).filter((line) => line !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"./workspace.js";
2
+ export interface DirectoryWorkspaceOptions {
3
+ /**
4
+ * Directories no command in the workspace may read or write, each a real path with no symbolic link on the way,
5
+ * since that is how the sandbox sees them. Only macOS enforces this; elsewhere commands run unconfined.
6
+ */
7
+ hidden?: readonly string[];
8
+ }
9
+ /**
10
+ * Single-user local mode: the workspace is a directory of this machine, used as it is. There is nothing to start or
11
+ * stop, and nothing is ever deleted: the directory is the user's own.
12
+ */
13
+ export declare class DirectoryWorkspaceProvider implements WorkspaceProvider {
14
+ #private;
15
+ constructor(root: string, options?: DirectoryWorkspaceOptions);
16
+ open(owner: string): Workspace;
17
+ /** Nothing here can be reclaimed. */
18
+ list(): Promise<Workspace[]>;
19
+ }
@@ -0,0 +1,45 @@
1
+ import { carried } from "./workspace.js";
2
+ /**
3
+ * Single-user local mode: the workspace is a directory of this machine, used as it is. There is nothing to start or
4
+ * stop, and nothing is ever deleted: the directory is the user's own.
5
+ */
6
+ export class DirectoryWorkspaceProvider {
7
+ #root;
8
+ #hidden;
9
+ constructor(root, options = {}) {
10
+ this.#root = root;
11
+ this.#hidden = options.hidden ?? [];
12
+ }
13
+ open(owner) {
14
+ return {
15
+ owner,
16
+ root: this.#root,
17
+ state: async () => "running",
18
+ start: async () => { },
19
+ pause: async () => { },
20
+ stop: async () => { },
21
+ destroy: async () => {
22
+ throw new Error(`${this.#root} is the user's own directory and is never destroyed`);
23
+ },
24
+ command: (argv, env = {}) => {
25
+ const carry = carried(argv, env);
26
+ return confined({ argv: ["sh", "-c", `cd "$1" && shift && ${carry.exec}`, "sh", this.#root, ...argv], env: carry.env }, this.#hidden);
27
+ },
28
+ };
29
+ }
30
+ /** Nothing here can be reclaimed. */
31
+ async list() {
32
+ return [];
33
+ }
34
+ }
35
+ /** `launch` under a macOS sandbox that denies every file operation within `hidden`, and allows all else. */
36
+ function confined(launch, hidden) {
37
+ if (hidden.length === 0 || process.platform !== "darwin")
38
+ return launch;
39
+ // Paths travel as parameters, so none is ever quoted into the profile.
40
+ const params = hidden.flatMap((path, i) => ["-D", `HIDDEN_${i}=${path}`]);
41
+ const denied = hidden.map((_, i) => `(subpath (param "HIDDEN_${i}"))`).join(" ");
42
+ const profile = `(version 1)(allow default)(deny file-read* file-write* ${denied})`;
43
+ return { argv: ["/usr/bin/sandbox-exec", ...params, "-p", profile, ...launch.argv], env: launch.env };
44
+ }
45
+ //# sourceMappingURL=directory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory.js","sourceRoot":"","sources":["../src/directory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAuD,MAAM,gBAAgB,CAAC;AAU9F;;;GAGG;AACH,MAAM,OAAO,0BAA0B;IAC5B,KAAK,CAAS;IACd,OAAO,CAAoB;IAEpC,YAAY,IAAY,EAAE,OAAO,GAA8B,EAAE;QAC/D,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,KAAa;QAChB,OAAO;YACL,KAAK;YACL,IAAI,EAAE,IAAI,CAAC,KAAK;YAChB,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS;YAC5B,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;YACrB,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;YACrB,IAAI,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;YACpB,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,qDAAqD,CAAC,CAAC;YACtF,CAAC;YACD,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE,EAAE,EAAE;gBAC1B,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;gBACjC,OAAO,QAAQ,CAAC,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,uBAAuB,KAAK,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACxI,CAAC;SACF,CAAC;IACJ,CAAC;IAED,qCAAqC;IACrC,KAAK,CAAC,IAAI;QACR,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AAED,4GAA4G;AAC5G,SAAS,QAAQ,CAAC,MAAc,EAAE,MAAyB;IACzD,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC;IACxE,uEAAuE;IACvE,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1E,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,2BAA2B,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACjF,MAAM,OAAO,GAAG,0DAA0D,MAAM,GAAG,CAAC;IACpF,OAAO,EAAE,IAAI,EAAE,CAAC,uBAAuB,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;AACxG,CAAC"}
@@ -0,0 +1,10 @@
1
+ export { carried, isVariableName, reclaimIdle } from "./workspace.js";
2
+ export type { Launch, Reclaimed, Workspace, WorkspaceProvider, WorkspaceState } from "./workspace.js";
3
+ export { containerCli, ContainerWorkspaceProvider } from "./container.js";
4
+ export type { ContainerCli, ContainerWorkspaceOptions } from "./container.js";
5
+ export { diff, run, snapshot } from "./run.js";
6
+ export type { RunOptions, RunResult } from "./run.js";
7
+ export { DirectoryWorkspaceProvider } from "./directory.js";
8
+ export type { DirectoryWorkspaceOptions } from "./directory.js";
9
+ export { LoopbackWorkspaceProvider } from "./loopback.js";
10
+ export type { LoopbackWorkspaceOptions } from "./loopback.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { carried, isVariableName, reclaimIdle } from "./workspace.js";
2
+ export { containerCli, ContainerWorkspaceProvider } from "./container.js";
3
+ export { diff, run, snapshot } from "./run.js";
4
+ export { DirectoryWorkspaceProvider } from "./directory.js";
5
+ export { LoopbackWorkspaceProvider } from "./loopback.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEtE,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAE/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ // Run as `loopback-connect <port> serve --token <hex>`, where the execution daemon would be: hands the token to the
2
+ // workspace listener on that loopback port, then joins this process's standard input and output to the daemon it starts.
3
+ import { connect } from "node:net";
4
+ const [port, verb, flag, token] = process.argv.slice(2);
5
+ if (!/^\d{1,5}$/.test(port ?? "") || verb !== "serve" || flag !== "--token" || token === undefined) {
6
+ process.stderr.write("usage: loopback-connect <port> serve --token <hex>\n");
7
+ process.exit(2);
8
+ }
9
+ const link = connect(Number(port), "127.0.0.1", () => {
10
+ link.write(`${token}\n`);
11
+ process.stdin.pipe(link);
12
+ link.pipe(process.stdout);
13
+ });
14
+ link.on("error", (error) => process.stderr.write(`loopback-connect: ${error.message}\n`));
15
+ // The daemon's last answer is written out whole before this process ends.
16
+ link.on("close", (failed) => process.stdout.write("", () => process.exit(failed ? 1 : 0)));
17
+ //# sourceMappingURL=loopback-connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback-connect.js","sourceRoot":"","sources":["../src/loopback-connect.ts"],"names":[],"mappings":"AAAA,oHAAoH;AACpH,yHAAyH;AACzH,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAEnC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACxD,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;IACnG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC7E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AACD,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE;IACnD,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,CAAC;IACzB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC,CAAC,CAAC;AACH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC;AAC1F,0EAA0E;AAC1E,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { Workspace, WorkspaceProvider } from "./workspace.js";
2
+ export interface LoopbackWorkspaceOptions {
3
+ /** The port the workspace's listener serves on the loopback address. */
4
+ port: number;
5
+ /** The persistent directory inside the workspace, where work happens. */
6
+ root: string;
7
+ /** The execution daemon as the listener starts it, the one command this workspace runs. */
8
+ daemon: string;
9
+ /** How long `start` waits for the listener to answer; a minute by default. */
10
+ startTimeoutMs?: number;
11
+ }
12
+ /**
13
+ * A workspace someone else runs beside the service on the same network, such as another container of the same pod,
14
+ * whose listener on a loopback port starts the execution daemon for each connection. Starting and stopping it is
15
+ * theirs. The daemon is all it runs: a byte stream carries no exit status, which any other command would need.
16
+ */
17
+ export declare class LoopbackWorkspaceProvider implements WorkspaceProvider {
18
+ #private;
19
+ constructor(options: LoopbackWorkspaceOptions);
20
+ open(owner: string): Workspace;
21
+ /** Nothing here can be reclaimed: whoever runs the workspace does that. */
22
+ list(): Promise<Workspace[]>;
23
+ }
@@ -0,0 +1,65 @@
1
+ import { connect } from "node:net";
2
+ import { extname } from "node:path";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ /** The only address the workspace's listener is reached at: one no other machine can reach. */
6
+ const LOOPBACK = "127.0.0.1";
7
+ // The connector next to this module, run by Node as it is: compiled, or as source while testing.
8
+ const CONNECTOR = fileURLToPath(new URL(`./loopback-connect${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
9
+ /**
10
+ * A workspace someone else runs beside the service on the same network, such as another container of the same pod,
11
+ * whose listener on a loopback port starts the execution daemon for each connection. Starting and stopping it is
12
+ * theirs. The daemon is all it runs: a byte stream carries no exit status, which any other command would need.
13
+ */
14
+ export class LoopbackWorkspaceProvider {
15
+ #options;
16
+ constructor(options) {
17
+ if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65_535)
18
+ throw new Error(`${options.port} is no port`);
19
+ this.#options = options;
20
+ }
21
+ open(owner) {
22
+ const { port, root, daemon, startTimeoutMs = 60_000 } = this.#options;
23
+ const at = `${LOOPBACK}:${port}`;
24
+ const managed = async () => {
25
+ throw new Error(`the workspace at ${at} is started and stopped by whoever runs it`);
26
+ };
27
+ return {
28
+ owner,
29
+ root,
30
+ state: async () => ((await answers(port)) ? "running" : "stopped"),
31
+ start: async () => {
32
+ const deadline = Date.now() + startTimeoutMs;
33
+ while (!(await answers(port))) {
34
+ if (Date.now() >= deadline)
35
+ throw new Error(`no workspace listener answered at ${at}`);
36
+ await sleep(250);
37
+ }
38
+ },
39
+ pause: managed,
40
+ stop: managed,
41
+ destroy: managed,
42
+ command: (argv, env = {}) => {
43
+ if (argv.length !== 1 || argv[0] !== daemon || Object.keys(env).length > 0) {
44
+ throw new Error(`the workspace at ${at} runs only its execution daemon, ${daemon}`);
45
+ }
46
+ return { argv: [process.execPath, CONNECTOR, String(port)], env: {} };
47
+ },
48
+ };
49
+ }
50
+ /** Nothing here can be reclaimed: whoever runs the workspace does that. */
51
+ async list() {
52
+ return [];
53
+ }
54
+ }
55
+ /** Whether a listener accepts a connection on the loopback `port` now. */
56
+ function answers(port) {
57
+ return new Promise((resolve) => {
58
+ const probe = connect(port, LOOPBACK, () => {
59
+ probe.destroy();
60
+ resolve(true);
61
+ });
62
+ probe.on("error", () => resolve(false));
63
+ });
64
+ }
65
+ //# sourceMappingURL=loopback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.js","sourceRoot":"","sources":["../src/loopback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,OAA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AAC,IAAI,CAAC,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1C,CAAC,CAAC,CAAC;AACL,CAAC"}
package/dist/run.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { Workspace } from "./workspace.js";
2
+ export interface RunResult {
3
+ stdout: string;
4
+ stderr: string;
5
+ /** As a shell reports it: 128 plus the signal's number for a program a signal ended. */
6
+ exitCode: number;
7
+ }
8
+ export interface RunOptions {
9
+ /** Written to the program's standard input, which is closed either way. */
10
+ input?: string;
11
+ }
12
+ /**
13
+ * Runs a program inside the running workspace and collects all of its output, which callers take whole, such as a
14
+ * patch. However the program ends is a result, as is a program the workspace could not start, which ends with the
15
+ * code its launcher gives, such as 127 for one not found; only a launcher that could not start at all is an error.
16
+ */
17
+ export declare function run(workspace: Workspace, argv: readonly string[], options?: RunOptions): Promise<RunResult>;
18
+ /**
19
+ * The workspace's git work tree as a tree object, untracked files under the root included, for `diff` to compare
20
+ * against later.
21
+ * @returns `undefined` when the workspace root is not in a git work tree.
22
+ */
23
+ export declare function snapshot(workspace: Workspace): Promise<string | undefined>;
24
+ /**
25
+ * Everything changed under the workspace root since `base`, a `snapshot`, or since the last commit without one,
26
+ * untracked files included, as a binary patch with paths relative to the root: the bytes git wrote, whatever the
27
+ * files' encodings.
28
+ * @returns `undefined` when the workspace root is not in a git work tree.
29
+ */
30
+ export declare function diff(workspace: Workspace, base?: string): Promise<Uint8Array | undefined>;
package/dist/run.js ADDED
@@ -0,0 +1,85 @@
1
+ import { execFile } from "node:child_process";
2
+ import { constants } from "node:os";
3
+ /**
4
+ * Runs a program inside the running workspace and collects all of its output, which callers take whole, such as a
5
+ * patch. However the program ends is a result, as is a program the workspace could not start, which ends with the
6
+ * code its launcher gives, such as 127 for one not found; only a launcher that could not start at all is an error.
7
+ */
8
+ export async function run(workspace, argv, options = {}) {
9
+ const result = await execute(workspace, argv, options);
10
+ return { ...result, stdout: result.stdout.toString("utf8") };
11
+ }
12
+ /** `run`, keeping standard output as the bytes the program wrote. */
13
+ function execute(workspace, argv, options) {
14
+ const { argv: [binary, ...args], env } = workspace.command(argv);
15
+ return new Promise((resolve, reject) => {
16
+ const child = execFile(binary, args, { env: { ...process.env, ...env }, maxBuffer: Infinity, encoding: "buffer" }, (error, stdout, stderr) => {
17
+ const ended = (exitCode) => resolve({ stdout, stderr: stderr.toString("utf8"), exitCode });
18
+ if (error === null)
19
+ return ended(0);
20
+ if (typeof error.code === "number")
21
+ return ended(error.code);
22
+ const signal = error.signal === undefined || error.signal === null ? undefined : constants.signals[error.signal];
23
+ if (signal === undefined)
24
+ return reject(error);
25
+ ended(128 + signal);
26
+ });
27
+ // A program that exits without reading its input fails through its exit code, not through the pipe.
28
+ child.stdin?.on("error", () => { });
29
+ child.stdin?.end(options.input);
30
+ });
31
+ }
32
+ /**
33
+ * The workspace's git work tree as a tree object, untracked files under the root included, for `diff` to compare
34
+ * against later.
35
+ * @returns `undefined` when the workspace root is not in a git work tree.
36
+ */
37
+ export async function snapshot(workspace) {
38
+ return (await inWorkTree(workspace, "git write-tree"))?.toString("utf8").trim();
39
+ }
40
+ /**
41
+ * Everything changed under the workspace root since `base`, a `snapshot`, or since the last commit without one,
42
+ * untracked files included, as a binary patch with paths relative to the root: the bytes git wrote, whatever the
43
+ * files' encodings.
44
+ * @returns `undefined` when the workspace root is not in a git work tree.
45
+ */
46
+ export function diff(workspace, base) {
47
+ const since = '"${1:-$(git rev-parse --verify --quiet HEAD || git hash-object -t tree /dev/null)}"';
48
+ // Plumbing, so the user's diff settings, such as color, prefixes or external tools, never shape the patch.
49
+ const command = `git diff-index --cached --relative --patch --binary ${since}`;
50
+ return inWorkTree(workspace, command, ...(base === undefined ? [] : [base]));
51
+ }
52
+ /**
53
+ * Runs `command` with everything under the root staged in a throwaway index, so the work tree's own index stays
54
+ * untouched; a root inside a larger repository leaves the rest of it as the real index has it. The throwaway index
55
+ * starts as a copy of the real one, whose cached file stats spare rehashing unchanged files, and files are staged
56
+ * as a commit in this repository would record them. What git cannot stage, such as an unreadable file or a nested
57
+ * repository without a commit, is left out.
58
+ */
59
+ async function inWorkTree(workspace, command, ...args) {
60
+ const script = [
61
+ // No repository only when nothing names one: no GIT_DIR and no `.git` up the tree. Any git failure past that is
62
+ // an error, even one git would also give outside a repository.
63
+ 'if [ -z "${GIT_DIR:-}" ]; then dir=$(pwd -P); while [ ! -e "$dir/.git" ]; do [ "$dir" = / ] && exit 3; dir=${dir%/*}; dir=${dir:-/}; done; fi',
64
+ // The workspace may belong to another user than the one running this.
65
+ 'n=${GIT_CONFIG_COUNT:-0}; export GIT_CONFIG_COUNT=$((n + 1)) "GIT_CONFIG_KEY_$n=safe.directory" "GIT_CONFIG_VALUE_$n=*"',
66
+ 'inside=$(git rev-parse --is-inside-work-tree) || exit',
67
+ '[ "$inside" = true ] || exit 3',
68
+ 'index="$(git rev-parse --git-path index)"',
69
+ 'export GIT_INDEX_FILE="$(mktemp)"',
70
+ "trap 'rm -f \"$GIT_INDEX_FILE\"' EXIT",
71
+ // The copy keeps the index's own time, which git needs to notice a file changed within the same second.
72
+ 'if [ -f "$index" ]; then cp -p "$index" "$GIT_INDEX_FILE"; else git read-tree --empty; fi',
73
+ "git add --all --ignore-errors -- .",
74
+ // Status 1: some path was left out.
75
+ 'staged=$?; [ "$staged" -le 1 ] || exit "$staged"',
76
+ command,
77
+ ].join("\n");
78
+ const result = await execute(workspace, ["sh", "-c", script, "sh", ...args], {});
79
+ if (result.exitCode === 3)
80
+ return undefined;
81
+ if (result.exitCode !== 0)
82
+ throw new Error(`git failed in ${workspace.root}: ${result.stderr.trim()}`);
83
+ return result.stdout;
84
+ }
85
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EA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AC/D,+IAA+I;QAC/I,sEAAsE;QACtE,yHAAyH;QACzH,uDAAuD;QACvD,gCAAgC;QAChC,2CAA2C;QAC3C,mCAAmC;QACnC,uCAAuC;QACvC,wGAAwG;QACxG,2FAA2F;QAC3F,oCAAoC;QACpC,oCAAoC;QACpC,kDAAkD;QAClD,OAAO;KACR,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;IACjF,IAAI,MAAM,CAAC,QAAQ,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5C,IAAI,MAAM,CAAC,QAAQ,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,SAAS,CAAC,IAAI,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvG,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC"}
@@ -0,0 +1,58 @@
1
+ export type WorkspaceState = "absent" | "stopped" | "paused" | "running";
2
+ /** One owner's isolated machine. Its volume outlives every state but `destroy`. */
3
+ export interface Workspace {
4
+ readonly owner: string;
5
+ /** The persistent directory inside the workspace, where work happens. */
6
+ readonly root: string;
7
+ state(): Promise<WorkspaceState>;
8
+ /** Brings the workspace to running: creates, boots or resumes it as needed. */
9
+ start(): Promise<void>;
10
+ /** Freezes its processes and keeps their memory; `start` resumes them. */
11
+ pause(): Promise<void>;
12
+ /** Releases compute and keeps the volume; `start` boots it again. */
13
+ stop(): Promise<void>;
14
+ /** Deletes the workspace together with its volume. */
15
+ destroy(): Promise<void>;
16
+ /** How to run `argv` inside the running workspace, in its root, with stdio attached and `env` set. */
17
+ command(argv: readonly string[], env?: Readonly<Record<string, string>>): Launch;
18
+ }
19
+ /** A command line, and what to add to the environment it is started with. */
20
+ export interface Launch {
21
+ argv: string[];
22
+ env: Record<string, string>;
23
+ }
24
+ /**
25
+ * Whether a workspace can carry a variable of this name: a portable name, other than `_`, which a shell sets anew
26
+ * for every command it starts, and those under which workspaces carry variables.
27
+ */
28
+ export declare function isVariableName(name: string): boolean;
29
+ /**
30
+ * Carries variables into a workspace with no value on any command line and none of their names in the launcher's own
31
+ * environment, where a PATH or a preload would change how the launcher runs. Each travels under a name of its own,
32
+ * and `exec`, a shell command that runs "$@", sets it under its name; one the shell does not keep as given, such as
33
+ * a variable it computes or holds read-only, stops the command from starting rather than reaching it changed.
34
+ */
35
+ export declare function carried(argv: readonly string[], env: Readonly<Record<string, string>>): {
36
+ env: Record<string, string>;
37
+ exec: string;
38
+ };
39
+ export interface WorkspaceProvider {
40
+ /** The owner's workspace. Nothing is created until it is started. */
41
+ open(owner: string): Workspace;
42
+ /** Every workspace this provider has created and not destroyed. */
43
+ list(): Promise<Workspace[]>;
44
+ }
45
+ /** What a sweep did: the owners whose workspaces it stopped, and those it could not, with why. */
46
+ export interface Reclaimed {
47
+ stopped: string[];
48
+ failed: {
49
+ owner: string;
50
+ error: unknown;
51
+ }[];
52
+ }
53
+ /**
54
+ * Stops the workspaces of owners idle for at least `idleMs`, a few at a time, keeping their volumes. An owner is
55
+ * asked again right before its workspace stops, so work that began meanwhile keeps it; a workspace that fails to
56
+ * stop keeps no other from stopping.
57
+ */
58
+ export declare function reclaimIdle(provider: WorkspaceProvider, lastActive: (owner: string) => number | undefined, idleMs: number, now?: number): Promise<Reclaimed>;
@@ -0,0 +1,67 @@
1
+ const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
+ const CARRIED = "CHOPIN_ENV_";
3
+ /**
4
+ * Whether a workspace can carry a variable of this name: a portable name, other than `_`, which a shell sets anew
5
+ * for every command it starts, and those under which workspaces carry variables.
6
+ */
7
+ export function isVariableName(name) {
8
+ return VARIABLE.test(name) && name !== "_" && !name.startsWith(CARRIED);
9
+ }
10
+ /**
11
+ * Carries variables into a workspace with no value on any command line and none of their names in the launcher's own
12
+ * environment, where a PATH or a preload would change how the launcher runs. Each travels under a name of its own,
13
+ * and `exec`, a shell command that runs "$@", sets it under its name; one the shell does not keep as given, such as
14
+ * a variable it computes or holds read-only, stops the command from starting rather than reaching it changed.
15
+ */
16
+ export function carried(argv, env) {
17
+ if (argv.length === 0)
18
+ throw new Error("there is no command to run");
19
+ const names = Object.keys(env);
20
+ if (names.length === 0)
21
+ return { env: {}, exec: 'exec "$@"' };
22
+ const invalid = names.find((name) => !isVariableName(name));
23
+ if (invalid !== undefined)
24
+ throw new Error(`${JSON.stringify(invalid)} is not a variable name a workspace can carry`);
25
+ const carrier = (name) => CARRIED + name;
26
+ // A subshell tries each export first, since a failing one would end the shell itself.
27
+ const set = names.map((name) => {
28
+ const value = `"$${carrier(name)}"`;
29
+ return `{ (export ${name}=${value}) 2>/dev/null && export ${name}=${value} && [ "$${name}" = ${value} ] || { echo "the workspace's shell keeps its own ${name}" >&2; exit 126; }; }`;
30
+ });
31
+ return {
32
+ env: Object.fromEntries(names.map((name) => [carrier(name), env[name]])),
33
+ exec: `${set.join(" && ")} && unset ${names.map(carrier).join(" ")} && exec "$@"`,
34
+ };
35
+ }
36
+ /**
37
+ * Stops the workspaces of owners idle for at least `idleMs`, a few at a time, keeping their volumes. An owner is
38
+ * asked again right before its workspace stops, so work that began meanwhile keeps it; a workspace that fails to
39
+ * stop keeps no other from stopping.
40
+ */
41
+ export async function reclaimIdle(provider, lastActive, idleMs, now = Date.now()) {
42
+ const reclaimed = { stopped: [], failed: [] };
43
+ const idle = (owner) => {
44
+ const active = lastActive(owner);
45
+ return active === undefined || now - active >= idleMs;
46
+ };
47
+ const queue = (await provider.list()).filter((workspace) => idle(workspace.owner));
48
+ const worker = async () => {
49
+ for (let workspace = queue.shift(); workspace !== undefined; workspace = queue.shift()) {
50
+ try {
51
+ const state = await workspace.state();
52
+ if ((state !== "running" && state !== "paused") || !idle(workspace.owner))
53
+ continue;
54
+ await workspace.stop();
55
+ reclaimed.stopped.push(workspace.owner);
56
+ }
57
+ catch (error) {
58
+ reclaimed.failed.push({ owner: workspace.owner, error });
59
+ }
60
+ }
61
+ };
62
+ await Promise.all(Array.from({ length: RECLAIMING_AT_ONCE }, worker));
63
+ return reclaimed;
64
+ }
65
+ /** How many workspaces a sweep stops at once, so an engine with many is not flooded. */
66
+ const RECLAIMING_AT_ONCE = 8;
67
+ //# sourceMappingURL=workspace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace.js","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AA0BA,MAAM,QAAQ,GAAG,0BAA0B,CAAC;AAC5C,MAAM,OAAO,GAAG,aAAa,CAAC;AAE9B;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAC1E,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,IAAuB,EAAE,GAAqC;IACpF,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IACrE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAC9D,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5D,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,+CAA+C,CAAC,CAAC;IACtH,MAAM,OAA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,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IACnF,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE;QACxB,KAAK,IAAI,SAAS,GAAG,KAAK,CAAC,KAAK,EAAE,EAAE,SAAS,KAAK,SAAS,EAAE,SAAS,GAAG,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;YACvF,IAAI,CAAC;gBACH,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;gBACtC,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;oBAAE,SAAS;gBACpF,MAAM,SAAS,CAAC,IAAI,EAAE,CAAC;gBACvB,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;YAC1C,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAC3D,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IACF,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACtE,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,wFAAwF;AACxF,MAAM,kBAAkB,GAAG,CAAC,CAAC"}
@@ -0,0 +1,16 @@
1
+ #!/bin/sh
2
+ # Serves this workspace to an agent service beside it on the same network, as LoopbackWorkspaceProvider reaches it:
3
+ # loopback-listener.sh <port> <daemon>
4
+ # Each connection starts the execution daemon with the connection as its standard input and output, under the token
5
+ # the connection's first line carries; one that sends nothing was only checking the listener is up. It listens on the
6
+ # loopback address alone, which nothing outside this network can reach. The daemon's path, and this script's, have no
7
+ # space, colon or comma, which the relay's addresses would split on.
8
+ set -eu
9
+ if [ "${1-}" = --connection ]; then
10
+ read -r token || exit 0
11
+ case $token in '' | *[!0-9a-f]*) exit 2 ;; esac
12
+ exec "$2" serve --token "$token"
13
+ fi
14
+ case ${1-}:${2-} in '' | :* | *[!0-9]*:* | *:) echo "usage: loopback-listener.sh <port> <daemon>" >&2; exit 2 ;; esac
15
+ # Once a connection stops sending, the daemon is given time to answer what it was asked; it ends sooner by itself.
16
+ exec socat -t 10 "TCP-LISTEN:$1,bind=127.0.0.1,reuseaddr,fork" "EXEC:$0 --connection $2"
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@chopin-ai/workspace",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Per-user workspace lifecycle interface with directory and container implementations",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/CodePrometheus/chopin-ai.git",
9
+ "directory": "packages/workspace"
10
+ },
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=24.8.0"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "loopback-listener.sh"
24
+ ]
6
25
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.