@foleo/cli 0.1.36 → 0.1.48
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/README.md +24 -0
- package/dist/encoded-image-cache.d.ts +14 -0
- package/dist/encoded-image-cache.d.ts.map +1 -0
- package/dist/encoded-image-cache.js +123 -0
- package/dist/encoded-image-cache.js.map +1 -0
- package/dist/image-encoder.d.ts +16 -0
- package/dist/image-encoder.d.ts.map +1 -0
- package/dist/image-encoder.js +142 -0
- package/dist/image-encoder.js.map +1 -0
- package/dist/images.d.ts +85 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +411 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +987 -166
- package/dist/index.js.map +1 -1
- package/dist/workspaces.d.ts +13 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +705 -0
- package/dist/workspaces.js.map +1 -0
- package/package.json +1 -1
- package/skills/foleo/SKILL.md +229 -6
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
import { createHash, randomUUID, randomBytes, pbkdf2Sync } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { open, readFile } from "node:fs/promises";
|
|
4
|
+
import { basename } from "node:path";
|
|
5
|
+
import { LocalError, FoleoError } from "./errors.js";
|
|
6
|
+
import { createWriteStream } from "node:fs";
|
|
7
|
+
import { Readable } from "node:stream";
|
|
8
|
+
import { pipeline } from "node:stream/promises";
|
|
9
|
+
import { UsageError } from "./errors.js";
|
|
10
|
+
/** Keep in step with infra/publish/src/managed-workspaces/contracts.ts. */
|
|
11
|
+
export function secretFileName(value) {
|
|
12
|
+
const name = value.normalize("NFC").toLowerCase();
|
|
13
|
+
return (name === ".env" ||
|
|
14
|
+
name.startsWith(".env.") ||
|
|
15
|
+
name === ".dev.vars" ||
|
|
16
|
+
name.startsWith(".dev.vars.") ||
|
|
17
|
+
name === ".npmrc" ||
|
|
18
|
+
name === ".netrc" ||
|
|
19
|
+
name === ".pgpass" ||
|
|
20
|
+
/\.(?:pem|p12|pfx)$/u.test(name) ||
|
|
21
|
+
/^id_(?:rsa|dsa|ecdsa|ed25519)$/u.test(name) ||
|
|
22
|
+
[".git", ".ssh", ".aws", ".gnupg"].includes(name));
|
|
23
|
+
}
|
|
24
|
+
export const WORKSPACE_HELP = `Foleo workspace (explicit workspace grant required):
|
|
25
|
+
foleo workspace list [--json]
|
|
26
|
+
foleo workspace items <workspaceId> [--parent <id>] [--state live|trashed] [--cursor <cursor>] [--limit <1-100>] [--json]
|
|
27
|
+
foleo workspace get <workspaceId> <itemId> [--json]
|
|
28
|
+
foleo workspace read <workspaceId> <itemId> --output <path> [--revision <id>] [--json]
|
|
29
|
+
foleo workspace history <workspaceId> <itemId> [--cursor <cursor>] [--limit <1-100>] [--json]
|
|
30
|
+
foleo workspace search <workspaceId> <query> [--limit <1-50>] [--state live|trashed] [--json]
|
|
31
|
+
foleo workspace status <workspaceId> [--json]
|
|
32
|
+
foleo workspace watch <workspaceId> [--timeout <seconds>] [--json]
|
|
33
|
+
foleo workspace capabilities [--json]
|
|
34
|
+
foleo capabilities [--json]
|
|
35
|
+
foleo workspace create <name> [--mutation-id <id>] [--json]
|
|
36
|
+
foleo workspace put <workspaceId> <path> (--parent <id> [--name <name>] | --item <id> --expected-revision <revisionId>) [--mutation-id <id>] [--json]
|
|
37
|
+
--expected-revision is the revisionId you read (from get/read); a newer save is refused, never overwritten.
|
|
38
|
+
foleo workspace mkdir <workspaceId> --parent <id> --name <name> [--mutation-id <id>] [--json]
|
|
39
|
+
foleo workspace move <workspaceId> <itemId> --parent <id> --name <name> [--mutation-id <id>] [--acknowledge-access-widening] [--json]
|
|
40
|
+
foleo workspace trash <workspaceId> <itemId> [--mutation-id <id>] [--json]
|
|
41
|
+
foleo workspace restore <workspaceId> <itemId> --parent <id> --name <name> [--mutation-id <id>] [--acknowledge-access-widening] [--json]
|
|
42
|
+
foleo workspace commit <workspaceId> --input <json-file> [--json]
|
|
43
|
+
foleo workspace commit-status <workspaceId> <mutationId> [--json]
|
|
44
|
+
foleo workspace upload-status <workspaceId> <uploadId> [--json]
|
|
45
|
+
foleo workspace upload-cancel <workspaceId> <uploadId> [--json]
|
|
46
|
+
foleo workspace share get <workspaceId> <itemId> [--json]
|
|
47
|
+
foleo workspace share set <workspaceId> <itemId> --mode private|link|password|public|inherit [--password-stdin] [--mutation-id <id>] [--acknowledge-access-widening] [--json]
|
|
48
|
+
foleo approval get <approvalId> [--json]
|
|
49
|
+
foleo approval commit <approvalId> --idempotency-key <key> [--json]
|
|
50
|
+
Writes require workspaces:read + workspaces:write. Sharing requires workspaces:read + workspaces:share.
|
|
51
|
+
New items are Private. Narrowing applies immediately.
|
|
52
|
+
Before widening who can see a file, ask the human in chat and get a clear yes; then retry with the acknowledgement. Never acknowledge on the human's behalf.
|
|
53
|
+
With an API key, link and password widenings need --acknowledge-access-widening (otherwise acknowledgement_required); public always needs approval in Foleo, then approval commit.
|
|
54
|
+
Undo a widening with share set <workspaceId> <itemId> --mode private. In commit JSON, the acknowledgement is top-level accessWideningAcknowledged: true.
|
|
55
|
+
Hash-first put uploads zero bytes when unchanged (32 MiB/file). Batches accept eight operations.
|
|
56
|
+
On response loss retry the exact commit payload and mutation ID, or use commit-status. Never mint a new ID just because a response was lost.
|
|
57
|
+
Saves do not publish files or change sharing.
|
|
58
|
+
`;
|
|
59
|
+
/** Read-only adapters; the server owns authorization, pagination and bytes. */
|
|
60
|
+
export async function workspaceCommand(args, deps) {
|
|
61
|
+
const [command, ...rest] = args;
|
|
62
|
+
if (command === "share" || command === "approval")
|
|
63
|
+
return workspaceSharing(command, rest, deps);
|
|
64
|
+
if (!command || command === "--help" || command === "help") {
|
|
65
|
+
deps.stdout(WORKSPACE_HELP);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
const positionals = [];
|
|
69
|
+
const flags = new Map();
|
|
70
|
+
const allowed = new Set([
|
|
71
|
+
"--timeout",
|
|
72
|
+
"--parent",
|
|
73
|
+
"--state",
|
|
74
|
+
"--cursor",
|
|
75
|
+
"--limit",
|
|
76
|
+
"--output",
|
|
77
|
+
"--revision",
|
|
78
|
+
"--item",
|
|
79
|
+
"--expected-revision",
|
|
80
|
+
"--name",
|
|
81
|
+
"--input",
|
|
82
|
+
"--mutation-id",
|
|
83
|
+
]);
|
|
84
|
+
let acknowledgeWidening = false;
|
|
85
|
+
for (let i = 0; i < rest.length; i++) {
|
|
86
|
+
const value = rest[i];
|
|
87
|
+
if (value === "--json")
|
|
88
|
+
continue;
|
|
89
|
+
if (value === "--acknowledge-access-widening") {
|
|
90
|
+
if (acknowledgeWidening || !["move", "restore"].includes(command))
|
|
91
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
92
|
+
acknowledgeWidening = true;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (value.startsWith("--")) {
|
|
96
|
+
const next = rest[++i];
|
|
97
|
+
if (!allowed.has(value) ||
|
|
98
|
+
!next ||
|
|
99
|
+
next.startsWith("--") ||
|
|
100
|
+
flags.has(value))
|
|
101
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
102
|
+
flags.set(value, next);
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
positionals.push(value);
|
|
106
|
+
}
|
|
107
|
+
if (command === "watch") {
|
|
108
|
+
if (positionals.length !== 1 ||
|
|
109
|
+
[...flags.keys()].some((k) => k !== "--timeout"))
|
|
110
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
111
|
+
const timeout = Number(flags.get("--timeout") ?? "60");
|
|
112
|
+
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 300)
|
|
113
|
+
throw new UsageError("--timeout must be 1–300 seconds.");
|
|
114
|
+
const wid = encodeURIComponent(positionals[0]);
|
|
115
|
+
const snapshot = (await (await deps.request(`/workspaces/${wid}/manifest`)).json());
|
|
116
|
+
const response = await deps.request(`/workspaces/${wid}/room-ticket`, {
|
|
117
|
+
method: "POST",
|
|
118
|
+
headers: { "content-type": "application/json" },
|
|
119
|
+
body: "{}",
|
|
120
|
+
});
|
|
121
|
+
if (!response.ok) {
|
|
122
|
+
await response.json();
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
const ticket = (await response.json());
|
|
126
|
+
const socket = (deps.openSocket ?? ((url) => new WebSocket(url)))(ticket.url);
|
|
127
|
+
let admittedFeed;
|
|
128
|
+
await new Promise((resolve, reject) => {
|
|
129
|
+
let settled = false;
|
|
130
|
+
const done = () => {
|
|
131
|
+
if (settled)
|
|
132
|
+
return;
|
|
133
|
+
settled = true;
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
socket.close(1000, "done");
|
|
136
|
+
resolve();
|
|
137
|
+
};
|
|
138
|
+
const timer = setTimeout(done, timeout * 1000);
|
|
139
|
+
socket.onmessage = (event) => {
|
|
140
|
+
try {
|
|
141
|
+
const raw = String(event.data);
|
|
142
|
+
if (raw.length > 1024)
|
|
143
|
+
return;
|
|
144
|
+
const h = JSON.parse(raw);
|
|
145
|
+
if (Object.keys(h).length === 2 &&
|
|
146
|
+
["seq", "share", "comments"].includes(h.t) &&
|
|
147
|
+
Number.isSafeInteger(h.s) &&
|
|
148
|
+
h.s > snapshot.workspace.sequence)
|
|
149
|
+
done();
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
/* ignore malformed hints */
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
socket.onopen = () => {
|
|
156
|
+
void (async () => {
|
|
157
|
+
const feed = await deps.request(`/workspaces/${wid}/changes?cursor=${encodeURIComponent(snapshot.cursor)}`);
|
|
158
|
+
if (!feed.ok)
|
|
159
|
+
throw new Error("Could not catch up workspace watch.");
|
|
160
|
+
const value = (await feed.json());
|
|
161
|
+
if (!settled && (value.changes?.length || value.hasMore)) {
|
|
162
|
+
admittedFeed = value;
|
|
163
|
+
done();
|
|
164
|
+
}
|
|
165
|
+
})().catch((error) => {
|
|
166
|
+
if (settled)
|
|
167
|
+
return;
|
|
168
|
+
settled = true;
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
socket.close(1000, "done");
|
|
171
|
+
reject(error);
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
socket.onclose = done;
|
|
175
|
+
socket.onerror = done;
|
|
176
|
+
});
|
|
177
|
+
// Even timeout/disconnect checks durable truth. Hints never become cursors.
|
|
178
|
+
const result = admittedFeed ??
|
|
179
|
+
(await (await deps.request(`/workspaces/${wid}/changes?cursor=${encodeURIComponent(snapshot.cursor)}`)).json());
|
|
180
|
+
deps.stdout(JSON.stringify(result));
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
if ([
|
|
184
|
+
"create",
|
|
185
|
+
"put",
|
|
186
|
+
"mkdir",
|
|
187
|
+
"move",
|
|
188
|
+
"trash",
|
|
189
|
+
"restore",
|
|
190
|
+
"commit",
|
|
191
|
+
"commit-status",
|
|
192
|
+
"upload-status",
|
|
193
|
+
"upload-cancel",
|
|
194
|
+
].includes(command))
|
|
195
|
+
return workspaceMutation(command, positionals, flags, deps, acknowledgeWidening);
|
|
196
|
+
const count = command === "list" || command === "capabilities"
|
|
197
|
+
? 0
|
|
198
|
+
: command === "items" || command === "status"
|
|
199
|
+
? 1
|
|
200
|
+
: 2;
|
|
201
|
+
const validFlags = command === "search"
|
|
202
|
+
? ["--limit", "--state"]
|
|
203
|
+
: command === "items"
|
|
204
|
+
? ["--parent", "--state", "--cursor", "--limit"]
|
|
205
|
+
: command === "history"
|
|
206
|
+
? ["--cursor", "--limit"]
|
|
207
|
+
: command === "read"
|
|
208
|
+
? ["--output", "--revision"]
|
|
209
|
+
: [];
|
|
210
|
+
if (![
|
|
211
|
+
"list",
|
|
212
|
+
"items",
|
|
213
|
+
"get",
|
|
214
|
+
"read",
|
|
215
|
+
"history",
|
|
216
|
+
"capabilities",
|
|
217
|
+
"search",
|
|
218
|
+
"status",
|
|
219
|
+
].includes(command) ||
|
|
220
|
+
positionals.length !== count ||
|
|
221
|
+
[...flags.keys()].some((key) => !validFlags.includes(key)))
|
|
222
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
223
|
+
const limit = flags.get("--limit");
|
|
224
|
+
if (limit &&
|
|
225
|
+
(!/^\d+$/u.test(limit) ||
|
|
226
|
+
Number(limit) < 1 ||
|
|
227
|
+
Number(limit) > (command === "search" ? 50 : 100)))
|
|
228
|
+
throw new UsageError(`--limit must be between 1 and ${command === "search" ? 50 : 100}.`);
|
|
229
|
+
if (command === "read" && !flags.has("--output"))
|
|
230
|
+
throw new UsageError("workspace read requires --output <path>.");
|
|
231
|
+
const [wid, iid] = positionals.map(encodeURIComponent);
|
|
232
|
+
const base = `/workspaces/${wid}/items`;
|
|
233
|
+
const path = command === "search" || command === "status"
|
|
234
|
+
? `/workspaces/${wid}/${command}`
|
|
235
|
+
: command === "capabilities"
|
|
236
|
+
? "/capabilities"
|
|
237
|
+
: command === "list"
|
|
238
|
+
? "/workspaces"
|
|
239
|
+
: command === "items"
|
|
240
|
+
? base
|
|
241
|
+
: `${base}/${iid}${command === "read" ? "/content" : command === "history" ? "/revisions" : ""}`;
|
|
242
|
+
const query = new URLSearchParams();
|
|
243
|
+
if (command === "search")
|
|
244
|
+
query.set("q", positionals[1]);
|
|
245
|
+
for (const [flag, key] of [
|
|
246
|
+
["--parent", "parentId"],
|
|
247
|
+
["--state", "state"],
|
|
248
|
+
["--cursor", "cursor"],
|
|
249
|
+
["--limit", "limit"],
|
|
250
|
+
["--revision", "revisionId"],
|
|
251
|
+
]) {
|
|
252
|
+
if (flags.has(flag))
|
|
253
|
+
query.set(key, flags.get(flag));
|
|
254
|
+
}
|
|
255
|
+
const response = await deps.request(`${path}${query.size ? `?${query}` : ""}`);
|
|
256
|
+
if (command === "read") {
|
|
257
|
+
if (!response.body)
|
|
258
|
+
throw new Error("Workspace content response had no body.");
|
|
259
|
+
const output = flags.get("--output");
|
|
260
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(output, { flags: "wx" }));
|
|
261
|
+
deps.stdout(`${JSON.stringify({ output, revisionId: response.headers.get("x-foleo-revision-id"), sha256: response.headers.get("x-foleo-sha256"), size: Number(response.headers.get("content-length")) }, null, 2)}\n`);
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
const value = (await response.json());
|
|
265
|
+
deps.stdout(`${JSON.stringify(command === "capabilities" ? value.workspaces : value, null, 2)}\n`);
|
|
266
|
+
}
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
/** Capture one bounded, stable file before hashing; never reopen it for upload. */
|
|
270
|
+
async function captureFile(path) {
|
|
271
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
272
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
273
|
+
try {
|
|
274
|
+
const before = await handle.stat({ bigint: true });
|
|
275
|
+
if (!before.isFile() || before.size > 33554432n)
|
|
276
|
+
throw new UsageError("workspace put requires a regular file of at most 32 MiB.");
|
|
277
|
+
const chunks = [];
|
|
278
|
+
let size = 0;
|
|
279
|
+
for (;;) {
|
|
280
|
+
const buffer = Buffer.alloc(65536);
|
|
281
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
282
|
+
if (!bytesRead)
|
|
283
|
+
break;
|
|
284
|
+
size += bytesRead;
|
|
285
|
+
if (size > 33554432)
|
|
286
|
+
throw new UsageError("workspace put requires a file of at most 32 MiB.");
|
|
287
|
+
chunks.push(buffer.subarray(0, bytesRead));
|
|
288
|
+
}
|
|
289
|
+
const after = await handle.stat({ bigint: true });
|
|
290
|
+
if (before.size !== after.size ||
|
|
291
|
+
before.mtimeNs !== after.mtimeNs ||
|
|
292
|
+
before.ctimeNs !== after.ctimeNs ||
|
|
293
|
+
BigInt(size) !== after.size)
|
|
294
|
+
continue;
|
|
295
|
+
const bytes = Buffer.concat(chunks, size);
|
|
296
|
+
return {
|
|
297
|
+
bytes,
|
|
298
|
+
size,
|
|
299
|
+
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
await handle.close();
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
throw new LocalError("file_changed_during_capture", "File changed during capture; retry after it stops changing.");
|
|
307
|
+
}
|
|
308
|
+
async function workspaceMutation(command, positionals, flags, deps, acknowledgeWidening = false) {
|
|
309
|
+
const count = ["create", "mkdir", "commit"].includes(command) ? 1 : 2;
|
|
310
|
+
const allowed = command === "put"
|
|
311
|
+
? ["--parent", "--name", "--item", "--expected-revision", "--mutation-id"]
|
|
312
|
+
: command === "mkdir" || command === "move" || command === "restore"
|
|
313
|
+
? ["--parent", "--name", "--mutation-id"]
|
|
314
|
+
: command === "create" || command === "trash"
|
|
315
|
+
? ["--mutation-id"]
|
|
316
|
+
: command === "commit"
|
|
317
|
+
? ["--input"]
|
|
318
|
+
: [];
|
|
319
|
+
if (positionals.length !== count ||
|
|
320
|
+
[...flags.keys()].some((flag) => !allowed.includes(flag)))
|
|
321
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
322
|
+
if ((["mkdir", "move", "restore"].includes(command) &&
|
|
323
|
+
(!flags.has("--parent") || !flags.has("--name"))) ||
|
|
324
|
+
(command === "commit" && !flags.has("--input")) ||
|
|
325
|
+
(command === "put" &&
|
|
326
|
+
(flags.has("--item") === flags.has("--parent") ||
|
|
327
|
+
(flags.has("--item") && flags.has("--name")) ||
|
|
328
|
+
// Spec 114 §3.2: a replace names the version the caller actually read.
|
|
329
|
+
flags.has("--item") !== flags.has("--expected-revision"))))
|
|
330
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
331
|
+
const wid = encodeURIComponent(positionals[0]), iid = encodeURIComponent(positionals[1] ?? "");
|
|
332
|
+
const base = `/workspaces/${wid}`;
|
|
333
|
+
const json = async (path, init) => (await deps.request(path, init)).json();
|
|
334
|
+
const send = (path, value) => json(path, {
|
|
335
|
+
method: "POST",
|
|
336
|
+
headers: { "content-type": "application/json" },
|
|
337
|
+
body: JSON.stringify(value),
|
|
338
|
+
});
|
|
339
|
+
const print = (value) => deps.stdout(`${JSON.stringify(value, null, 2)}\n`);
|
|
340
|
+
if (command === "commit-status" ||
|
|
341
|
+
command === "upload-status" ||
|
|
342
|
+
command === "upload-cancel") {
|
|
343
|
+
print(await json(`${base}/${command === "commit-status" ? "commits" : "uploads"}/${iid}${command === "upload-cancel" ? "/cancel" : ""}`, command === "upload-cancel" ? { method: "POST" } : undefined));
|
|
344
|
+
return 0;
|
|
345
|
+
}
|
|
346
|
+
if (command === "commit") {
|
|
347
|
+
const text = await readFile(flags.get("--input"), "utf8");
|
|
348
|
+
if (Buffer.byteLength(text) > 262144)
|
|
349
|
+
throw new UsageError("Commit metadata exceeds 256 KiB.");
|
|
350
|
+
const input = JSON.parse(text);
|
|
351
|
+
try {
|
|
352
|
+
print(await send(`${base}/commits`, input));
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (error instanceof FoleoError && (error.httpStatus ?? 0) < 500)
|
|
356
|
+
throw error;
|
|
357
|
+
const mutationId = input && typeof input === "object" && "clientMutationId" in input
|
|
358
|
+
? input.clientMutationId
|
|
359
|
+
: undefined;
|
|
360
|
+
if (typeof mutationId !== "string")
|
|
361
|
+
throw error;
|
|
362
|
+
try {
|
|
363
|
+
print(await json(`${base}/commits/${encodeURIComponent(mutationId)}`));
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
throw new LocalError("workspace_commit_unconfirmed", "Commit response unavailable. Recover using the original mutation ID.", {
|
|
367
|
+
next: `foleo workspace commit-status ${positionals[0]} ${mutationId} --json`,
|
|
368
|
+
context: { clientMutationId: mutationId, input },
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return 0;
|
|
373
|
+
}
|
|
374
|
+
const clientMutationId = flags.get("--mutation-id") ?? randomUUID();
|
|
375
|
+
if (command === "create") {
|
|
376
|
+
const payload = { clientMutationId, name: positionals[0] };
|
|
377
|
+
try {
|
|
378
|
+
print(await send("/workspaces", payload));
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
if (error instanceof FoleoError && (error.httpStatus ?? 0) < 500)
|
|
382
|
+
throw error;
|
|
383
|
+
try {
|
|
384
|
+
print(await send("/workspaces", payload));
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
throw new LocalError("workspace_create_unconfirmed", "Workspace creation response unavailable. Replay the same name and mutation ID.", {
|
|
388
|
+
next: `foleo workspace create ${JSON.stringify(positionals[0])} --mutation-id ${clientMutationId} --json`,
|
|
389
|
+
context: payload,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return 0;
|
|
394
|
+
}
|
|
395
|
+
const operations = [];
|
|
396
|
+
const metadata = async (id) => (await json(`${base}/items/${encodeURIComponent(id)}`));
|
|
397
|
+
// Spec 114 §2.1: mirror the API's secret-name refusal before any request,
|
|
398
|
+
// so the bytes never leave this machine (the server refuses it either way).
|
|
399
|
+
const targetName = command === "put"
|
|
400
|
+
? (flags.get("--name") ?? basename(positionals[1]))
|
|
401
|
+
: flags.get("--name");
|
|
402
|
+
if (!flags.has("--item") &&
|
|
403
|
+
targetName !== undefined &&
|
|
404
|
+
secretFileName(targetName))
|
|
405
|
+
throw new LocalError("secret_file_name", `Refusing ${JSON.stringify(targetName)}: files like .env, keys and credentials never go into a Foleo workspace.`, { retryable: false });
|
|
406
|
+
const parent = flags.has("--parent")
|
|
407
|
+
? await metadata(flags.get("--parent"))
|
|
408
|
+
: undefined;
|
|
409
|
+
let uploadId;
|
|
410
|
+
let inlineContent;
|
|
411
|
+
let protocolVersion;
|
|
412
|
+
let submitted = false;
|
|
413
|
+
const abort = new AbortController();
|
|
414
|
+
const interrupt = () => abort.abort(new Error("workspace_upload_interrupted"));
|
|
415
|
+
process.once("SIGINT", interrupt);
|
|
416
|
+
process.once("SIGTERM", interrupt);
|
|
417
|
+
try {
|
|
418
|
+
if (command === "put") {
|
|
419
|
+
const captured = await captureFile(positionals[1]);
|
|
420
|
+
const fetched = flags.has("--item")
|
|
421
|
+
? await metadata(flags.get("--item"))
|
|
422
|
+
: undefined;
|
|
423
|
+
// Metadata is fetched for the metadata version only; the content base is
|
|
424
|
+
// always the caller's observed revision, so a newer save makes the server
|
|
425
|
+
// refuse this write instead of the CLI silently rebasing onto it.
|
|
426
|
+
const current = fetched
|
|
427
|
+
? { ...fetched, revisionId: flags.get("--expected-revision") }
|
|
428
|
+
: undefined;
|
|
429
|
+
if (current &&
|
|
430
|
+
current.sha256 === captured.sha256 &&
|
|
431
|
+
current.size === captured.size)
|
|
432
|
+
operations.push({
|
|
433
|
+
type: "sameContent",
|
|
434
|
+
itemId: current.id,
|
|
435
|
+
expectedRevisionId: current.revisionId,
|
|
436
|
+
sha256: captured.sha256,
|
|
437
|
+
size: captured.size,
|
|
438
|
+
});
|
|
439
|
+
else {
|
|
440
|
+
const capabilities = captured.size <= 65536 ? await json("/capabilities") : undefined;
|
|
441
|
+
const advertised = capabilities?.workspaces?.commitProtocol;
|
|
442
|
+
if (advertised?.available === true &&
|
|
443
|
+
advertised.version === 2 &&
|
|
444
|
+
advertised.inlineMaxBytes >= captured.size) {
|
|
445
|
+
protocolVersion = 2;
|
|
446
|
+
inlineContent = {
|
|
447
|
+
content: captured.bytes.toString("base64"),
|
|
448
|
+
encoding: "base64",
|
|
449
|
+
size: captured.size,
|
|
450
|
+
sha256: captured.sha256,
|
|
451
|
+
mimeType: "application/octet-stream",
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
const upload = await send(`${base}/uploads`, {
|
|
456
|
+
clientMutationId,
|
|
457
|
+
size: captured.size,
|
|
458
|
+
sha256: captured.sha256,
|
|
459
|
+
mimeType: "application/octet-stream",
|
|
460
|
+
});
|
|
461
|
+
uploadId = upload.uploadId;
|
|
462
|
+
await deps.request(`${base}/uploads/${encodeURIComponent(uploadId)}/content`, {
|
|
463
|
+
method: "PUT",
|
|
464
|
+
headers: {
|
|
465
|
+
"content-length": String(captured.size),
|
|
466
|
+
"content-type": "application/octet-stream",
|
|
467
|
+
},
|
|
468
|
+
body: captured.bytes,
|
|
469
|
+
signal: abort.signal,
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
operations.push(current
|
|
473
|
+
? {
|
|
474
|
+
type: "replace",
|
|
475
|
+
itemId: current.id,
|
|
476
|
+
expectedRevisionId: current.revisionId,
|
|
477
|
+
expectedMetadataVersion: current.metadataVersion,
|
|
478
|
+
uploadId,
|
|
479
|
+
}
|
|
480
|
+
: {
|
|
481
|
+
type: "create",
|
|
482
|
+
clientOperationId: clientMutationId,
|
|
483
|
+
itemId: randomUUID(),
|
|
484
|
+
parentId: parent.id,
|
|
485
|
+
expectedParentMetadataVersion: parent.metadataVersion,
|
|
486
|
+
name: flags.get("--name") ?? basename(positionals[1]),
|
|
487
|
+
kind: "file",
|
|
488
|
+
uploadId,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
else if (command === "mkdir")
|
|
493
|
+
operations.push({
|
|
494
|
+
type: "create",
|
|
495
|
+
clientOperationId: clientMutationId,
|
|
496
|
+
itemId: randomUUID(),
|
|
497
|
+
parentId: parent.id,
|
|
498
|
+
expectedParentMetadataVersion: parent.metadataVersion,
|
|
499
|
+
name: flags.get("--name"),
|
|
500
|
+
kind: "folder",
|
|
501
|
+
});
|
|
502
|
+
else {
|
|
503
|
+
const item = await metadata(positionals[1]);
|
|
504
|
+
operations.push({
|
|
505
|
+
type: command,
|
|
506
|
+
itemId: item.id,
|
|
507
|
+
expectedMetadataVersion: item.metadataVersion,
|
|
508
|
+
...(command === "trash"
|
|
509
|
+
? { observedSubtreeToken: item.observedSubtreeToken }
|
|
510
|
+
: {
|
|
511
|
+
parentId: parent.id,
|
|
512
|
+
expectedParentMetadataVersion: parent.metadataVersion,
|
|
513
|
+
name: flags.get("--name"),
|
|
514
|
+
}),
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
if (abort.signal.aborted)
|
|
518
|
+
throw new LocalError("cancelled", "Upload cancelled; nothing was published.", { retryable: true });
|
|
519
|
+
// A lost response must never cause cancellation of a possibly committed upload.
|
|
520
|
+
submitted = true;
|
|
521
|
+
const input = {
|
|
522
|
+
clientMutationId,
|
|
523
|
+
...(protocolVersion ? { protocolVersion, inlineContent } : {}),
|
|
524
|
+
...(acknowledgeWidening ? { accessWideningAcknowledged: true } : {}),
|
|
525
|
+
operations,
|
|
526
|
+
};
|
|
527
|
+
let result;
|
|
528
|
+
try {
|
|
529
|
+
result = await send(`${base}/commits`, input);
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
if (error instanceof FoleoError && (error.httpStatus ?? 0) < 500) {
|
|
533
|
+
// A semantic conflict preserves staged bytes for the caller's decision.
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
result = await json(`${base}/commits/${encodeURIComponent(clientMutationId)}`);
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
throw new LocalError("workspace_commit_unconfirmed", "Commit response unavailable. Recover using the original mutation ID.", {
|
|
541
|
+
next: `foleo workspace commit-status ${positionals[0]} ${clientMutationId} --json`,
|
|
542
|
+
context: {
|
|
543
|
+
clientMutationId,
|
|
544
|
+
input,
|
|
545
|
+
cause: error instanceof Error ? error.message : "request_failed",
|
|
546
|
+
},
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
// The kernel fences an unused no-op reservation atomically. An optional
|
|
551
|
+
// transport cleanup must never hide an accepted receipt.
|
|
552
|
+
print(result);
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
const interrupted = abort.signal.aborted && !submitted;
|
|
556
|
+
if (uploadId && !submitted)
|
|
557
|
+
try {
|
|
558
|
+
const cleanup = new AbortController();
|
|
559
|
+
let timer;
|
|
560
|
+
try {
|
|
561
|
+
await Promise.race([
|
|
562
|
+
deps.request(`${base}/uploads/${uploadId}/cancel`, {
|
|
563
|
+
method: "POST",
|
|
564
|
+
signal: cleanup.signal,
|
|
565
|
+
}),
|
|
566
|
+
new Promise((resolve) => {
|
|
567
|
+
timer = setTimeout(resolve, 2800);
|
|
568
|
+
}),
|
|
569
|
+
]);
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
clearTimeout(timer);
|
|
573
|
+
cleanup.abort();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
catch {
|
|
577
|
+
/* Preserve the original failure; upload-status allows recovery. */
|
|
578
|
+
}
|
|
579
|
+
if (interrupted)
|
|
580
|
+
throw new LocalError("cancelled", "Upload cancelled; nothing was published.", { retryable: true });
|
|
581
|
+
throw error;
|
|
582
|
+
}
|
|
583
|
+
finally {
|
|
584
|
+
process.removeListener("SIGINT", interrupt);
|
|
585
|
+
process.removeListener("SIGTERM", interrupt);
|
|
586
|
+
}
|
|
587
|
+
return 0;
|
|
588
|
+
}
|
|
589
|
+
async function workspaceSharing(family, args, deps) {
|
|
590
|
+
const [action, ...rest] = args;
|
|
591
|
+
const positionals = [], flags = new Map();
|
|
592
|
+
let passwordStdin = false;
|
|
593
|
+
let acknowledgeWidening = false;
|
|
594
|
+
for (let i = 0; i < rest.length; i++) {
|
|
595
|
+
const value = rest[i];
|
|
596
|
+
if (value === "--json")
|
|
597
|
+
continue;
|
|
598
|
+
if (value === "--acknowledge-access-widening") {
|
|
599
|
+
if (acknowledgeWidening || family !== "share" || action !== "set")
|
|
600
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
601
|
+
acknowledgeWidening = true;
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (value === "--password-stdin") {
|
|
605
|
+
if (passwordStdin)
|
|
606
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
607
|
+
passwordStdin = true;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
if (value.startsWith("--")) {
|
|
611
|
+
if (!["--mode", "--mutation-id", "--idempotency-key"].includes(value) ||
|
|
612
|
+
flags.has(value) ||
|
|
613
|
+
!rest[i + 1] ||
|
|
614
|
+
rest[i + 1].startsWith("--"))
|
|
615
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
616
|
+
flags.set(value, rest[++i]);
|
|
617
|
+
}
|
|
618
|
+
else
|
|
619
|
+
positionals.push(value);
|
|
620
|
+
}
|
|
621
|
+
const approval = family === "approval";
|
|
622
|
+
if (!["get", approval ? "commit" : "set"].includes(action ?? "") ||
|
|
623
|
+
positionals.length !== (approval ? 1 : 2))
|
|
624
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
625
|
+
const allowed = action === "get"
|
|
626
|
+
? []
|
|
627
|
+
: approval
|
|
628
|
+
? ["--idempotency-key"]
|
|
629
|
+
: ["--mode", "--mutation-id"];
|
|
630
|
+
if ([...flags.keys()].some((flag) => !allowed.includes(flag)) ||
|
|
631
|
+
(passwordStdin &&
|
|
632
|
+
(approval || action !== "set" || flags.get("--mode") !== "password")))
|
|
633
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
634
|
+
const base = approval
|
|
635
|
+
? `/agent-approvals/${encodeURIComponent(positionals[0])}`
|
|
636
|
+
: `/workspaces/${encodeURIComponent(positionals[0])}/items/${encodeURIComponent(positionals[1])}`;
|
|
637
|
+
let path = approval ? base : `${base}/share`, init;
|
|
638
|
+
if (action === "commit") {
|
|
639
|
+
const key = flags.get("--idempotency-key");
|
|
640
|
+
if (!key || key.length < 8 || key.length > 200)
|
|
641
|
+
throw new UsageError("approval commit requires --idempotency-key (8–200 characters).");
|
|
642
|
+
path += "/commit";
|
|
643
|
+
init = { method: "POST", headers: { "idempotency-key": key } };
|
|
644
|
+
}
|
|
645
|
+
else if (action === "set") {
|
|
646
|
+
const mode = flags.get("--mode");
|
|
647
|
+
if (!mode ||
|
|
648
|
+
!["private", "link", "password", "public", "inherit"].includes(mode))
|
|
649
|
+
throw new UsageError(WORKSPACE_HELP);
|
|
650
|
+
if (mode === "password" && !passwordStdin)
|
|
651
|
+
throw new UsageError("Password mode requires --password-stdin; passwords are never accepted in argv.");
|
|
652
|
+
let passwordKey;
|
|
653
|
+
if (passwordStdin) {
|
|
654
|
+
if (!deps.readStdin)
|
|
655
|
+
throw new UsageError("Password stdin is unavailable.");
|
|
656
|
+
const password = (await deps.readStdin()).replace(/\r?\n$/u, "");
|
|
657
|
+
if (password.length < 8 || password.length > 256)
|
|
658
|
+
throw new UsageError("Use a password with 8–256 characters.");
|
|
659
|
+
const salt = randomBytes(16).toString("hex");
|
|
660
|
+
const bytes = Buffer.from(password, "utf8");
|
|
661
|
+
try {
|
|
662
|
+
passwordKey = {
|
|
663
|
+
version: 1,
|
|
664
|
+
algorithm: "PBKDF2-SHA256",
|
|
665
|
+
iterations: 600000,
|
|
666
|
+
salt,
|
|
667
|
+
derivedKey: pbkdf2Sync(bytes, Buffer.from(salt, "hex"), 600000, 32, "sha256").toString("hex"),
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
finally {
|
|
671
|
+
bytes.fill(0);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
const metadata = (await (await deps.request(base)).json());
|
|
675
|
+
init = {
|
|
676
|
+
method: "POST",
|
|
677
|
+
headers: { "content-type": "application/json" },
|
|
678
|
+
body: JSON.stringify({
|
|
679
|
+
clientMutationId: flags.get("--mutation-id") ?? randomUUID(),
|
|
680
|
+
mode,
|
|
681
|
+
enabled: ["link", "password", "public"].includes(mode),
|
|
682
|
+
expectedMetadataVersion: metadata.metadataVersion,
|
|
683
|
+
expectedSequence: metadata.workspaceSequence,
|
|
684
|
+
...(passwordKey ? { passwordKey } : {}),
|
|
685
|
+
// Only when the human said yes in chat to this exact change.
|
|
686
|
+
...(acknowledgeWidening ? { accessWideningAcknowledged: true } : {}),
|
|
687
|
+
}),
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
let response;
|
|
691
|
+
try {
|
|
692
|
+
response = await deps.request(path, init);
|
|
693
|
+
}
|
|
694
|
+
catch (error) {
|
|
695
|
+
if (!init || (error instanceof FoleoError && (error.httpStatus ?? 0) < 500))
|
|
696
|
+
throw error;
|
|
697
|
+
// Retain the exact in-memory payload/key after response loss, including the
|
|
698
|
+
// stretched password. Never put secret-bearing recovery inputs in output.
|
|
699
|
+
response = await deps.request(path, init);
|
|
700
|
+
}
|
|
701
|
+
const result = await response.json();
|
|
702
|
+
deps.stdout(`${JSON.stringify(result, null, 2)}\n`);
|
|
703
|
+
return 0;
|
|
704
|
+
}
|
|
705
|
+
//# sourceMappingURL=workspaces.js.map
|