@archildata/just-bash 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Archil, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # @archildata/just-bash
2
+
3
+ Archil filesystem adapter for [just-bash](https://github.com/anthropics/just-bash) - run bash commands against Archil distributed filesystems.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @archildata/just-bash @archildata/client just-bash
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { ArchilClient } from '@archildata/client';
15
+ import { ArchilFs } from '@archildata/just-bash';
16
+ import { Bash } from 'just-bash';
17
+
18
+ // Connect to Archil
19
+ const client = await ArchilClient.connect({
20
+ region: 'aws-us-east-1',
21
+ diskName: 'myaccount/mydisk',
22
+ authToken: 'adt_xxx', // or omit for IAM auth
23
+ });
24
+
25
+ // Create filesystem adapter
26
+ const fs = new ArchilFs(client);
27
+
28
+ // Use with just-bash
29
+ const bash = new Bash({ fs });
30
+
31
+ // Run commands
32
+ const result = await bash.exec('ls -la /');
33
+ console.log(result.stdout);
34
+
35
+ // Read files
36
+ const content = await bash.exec('cat /myfile.txt');
37
+
38
+ // Close when done
39
+ await client.close();
40
+ ```
41
+
42
+ ## Writing Files (Delegations)
43
+
44
+ Archil uses a delegation system for write access. Before writing, you need to "checkout" the directory or file:
45
+
46
+ ```typescript
47
+ // Get the inode ID for a path
48
+ const inodeId = await fs.resolveInodeId('/mydir');
49
+
50
+ // Checkout to get write access
51
+ await client.checkout(inodeId, false); // false = don't force
52
+
53
+ // Now you can write
54
+ await bash.exec('echo "hello" > /mydir/newfile.txt');
55
+
56
+ // Release the delegation when done
57
+ await client.checkin(inodeId);
58
+ ```
59
+
60
+ For shared/multi-client access, use `--force` to revoke existing delegations:
61
+
62
+ ```typescript
63
+ await client.checkout(inodeId, true); // force = true
64
+ ```
65
+
66
+ ## With User Context
67
+
68
+ Specify a Unix user context for permission checks:
69
+
70
+ ```typescript
71
+ const fs = new ArchilFs(client, {
72
+ user: { uid: 1000, gid: 1000 }
73
+ });
74
+ ```
75
+
76
+ ## Interactive Shell
77
+
78
+ The package includes an interactive shell for testing:
79
+
80
+ ```bash
81
+ ARCHIL_REGION=aws-us-east-1 ARCHIL_DISK=myaccount/mydisk ARCHIL_TOKEN=xxx npx @archildata/just-bash
82
+ ```
83
+
84
+ Shell commands:
85
+ - Standard bash commands (`ls`, `cat`, `echo`, etc.)
86
+ - `archil checkout [--force] <path>` - Acquire write delegation
87
+ - `archil checkin <path>` - Release write delegation
88
+ - `archil help` - Show archil commands
89
+
90
+ ## API
91
+
92
+ ### `ArchilFs`
93
+
94
+ ```typescript
95
+ new ArchilFs(client: ArchilClient, options?: { user?: UnixUser })
96
+ ```
97
+
98
+ #### Read Operations
99
+ - `readFile(path, encoding?)` - Read file as string
100
+ - `readFileBuffer(path)` - Read file as Uint8Array
101
+ - `readdir(path)` - List directory entries
102
+ - `stat(path)` / `lstat(path)` - Get file stats
103
+ - `exists(path)` - Check if path exists
104
+ - `readlink(path)` - Read symlink target
105
+
106
+ #### Write Operations
107
+ - `writeFile(path, content)` - Write file
108
+ - `appendFile(path, content)` - Append to file
109
+ - `mkdir(path, options?)` - Create directory
110
+ - `rm(path, options?)` - Delete file/directory
111
+ - `cp(src, dest, options?)` - Copy
112
+ - `mv(src, dest)` - Move/rename
113
+ - `symlink(target, path)` - Create symlink
114
+
115
+ #### Utilities
116
+ - `resolveInodeId(path)` - Get inode ID for delegation operations
117
+ - `clearCache()` - Clear path cache
118
+
119
+ ## Debugging
120
+
121
+ Enable debug logging with the `DEBUG` environment variable:
122
+
123
+ ```bash
124
+ # Enable archil:fs logging
125
+ DEBUG=archil:fs node myapp.js
126
+
127
+ # Enable all archil debug logging
128
+ DEBUG=archil:* node myapp.js
129
+ ```
130
+
131
+ ## Performance
132
+
133
+ - **Path-to-inode caching** - Avoids repeated directory lookups
134
+ - **Chunked reads** - Large files read in 4 MiB chunks
135
+ - **Native protocol** - Direct Archil protocol access, no FUSE overhead
136
+
137
+ ## License
138
+
139
+ MIT
package/bin/shell.ts ADDED
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Interactive just-bash shell with Archil filesystem
4
+ *
5
+ * Usage:
6
+ * ARCHIL_REGION=aws-us-east-1 ARCHIL_DISK=myaccount/mydisk ARCHIL_TOKEN=xxx npx tsx bin/shell.ts
7
+ */
8
+
9
+ import * as readline from "readline";
10
+ import { ArchilClient } from "@archildata/client";
11
+ import { Bash } from "just-bash";
12
+ import { ArchilFs } from "../src/ArchilFs.js";
13
+
14
+ async function main() {
15
+ const region = process.env.ARCHIL_REGION;
16
+ const diskName = process.env.ARCHIL_DISK;
17
+ const authToken = process.env.ARCHIL_TOKEN;
18
+ const logLevel = process.env.ARCHIL_LOG_LEVEL; // e.g., "debug", "info", "warn", "error", "trace"
19
+
20
+ if (!region || !diskName) {
21
+ console.error("Missing required environment variables:");
22
+ console.error(" ARCHIL_REGION - e.g., aws-us-east-1");
23
+ console.error(" ARCHIL_DISK - e.g., myaccount/mydisk");
24
+ console.error(" ARCHIL_TOKEN - (optional) auth token, defaults to IAM");
25
+ console.error(" ARCHIL_LOG_LEVEL - (optional) log level: trace, debug, info, warn, error");
26
+ console.error("");
27
+ console.error("Usage:");
28
+ console.error(" ARCHIL_REGION=aws-us-east-1 ARCHIL_DISK=myaccount/mydisk npx tsx bin/shell.ts");
29
+ console.error("");
30
+ console.error("For debug logging:");
31
+ console.error(" ARCHIL_LOG_LEVEL=debug ARCHIL_REGION=... ARCHIL_DISK=... npx tsx bin/shell.ts");
32
+ process.exit(1);
33
+ }
34
+
35
+ console.log("Connecting to Archil...");
36
+ console.log(` Region: ${region}`);
37
+ console.log(` Disk: ${diskName}`);
38
+ console.log(` Auth: ${authToken ? "token" : "IAM"}`);
39
+ if (logLevel) {
40
+ console.log(` Log level: ${logLevel}`);
41
+ }
42
+ console.log("");
43
+
44
+ let client: ArchilClient;
45
+ try {
46
+ client = await ArchilClient.connect({
47
+ region,
48
+ diskName,
49
+ authToken: authToken || undefined,
50
+ logLevel,
51
+ });
52
+ console.log("Connected!");
53
+ } catch (err) {
54
+ console.error("Failed to connect:", err instanceof Error ? err.message : err);
55
+ process.exit(1);
56
+ }
57
+
58
+ // Create filesystem adapter
59
+ const fs = new ArchilFs(client);
60
+
61
+ // Create bash environment
62
+ const bash = new Bash({ fs });
63
+
64
+ // Cleanup function to release delegations and close connection
65
+ let cleaningUp = false;
66
+ const cleanup = async (signal?: string) => {
67
+ if (cleaningUp) return;
68
+ cleaningUp = true;
69
+
70
+ if (signal) {
71
+ console.log(`\nReceived ${signal}, cleaning up...`);
72
+ } else {
73
+ console.log("\nGoodbye!");
74
+ }
75
+
76
+ try {
77
+ // close() releases all delegations and cleans up resources
78
+ const released = await client.close();
79
+ if (released > 0) {
80
+ console.log(`Released ${released} delegation${released > 1 ? 's' : ''}`);
81
+ }
82
+ } catch (err) {
83
+ console.error("Error during cleanup:", err instanceof Error ? err.message : err);
84
+ }
85
+
86
+ process.exit(0);
87
+ };
88
+
89
+ // Handle signals for graceful shutdown
90
+ process.on('SIGINT', () => cleanup('SIGINT'));
91
+ process.on('SIGTERM', () => cleanup('SIGTERM'));
92
+ process.on('SIGHUP', () => cleanup('SIGHUP'));
93
+
94
+ console.log("");
95
+ console.log("=== Archil just-bash shell ===");
96
+ console.log("Type bash commands to interact with the filesystem.");
97
+ console.log("Special commands:");
98
+ console.log(" archil checkout [--force] <path> - Acquire write delegation");
99
+ console.log(" archil checkin <path> - Release write delegation");
100
+ console.log(" archil list-delegations - Show held delegations");
101
+ console.log(" archil help - Show archil commands");
102
+ console.log("Type 'exit' or Ctrl+D to quit.");
103
+ console.log("");
104
+
105
+ // Create readline interface for interactive input
106
+ const rl = readline.createInterface({
107
+ input: process.stdin,
108
+ output: process.stdout,
109
+ prompt: "archil$ ",
110
+ });
111
+
112
+ let cwd = "/";
113
+
114
+ const prompt = () => {
115
+ rl.setPrompt(`archil:${cwd}$ `);
116
+ rl.prompt();
117
+ };
118
+
119
+ prompt();
120
+
121
+ // Helper to resolve a path relative to cwd
122
+ const resolvePath = (path: string): string => {
123
+ if (path.startsWith("/")) {
124
+ return path;
125
+ }
126
+ return cwd === "/" ? "/" + path : cwd + "/" + path;
127
+ };
128
+
129
+ // Handle archil checkout/checkin commands
130
+ const handleArchilCommand = async (command: string): Promise<boolean> => {
131
+ const parts = command.split(/\s+/);
132
+ if (parts[0] !== "archil") {
133
+ return false;
134
+ }
135
+
136
+ const subcommand = parts[1];
137
+ const targetPath = parts[2];
138
+
139
+ if (subcommand === "checkout") {
140
+ // Parse flags and path
141
+ const args = parts.slice(2);
142
+ const force = args.includes("--force") || args.includes("-f");
143
+ const pathArg = args.find(a => !a.startsWith("-"));
144
+
145
+ if (!pathArg) {
146
+ console.error("Usage: archil checkout [--force|-f] <path>");
147
+ return true;
148
+ }
149
+ const fullPath = resolvePath(pathArg);
150
+ try {
151
+ const inodeId = await fs.resolveInodeId(fullPath);
152
+ await client.checkout(inodeId, force);
153
+ console.log(`Checked out: ${fullPath} (inode ${inodeId})${force ? " (forced)" : ""}`);
154
+ } catch (err) {
155
+ console.error(`Failed to checkout ${fullPath}:`, err instanceof Error ? err.message : err);
156
+ }
157
+ return true;
158
+ }
159
+
160
+ if (subcommand === "checkin") {
161
+ if (!targetPath) {
162
+ console.error("Usage: archil checkin <path>");
163
+ return true;
164
+ }
165
+ const fullPath = resolvePath(targetPath);
166
+ try {
167
+ const inodeId = await fs.resolveInodeId(fullPath);
168
+ await client.checkin(inodeId);
169
+ console.log(`Checked in: ${fullPath} (inode ${inodeId})`);
170
+ } catch (err) {
171
+ console.error(`Failed to checkin ${fullPath}:`, err instanceof Error ? err.message : err);
172
+ }
173
+ return true;
174
+ }
175
+
176
+ if (subcommand === "list-delegations" || subcommand === "delegations") {
177
+ try {
178
+ const delegations = client.listDelegations();
179
+ if (delegations.length === 0) {
180
+ console.log("No delegations held");
181
+ } else {
182
+ console.log("Delegations:");
183
+ for (const d of delegations) {
184
+ console.log(` inode ${d.inodeId}: ${d.state}`);
185
+ }
186
+ }
187
+ } catch (err) {
188
+ console.error("Failed to list delegations:", err instanceof Error ? err.message : err);
189
+ }
190
+ return true;
191
+ }
192
+
193
+ if (subcommand === "help" || !subcommand) {
194
+ console.log("Archil commands:");
195
+ console.log(" archil checkout [--force|-f] <path> - Acquire write delegation");
196
+ console.log(" archil checkin <path> - Release write delegation");
197
+ console.log(" archil list-delegations - Show held delegations");
198
+ console.log(" archil help - Show this help message");
199
+ console.log("");
200
+ console.log("The --force flag revokes any existing delegation from other clients.");
201
+ return true;
202
+ }
203
+
204
+ console.error(`Unknown archil command: ${subcommand}`);
205
+ console.error("Run 'archil help' for available commands");
206
+ return true;
207
+ };
208
+
209
+ rl.on("line", async (line) => {
210
+ const trimmed = line.trim();
211
+
212
+ if (trimmed === "exit" || trimmed === "quit") {
213
+ await cleanup();
214
+ return;
215
+ }
216
+
217
+ if (!trimmed) {
218
+ prompt();
219
+ return;
220
+ }
221
+
222
+ // Pause readline while we process the command
223
+ rl.pause();
224
+
225
+ try {
226
+ // Check for archil commands first
227
+ if (trimmed.startsWith("archil")) {
228
+ await handleArchilCommand(trimmed);
229
+ rl.resume();
230
+ prompt();
231
+ return;
232
+ }
233
+
234
+ // Execute command with current working directory
235
+ const result = await bash.exec(trimmed, {
236
+ cwd,
237
+ env: {
238
+ HOME: "/",
239
+ USER: "archil",
240
+ PWD: cwd,
241
+ },
242
+ });
243
+
244
+ // Print output
245
+ if (result.stdout) {
246
+ process.stdout.write(result.stdout);
247
+ if (!result.stdout.endsWith("\n")) {
248
+ console.log("");
249
+ }
250
+ }
251
+ if (result.stderr) {
252
+ process.stderr.write(result.stderr);
253
+ if (!result.stderr.endsWith("\n")) {
254
+ console.error("");
255
+ }
256
+ }
257
+
258
+ // Update cwd if command changed it
259
+ if (result.env?.PWD && result.env.PWD !== cwd) {
260
+ cwd = result.env.PWD;
261
+ }
262
+ } catch (err) {
263
+ console.error("Error:", err instanceof Error ? err.message : err);
264
+ }
265
+
266
+ rl.resume();
267
+ prompt();
268
+ });
269
+
270
+ rl.on("close", () => cleanup());
271
+ }
272
+
273
+ main().catch((err) => {
274
+ console.error("Fatal error:", err);
275
+ process.exit(1);
276
+ });