@t2nagi/filebrowser-quantum-mcp 0.0.0-stage → 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +21 -0
  3. package/README.ja.md +335 -0
  4. package/README.md +328 -2
  5. package/dist/client/api.js +222 -0
  6. package/dist/client/errors.js +120 -0
  7. package/dist/client/http.js +172 -0
  8. package/dist/client/types.js +2 -0
  9. package/dist/config.js +168 -0
  10. package/dist/core/approvals.js +75 -0
  11. package/dist/core/confirm.js +66 -0
  12. package/dist/core/content.js +28 -0
  13. package/dist/core/display.js +65 -0
  14. package/dist/core/inspect.js +180 -0
  15. package/dist/core/lock.js +54 -0
  16. package/dist/core/messages.js +131 -0
  17. package/dist/core/names.js +114 -0
  18. package/dist/core/paths.js +41 -0
  19. package/dist/core/reads.js +39 -0
  20. package/dist/core/recovery.js +55 -0
  21. package/dist/core/replace.js +131 -0
  22. package/dist/core/shares.js +46 -0
  23. package/dist/core/sources.js +18 -0
  24. package/dist/core/state.js +154 -0
  25. package/dist/core/text.js +44 -0
  26. package/dist/core/writeflow.js +497 -0
  27. package/dist/index.js +83 -0
  28. package/dist/log.js +32 -0
  29. package/dist/server.js +117 -0
  30. package/dist/tools/archive.js +159 -0
  31. package/dist/tools/common.js +68 -0
  32. package/dist/tools/create-folder.js +94 -0
  33. package/dist/tools/delete.js +195 -0
  34. package/dist/tools/find-duplicates.js +59 -0
  35. package/dist/tools/get-info.js +53 -0
  36. package/dist/tools/index.js +45 -0
  37. package/dist/tools/list-dir.js +68 -0
  38. package/dist/tools/list-sources.js +45 -0
  39. package/dist/tools/move-copy.js +231 -0
  40. package/dist/tools/read-file.js +69 -0
  41. package/dist/tools/rename.js +99 -0
  42. package/dist/tools/search.js +93 -0
  43. package/dist/tools/shares.js +219 -0
  44. package/dist/tools/unarchive.js +147 -0
  45. package/dist/tools/write-common.js +89 -0
  46. package/dist/tools/write-file.js +160 -0
  47. package/dist/version.js +5 -0
  48. package/npm-shrinkwrap.json +2657 -0
  49. package/package.json +57 -4
@@ -0,0 +1,99 @@
1
+ import { z } from "zod";
2
+ import { kindFromItemMessage, sanitizeServerMessage, ToolError } from "../client/errors.js";
3
+ import { approvalCodeArg } from "../core/approvals.js";
4
+ import { baseName, parentOf } from "../core/inspect.js";
5
+ import { checkNewName, foldName, invalidName } from "../core/names.js";
6
+ import { joinPath, normalizePath } from "../core/paths.js";
7
+ import { resolveSource } from "../core/sources.js";
8
+ import { assertWritable, onConflictArg, runWriteFlow } from "../core/writeflow.js";
9
+ import { defineTool, pathArg, sourceArg } from "./common.js";
10
+ import { callInfo, commonFields, commonOutput, conflictsOutput, flowDeps, result, WRITE_ANNOTATIONS, WRITE_NOTE, } from "./write-common.js";
11
+ const inputSchema = z.strictObject({
12
+ approvalCode: approvalCodeArg,
13
+ source: sourceArg,
14
+ path: pathArg("File or folder to rename, starting with /."),
15
+ newName: z
16
+ .string()
17
+ .min(1)
18
+ .max(255)
19
+ .describe("The new name only (no /). Stays in the same folder."),
20
+ onConflict: onConflictArg,
21
+ });
22
+ const outputSchema = z.strictObject({
23
+ ...commonOutput,
24
+ ...conflictsOutput,
25
+ source: z.string(),
26
+ from: z.string(),
27
+ to: z.string().optional(),
28
+ });
29
+ export const registerRename = (server, ctx) => defineTool(server, ctx.log, {
30
+ name: "fb_rename",
31
+ title: "Rename",
32
+ description: `Rename one file or folder within its folder. To move it elsewhere, use fb_move. New names must be valid on Windows, macOS and Linux. ${WRITE_NOTE}`,
33
+ inputSchema,
34
+ outputSchema,
35
+ annotations: WRITE_ANNOTATIONS,
36
+ previous: ctx.recovery,
37
+ handler: async (args, extra) => {
38
+ const facts = await ctx.state.ready();
39
+ const source = resolveSource(facts, args.source).name;
40
+ assertWritable(ctx.config, facts, [source]);
41
+ const path = normalizePath(args.path);
42
+ if (path === "/")
43
+ throw new ToolError("invalid_argument", "The root of a source cannot be renamed.");
44
+ if (args.newName.includes("/") || args.newName.includes("\\")) {
45
+ throw new ToolError("invalid_argument", "newName must be a name only, without / or \\. Use fb_move to change folders.");
46
+ }
47
+ const newName = args.newName.normalize("NFC");
48
+ const rule = checkNewName(newName);
49
+ if (rule)
50
+ throw invalidName(newName, rule);
51
+ const oldName = baseName(path);
52
+ if (newName === oldName)
53
+ throw new ToolError("invalid_argument", "newName is the same as the current name.");
54
+ if (foldName(newName) === foldName(oldName)) {
55
+ throw invalidName(newName, "case_conflict", "Changing only upper/lower case would clash with itself on Windows and macOS. Rename it to a different name first, then to the name you want.");
56
+ }
57
+ const from = await ctx.client.getResource(source, path, { signal: extra.signal });
58
+ const outcome = await runWriteFlow(flowDeps(ctx, facts), {
59
+ approval: { code: args.approvalCode, args },
60
+ tool: "fb_rename",
61
+ verb: "rename",
62
+ items: [
63
+ {
64
+ fromSource: source,
65
+ from: path,
66
+ fromInfo: { size: from.size, modified: from.modified },
67
+ toSource: source,
68
+ to: joinPath(parentOf(path), newName),
69
+ newType: from.type === "directory" ? "directory" : "file",
70
+ newSize: from.size,
71
+ },
72
+ ],
73
+ onConflict: args.onConflict,
74
+ crossSource: false,
75
+ renameStyle: (p) => (p.item.newType === "directory" ? "folder" : "file"),
76
+ execute: async (finals, run) => {
77
+ const f = finals[0];
78
+ if (!f)
79
+ return;
80
+ // Same folder: the server renames on disk, replacing a file atomically (design §6.2.5).
81
+ const res = await run.send([{ fromSource: source, from: path, toSource: source, to: f.finalTo }], [], (signal) => ctx.client.moveCopy("rename", [{ fromSource: source, fromPath: path, toSource: source, toPath: f.finalTo }], { signal }));
82
+ const failed = res.failed[0];
83
+ if (failed) {
84
+ const message = failed.message ?? "";
85
+ throw new ToolError(kindFromItemMessage(message), `The rename failed (server: ${sanitizeServerMessage(message)}).`, {
86
+ source,
87
+ path,
88
+ });
89
+ }
90
+ },
91
+ }, callInfo(extra));
92
+ return result({
93
+ ...commonFields(outcome),
94
+ source,
95
+ from: path,
96
+ ...(outcome.status === "completed" ? { to: outcome.finals[0]?.finalTo } : {}),
97
+ }, outcome);
98
+ },
99
+ });
@@ -0,0 +1,93 @@
1
+ import { z } from "zod";
2
+ import { ToolError } from "../client/errors.js";
3
+ import { normalizePath } from "../core/paths.js";
4
+ import { resolveSource } from "../core/sources.js";
5
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS } from "./common.js";
6
+ const isoDate = z.iso
7
+ .datetime({ offset: true })
8
+ .describe("ISO 8601 date-time, e.g. 2026-11-29T10:00:00Z. Compared with second precision.");
9
+ const inputSchema = z.strictObject({
10
+ query: z
11
+ .string()
12
+ .min(1)
13
+ .max(256)
14
+ .optional()
15
+ .describe("Search text (the server needs at least 3 characters)."),
16
+ terms: z
17
+ .array(z.string().min(1).max(256))
18
+ .min(1)
19
+ .max(20)
20
+ .optional()
21
+ .describe('Literal terms, combined with OR unless termJoin is "and". Use instead of query.'),
22
+ termJoin: z.enum(["and", "or"]).optional(),
23
+ sources: z
24
+ .array(z.string().min(1).max(255))
25
+ .min(1)
26
+ .max(100)
27
+ .optional()
28
+ .describe("Sources to search. Omit to use the default source."),
29
+ path: pathArg("Limit the search to this folder. Only with a single source.").optional(),
30
+ useWildcard: z.boolean().optional().describe("Treat * and ? in the query as wildcards."),
31
+ modifiedAfter: isoDate.optional(),
32
+ modifiedBefore: isoDate.optional(),
33
+ limit: z.number().int().min(1).max(1000).default(100),
34
+ });
35
+ const outputSchema = z.strictObject({
36
+ results: z.array(z.strictObject({
37
+ source: z.string(),
38
+ path: z.string(),
39
+ type: z.string(),
40
+ size: z.number(),
41
+ modified: z.string().describe("ISO 8601, UTC, second precision."),
42
+ })),
43
+ truncated: z
44
+ .boolean()
45
+ .describe("True when the number of results reached limit, so there may be more."),
46
+ });
47
+ const toUnixSeconds = (iso, round) => iso === undefined ? undefined : round(Date.parse(iso) / 1000);
48
+ export const registerSearch = (server, ctx) => defineTool(server, ctx.log, {
49
+ name: "fb_search",
50
+ title: "Search files",
51
+ description: "Search file and folder names in the server's index. Give query or terms. The server may cap results below limit (searchResultsLimit), so results can be incomplete even when truncated is false. Hidden and excluded items are not found.",
52
+ inputSchema,
53
+ outputSchema,
54
+ annotations: READ_ONLY_ANNOTATIONS,
55
+ handler: async (args, extra) => {
56
+ if (args.query === undefined && args.terms === undefined) {
57
+ throw new ToolError("invalid_argument", "Give either query or terms.");
58
+ }
59
+ if (args.termJoin !== undefined && args.terms === undefined) {
60
+ throw new ToolError("invalid_argument", "termJoin can only be used with terms.");
61
+ }
62
+ const facts = await ctx.state.ready();
63
+ const names = args.sources ? [...new Set(args.sources)] : [undefined];
64
+ const sources = names.map((name) => resolveSource(facts, name).name);
65
+ if (args.path !== undefined && sources.length !== 1) {
66
+ throw new ToolError("invalid_argument", "path can only be used when searching a single source.");
67
+ }
68
+ const { results, serverCount } = await ctx.client.search({
69
+ query: args.query,
70
+ terms: args.terms,
71
+ termJoin: args.termJoin,
72
+ useWildcard: args.useWildcard,
73
+ sources,
74
+ path: args.path === undefined ? undefined : normalizePath(args.path),
75
+ limit: args.limit,
76
+ newerThan: toUnixSeconds(args.modifiedAfter, Math.floor),
77
+ olderThan: toUnixSeconds(args.modifiedBefore, Math.ceil),
78
+ }, { signal: extra.signal });
79
+ return {
80
+ structured: {
81
+ results: results.slice(0, args.limit).map(({ source, path, type, size, modified }) => ({
82
+ source,
83
+ path,
84
+ type,
85
+ size,
86
+ modified,
87
+ })),
88
+ // Judged on what the server returned, not on what is left after filtering.
89
+ truncated: serverCount >= args.limit,
90
+ },
91
+ };
92
+ },
93
+ });
@@ -0,0 +1,219 @@
1
+ // fb_list_shares, fb_create_share, fb_delete_share (design §6.3, §6.5).
2
+ import { z } from "zod";
3
+ import { ToolError } from "../client/errors.js";
4
+ import { askUser } from "../core/confirm.js";
5
+ import { displayPath, formatTime } from "../core/display.js";
6
+ import { Inspector, sameProbe } from "../core/inspect.js";
7
+ import { cancelMessage, shareTexts } from "../core/messages.js";
8
+ import { normalizePath } from "../core/paths.js";
9
+ import { ownShares } from "../core/shares.js";
10
+ import { resolveSource } from "../core/sources.js";
11
+ import { assertWritable } from "../core/writeflow.js";
12
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS, sourceArg } from "./common.js";
13
+ import { commonOutput } from "./write-common.js";
14
+ const iso = (unixSeconds) => unixSeconds && unixSeconds > 0
15
+ ? new Date(unixSeconds * 1000).toISOString().replace(/\.000Z$/, "Z")
16
+ : null;
17
+ const ARCHIVE_EXT = /\.(zip|tar\.gz|tgz|tar|7z|rar)$/i;
18
+ const UNIT_SECONDS = { minutes: 60, hours: 3600, days: 86400 };
19
+ export const registerListShares = (server, ctx) => {
20
+ const outputSchema = z.strictObject({
21
+ shares: z.array(z.strictObject({
22
+ id: z.string().describe("Use with fb_delete_share."),
23
+ source: z.string(),
24
+ path: z.string(),
25
+ expires: z.string().nullable(),
26
+ hasPassword: z.boolean(),
27
+ downloads: z.number(),
28
+ downloadsLimit: z.number().nullable(),
29
+ })),
30
+ });
31
+ return defineTool(server, ctx.log, {
32
+ name: "fb_list_shares",
33
+ title: "List share links",
34
+ description: "List your own share links (not the URLs: ask the user to open them in FileBrowser). Use the id with fb_delete_share.",
35
+ inputSchema: z.strictObject({}),
36
+ outputSchema,
37
+ annotations: READ_ONLY_ANNOTATIONS,
38
+ handler: async (_args, extra) => {
39
+ const facts = await ctx.state.ready();
40
+ const list = await ctx.client.listShares({ signal: extra.signal });
41
+ return {
42
+ structured: {
43
+ shares: ownShares(list, facts).map((s) => ({
44
+ id: ctx.shareIds.idFor(s.hash),
45
+ source: s.source,
46
+ path: s.path,
47
+ expires: iso(s.entry.expire),
48
+ hasPassword: s.entry.hasPassword === true,
49
+ downloads: s.entry.downloads ?? 0,
50
+ downloadsLimit: s.entry.downloadsLimit ? s.entry.downloadsLimit : null,
51
+ })),
52
+ },
53
+ };
54
+ },
55
+ });
56
+ };
57
+ export const registerCreateShare = (server, ctx) => {
58
+ const inputSchema = z.strictObject({
59
+ source: sourceArg,
60
+ path: pathArg("File to share, starting with /."),
61
+ expiresIn: z
62
+ .strictObject({ value: z.number().int().min(1), unit: z.enum(["minutes", "hours", "days"]) })
63
+ .describe(`Required. At most ${ctx.config.maxShareDays} days in total.`),
64
+ password: z.string().min(1).max(256).optional(),
65
+ downloadsLimit: z.number().int().min(1).max(1_000_000).optional(),
66
+ });
67
+ const outputSchema = z.strictObject({
68
+ status: commonOutput.status,
69
+ cancelReason: commonOutput.cancelReason,
70
+ decidedBy: commonOutput.decidedBy,
71
+ previousOperation: commonOutput.previousOperation,
72
+ id: z.string().optional(),
73
+ source: z.string(),
74
+ path: z.string(),
75
+ shareURL: z.string().optional().describe("Give this to the user. It is not shown again."),
76
+ expires: z.string().nullable().optional(),
77
+ hasPassword: z.boolean().optional(),
78
+ });
79
+ return defineTool(server, ctx.log, {
80
+ name: "fb_create_share",
81
+ title: "Create share link (public)",
82
+ description: `Create a public share link: anyone with the link can open the item without logging in. The user must approve every link. ${ctx.config.allowFolderShare ? "Folders can be shared." : "Folders and archives cannot be shared."} If the user declines, do not retry on your own.`,
83
+ inputSchema,
84
+ outputSchema,
85
+ annotations: {
86
+ readOnlyHint: false,
87
+ destructiveHint: false,
88
+ idempotentHint: false,
89
+ openWorldHint: true,
90
+ },
91
+ previous: ctx.recovery,
92
+ handler: async (args, extra) => {
93
+ const facts = await ctx.state.ready();
94
+ const source = resolveSource(facts, args.source).name;
95
+ assertWritable(ctx.config, facts, [source]);
96
+ const path = normalizePath(args.path);
97
+ if (path === "/")
98
+ throw new ToolError("invalid_argument", "The root of a source cannot be shared.");
99
+ const seconds = args.expiresIn.value * UNIT_SECONDS[args.expiresIn.unit];
100
+ if (seconds > ctx.config.maxShareDays * 86400) {
101
+ throw new ToolError("invalid_argument", `Share links can last at most ${ctx.config.maxShareDays} days (FILEBROWSER_MAX_SHARE_DAYS).`);
102
+ }
103
+ if (!ctx.elicitor.supported()) {
104
+ // Never relaxed, not even by trust-client (design §6.2.8).
105
+ throw new ToolError("confirmation_required", "Creating a share link needs the user's confirmation, but the client does not support it (elicitation). Nothing was created. The user can create the link in FileBrowser.", { details: { reason: ["share_link"], alternatives: [] } });
106
+ }
107
+ // The type comes from a direct GET (a symlink to a folder lists as a file).
108
+ const probe = await new Inspector(ctx.client, facts, { signal: extra.signal }).probe(source, path);
109
+ if (probe.kind !== "present") {
110
+ throw new ToolError(probe.kind === "absent" ? "not_found" : "permission_denied", "The item does not exist or cannot be inspected.", {
111
+ source,
112
+ path,
113
+ });
114
+ }
115
+ const folder = probe.type === "directory";
116
+ if (!ctx.config.allowFolderShare && (folder || ARCHIVE_EXT.test(path))) {
117
+ throw new ToolError("invalid_argument", folder
118
+ ? "Sharing folders is disabled (FILEBROWSER_ALLOW_FOLDER_SHARE): hidden files inside a shared folder would be public too."
119
+ : "Sharing archives is disabled (FILEBROWSER_ALLOW_FOLDER_SHARE): an archive can contain a whole folder, hidden files included.", { source, path });
120
+ }
121
+ const t = shareTexts(ctx.config.lang);
122
+ const until = new Date(Date.now() + seconds * 1000).toISOString();
123
+ const lines = [
124
+ t.head,
125
+ "----",
126
+ `${displayPath(source, path)}(${folder ? t.folder : t.file})`,
127
+ t.expires(formatTime(until)),
128
+ t.password(args.password !== undefined),
129
+ t.downloads(args.downloadsLimit),
130
+ ];
131
+ if (folder)
132
+ lines.push(t.folderWarning);
133
+ const answer = await askUser(ctx.elicitor, { message: lines.join("\n"), confirmDescription: t.confirm }, {
134
+ timeout: ctx.config.confirmTimeoutMs,
135
+ signal: extra.signal,
136
+ relatedRequestId: extra.requestId,
137
+ });
138
+ if (!answer.ok) {
139
+ if (answer.aborted)
140
+ throw new ToolError("cancelled", "The tool call was cancelled.");
141
+ return {
142
+ structured: {
143
+ status: "cancelled",
144
+ cancelReason: answer.reason,
145
+ decidedBy: "user",
146
+ source,
147
+ path,
148
+ },
149
+ note: cancelMessage(answer.reason),
150
+ };
151
+ }
152
+ // The item must still be what the user approved.
153
+ const now = await new Inspector(ctx.client, facts, {}).probe(source, path);
154
+ if (!sameProbe(probe, now)) {
155
+ throw new ToolError("conflict", "The item changed while the share link was being confirmed. Nothing was created.", {
156
+ source,
157
+ path,
158
+ details: { reason: "changed_before_send", conflicts: [], allowedResolutions: [] },
159
+ });
160
+ }
161
+ const created = await ctx.client.createShare({
162
+ source,
163
+ path,
164
+ expires: String(args.expiresIn.value), // a string: numbers are rejected (verified)
165
+ unit: args.expiresIn.unit,
166
+ ...(args.password !== undefined ? { password: args.password } : {}),
167
+ ...(args.downloadsLimit !== undefined ? { downloadsLimit: args.downloadsLimit } : {}),
168
+ allowCreate: false,
169
+ allowModify: false,
170
+ allowDelete: false,
171
+ allowReplacements: false,
172
+ showHidden: false,
173
+ keepAfterExpiration: false,
174
+ canEditShare: false,
175
+ enableOnlyOffice: false,
176
+ });
177
+ if (!created.hash)
178
+ throw new ToolError("server_error", "The server did not return the new share.");
179
+ return {
180
+ structured: {
181
+ status: "completed",
182
+ decidedBy: "user",
183
+ id: ctx.shareIds.idFor(created.hash),
184
+ source,
185
+ path,
186
+ ...(created.shareURL ? { shareURL: created.shareURL } : {}),
187
+ expires: iso(created.expire),
188
+ hasPassword: args.password !== undefined,
189
+ },
190
+ };
191
+ },
192
+ });
193
+ };
194
+ export const registerDeleteShare = (server, ctx) => defineTool(server, ctx.log, {
195
+ name: "fb_delete_share",
196
+ title: "Delete share link",
197
+ description: "Delete one of your share links by the id from fb_list_shares or fb_create_share.",
198
+ inputSchema: z.strictObject({ id: z.string().min(1).max(64) }),
199
+ outputSchema: z.strictObject({ id: z.string(), deleted: z.literal(true) }),
200
+ annotations: {
201
+ readOnlyHint: false,
202
+ destructiveHint: true,
203
+ idempotentHint: true,
204
+ openWorldHint: false,
205
+ },
206
+ handler: async (args, extra) => {
207
+ const facts = await ctx.state.ready();
208
+ const notFound = () => new ToolError("not_found", "No such share link. Call fb_list_shares to get current ids (ids do not survive a restart).");
209
+ const hash = ctx.shareIds.hashFor(args.id);
210
+ if (!hash)
211
+ throw notFound();
212
+ // Only the user's own shares in allowed sources (never another user's, design §3.2).
213
+ const mine = ownShares(await ctx.client.listShares({ signal: extra.signal }), facts);
214
+ if (!mine.some((s) => s.hash === hash))
215
+ throw notFound();
216
+ await ctx.client.deleteShare(hash, { signal: extra.signal });
217
+ return { structured: { id: args.id, deleted: true } };
218
+ },
219
+ });
@@ -0,0 +1,147 @@
1
+ import { z } from "zod";
2
+ import { ToolError } from "../client/errors.js";
3
+ import { approvalCodeArg } from "../core/approvals.js";
4
+ import { Inspector } from "../core/inspect.js";
5
+ import { normalizePath } from "../core/paths.js";
6
+ import { resolveSource } from "../core/sources.js";
7
+ import { assertWritable, runWriteFlow } from "../core/writeflow.js";
8
+ import { defineTool, pathArg, sourceArg } from "./common.js";
9
+ import { callInfo, commonFields, commonOutput, conflictsOutput, flowDeps, result, WRITE_ANNOTATIONS, WRITE_NOTE, } from "./write-common.js";
10
+ const inputSchema = z.strictObject({
11
+ approvalCode: approvalCodeArg,
12
+ source: sourceArg,
13
+ path: pathArg("Archive to extract (.zip, .tar.gz, .tgz), starting with /."),
14
+ toSource: z
15
+ .string()
16
+ .min(1)
17
+ .max(255)
18
+ .optional()
19
+ .describe("Destination source. Default: same as source."),
20
+ toPath: pathArg("Folder to extract into. It must not exist yet; it is created."),
21
+ filenameEncoding: z
22
+ .enum(["utf-8", "cp932", "gb18030", "big5", "euc-kr", "cp437", "windows-1252"])
23
+ .optional()
24
+ .describe("Only if file names come out garbled: the encoding of names in a ZIP."),
25
+ onConflict: z
26
+ .enum(["ask", "rename"])
27
+ .default("ask")
28
+ .describe('If the folder exists: "ask" (the user decides) or "rename" (extract into name(1)). Never merges.'),
29
+ });
30
+ const outputSchema = z.strictObject({
31
+ ...commonOutput,
32
+ ...conflictsOutput,
33
+ source: z.string(),
34
+ path: z.string().optional().describe("The folder extracted into (a new name if renamed)."),
35
+ });
36
+ export const registerUnarchive = (server, ctx) => defineTool(server, ctx.log, {
37
+ name: "fb_unarchive",
38
+ title: "Extract archive",
39
+ description: `Extract an archive into a new folder (never into an existing one, because extraction silently overwrites files). Names inside the archive are not checked. The archive is never deleted. ${WRITE_NOTE}`,
40
+ inputSchema,
41
+ outputSchema,
42
+ annotations: WRITE_ANNOTATIONS,
43
+ previous: ctx.recovery,
44
+ handler: async (args, extra) => {
45
+ const facts = await ctx.state.ready();
46
+ const source = resolveSource(facts, args.source).name;
47
+ const toSource = args.toSource === undefined ? source : resolveSource(facts, args.toSource).name;
48
+ const path = normalizePath(args.path);
49
+ const toPath = normalizePath(args.toPath, "toPath");
50
+ assertWritable(ctx.config, facts, [toSource]);
51
+ const archive = await new Inspector(ctx.client, facts, { signal: extra.signal }).probe(source, path);
52
+ if (archive.kind !== "present" || archive.type === "directory") {
53
+ throw new ToolError(archive.kind === "absent" ? "not_found" : "invalid_argument", "path must be an existing archive file.", {
54
+ source,
55
+ path,
56
+ });
57
+ }
58
+ const outcome = await runWriteFlow(flowDeps(ctx, facts), {
59
+ approval: { code: args.approvalCode, args },
60
+ tool: "fb_unarchive",
61
+ verb: "unarchive",
62
+ items: [
63
+ {
64
+ fromSource: source,
65
+ from: path,
66
+ fromInfo: { size: archive.size, modified: archive.modified },
67
+ toSource,
68
+ to: toPath,
69
+ newType: "directory",
70
+ },
71
+ ],
72
+ onConflict: args.onConflict,
73
+ crossSource: toSource !== source,
74
+ renameStyle: () => "folder",
75
+ neverOverwrite: true,
76
+ classify: (p) => {
77
+ if (p.existing.kind === "present" && p.existing.type !== "directory") {
78
+ throw new ToolError("invalid_argument", "toPath is an existing file.", {
79
+ source: toSource,
80
+ path: p.dest,
81
+ });
82
+ }
83
+ return "conflict"; // an existing folder, even if it looks empty
84
+ },
85
+ execute: async (finals, run) => {
86
+ const f = finals[0];
87
+ if (!f)
88
+ return;
89
+ await run.createParents(toSource, f.missing);
90
+ // Create the destination only now, so a cancel leaves no empty folder.
91
+ try {
92
+ await run.send([{ toSource, to: f.finalTo }], [], (signal) => ctx.client.createFolder(toSource, f.finalTo, { signal }));
93
+ }
94
+ catch (err) {
95
+ if (err instanceof ToolError && err.kind === "already_exists") {
96
+ throw new ToolError("conflict", "The destination folder appeared while this was being confirmed. Nothing was extracted.", {
97
+ source: toSource,
98
+ path: f.finalTo,
99
+ details: {
100
+ reason: "changed_before_send",
101
+ conflicts: [],
102
+ allowedResolutions: [],
103
+ },
104
+ });
105
+ }
106
+ throw err;
107
+ }
108
+ run.createdFolders.push(f.finalTo);
109
+ try {
110
+ await run.send([{ fromSource: source, from: path, toSource, to: f.finalTo }], [], (signal) => ctx.client.unarchive({
111
+ fromSource: source,
112
+ toSource,
113
+ path,
114
+ destination: f.finalTo,
115
+ ...(args.filenameEncoding ? { filenameEncoding: args.filenameEncoding } : {}),
116
+ }, { signal }));
117
+ }
118
+ catch (err) {
119
+ if (err instanceof ToolError && err.kind !== "timeout") {
120
+ run.leftovers.push({
121
+ source: toSource,
122
+ path: f.finalTo,
123
+ kind: "partial_copy",
124
+ originalStillExists: true,
125
+ });
126
+ const hint = err.kind === "server_error"
127
+ ? " The archive may contain unsafe entries (../, absolute paths, symlinks) or be damaged; in that case nothing was extracted."
128
+ : err.kind === "invalid_argument"
129
+ ? " If file names use a legacy encoding, try filenameEncoding."
130
+ : "";
131
+ throw new ToolError(err.kind, `${err.message}${hint}`, {
132
+ source: toSource,
133
+ path: f.finalTo,
134
+ details: { createdFolders: run.createdFolders, leftovers: run.leftovers },
135
+ });
136
+ }
137
+ throw err;
138
+ }
139
+ },
140
+ }, callInfo(extra));
141
+ return result({
142
+ ...commonFields(outcome),
143
+ source: toSource,
144
+ ...(outcome.status === "completed" ? { path: outcome.finals[0]?.finalTo } : {}),
145
+ }, outcome);
146
+ },
147
+ });
@@ -0,0 +1,89 @@
1
+ // Pieces shared by the write tools: annotations, output fields (design §6.2.11),
2
+ // and turning a flow outcome into a tool result.
3
+ import { z } from "zod";
4
+ import { previousOperationSchema } from "../core/recovery.js";
5
+ import { cancelReasonSchema, conflictOutSchema, decidedBySchema, leftoverSchema, statusSchema, } from "../core/writeflow.js";
6
+ /** Writes that may overwrite (design §6.1). */
7
+ export const WRITE_ANNOTATIONS = {
8
+ readOnlyHint: false,
9
+ destructiveHint: true,
10
+ idempotentHint: false,
11
+ openWorldHint: false,
12
+ };
13
+ export const WRITE_NOTE = "Overwrites, writes to another source and writes into shared locations need the user's confirmation; if the user cancels, do not retry with different arguments on your own. After a timeout or interruption, check the state (fb_list_dir, fb_get_info) before retrying.";
14
+ /** Output fields every confirming write tool has. */
15
+ export const commonOutput = {
16
+ status: statusSchema,
17
+ cancelReason: cancelReasonSchema.optional(),
18
+ decidedBy: decidedBySchema,
19
+ createdFolders: z.array(z.string()).optional(),
20
+ leftovers: z.array(leftoverSchema).optional(),
21
+ previousOperation: previousOperationSchema.optional(),
22
+ };
23
+ export const conflictsOutput = { conflicts: z.array(conflictOutSchema) };
24
+ export function flowDeps(ctx, facts) {
25
+ return {
26
+ config: ctx.config,
27
+ client: ctx.client,
28
+ facts,
29
+ lock: ctx.lock,
30
+ recovery: ctx.recovery,
31
+ elicitor: ctx.elicitor,
32
+ log: ctx.log,
33
+ approvals: ctx.approvals,
34
+ };
35
+ }
36
+ const PROGRESS_INTERVAL_MS = 10_000;
37
+ /**
38
+ * Call info for the write flow. If the client sent a progressToken, progress
39
+ * notifications are sent every 10 s while waiting (design §5.4); `progress` is the
40
+ * elapsed seconds, which keeps increasing as the spec requires.
41
+ */
42
+ export function callInfo(extra) {
43
+ const token = extra._meta?.progressToken;
44
+ const info = { signal: extra.signal, requestId: extra.requestId };
45
+ if (token !== undefined) {
46
+ const started = Date.now();
47
+ info.progress = (message) => {
48
+ const timer = setInterval(() => {
49
+ extra
50
+ .sendNotification({
51
+ method: "notifications/progress",
52
+ params: {
53
+ progressToken: token,
54
+ progress: Math.round((Date.now() - started) / 1000),
55
+ message,
56
+ },
57
+ })
58
+ .catch(() => { });
59
+ }, PROGRESS_INTERVAL_MS);
60
+ timer.unref();
61
+ return () => clearInterval(timer);
62
+ };
63
+ }
64
+ return info;
65
+ }
66
+ /** Common fields of a flow outcome, ready to spread into a tool's structured output. */
67
+ export function commonFields(outcome) {
68
+ if (outcome.status === "cancelled") {
69
+ return {
70
+ status: "cancelled",
71
+ cancelReason: outcome.cancelReason,
72
+ decidedBy: outcome.decidedBy,
73
+ conflicts: outcome.conflicts,
74
+ };
75
+ }
76
+ const fields = {
77
+ status: "completed",
78
+ decidedBy: outcome.decidedBy,
79
+ conflicts: outcome.conflicts,
80
+ };
81
+ if (outcome.createdFolders.length > 0)
82
+ fields.createdFolders = outcome.createdFolders;
83
+ if (outcome.leftovers.length > 0)
84
+ fields.leftovers = outcome.leftovers;
85
+ return fields;
86
+ }
87
+ export function result(structured, outcome) {
88
+ return outcome.status === "cancelled" ? { structured, note: outcome.message } : { structured };
89
+ }