@insmind/cli 2.0.0 → 2.1.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.
- package/README.md +5 -0
- package/contracts/operations/agent.send/input.schema.json +1 -77
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +31 -15
- package/dist/src/bootstrap/create-runtime.js +103 -30
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +4 -1
- package/dist/src/cli/action-binding.js +17 -50
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +200 -30
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +14 -6
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +19 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
- package/skills/insmind-cli/references/update.md +2 -0
|
@@ -1,51 +1,52 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { parseHttpAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
2
2
|
import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
|
|
3
3
|
import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
|
|
4
|
+
import { mediaFilename, mediaTypeFromFilename } from "../../platform/media-type.js";
|
|
5
|
+
import { assertNoLocalAssetPaths } from "./argument-paths.js";
|
|
4
6
|
import { hasCanvasMetering } from "./canvas-pricing.js";
|
|
5
|
-
|
|
6
|
-
avif: "image/avif",
|
|
7
|
-
gif: "image/gif",
|
|
8
|
-
heic: "image/heic",
|
|
9
|
-
jpeg: "image/jpeg",
|
|
10
|
-
jpg: "image/jpeg",
|
|
11
|
-
mov: "video/quicktime",
|
|
12
|
-
mp3: "audio/mpeg",
|
|
13
|
-
mp4: "video/mp4",
|
|
14
|
-
png: "image/png",
|
|
15
|
-
wav: "audio/wav",
|
|
16
|
-
webm: "video/webm",
|
|
17
|
-
webp: "image/webp"
|
|
18
|
-
};
|
|
19
|
-
function inferRemoteMediaType(url) {
|
|
20
|
-
const segment = url.pathname.split("/").filter(Boolean).at(-1) ?? "";
|
|
21
|
-
let filename = segment;
|
|
7
|
+
function remoteMedia(value, name, path = name) {
|
|
22
8
|
try {
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
catch {
|
|
26
|
-
// The extension remains usable when the path contains malformed escapes.
|
|
27
|
-
}
|
|
28
|
-
const extension = filename.split(".").at(-1)?.toLowerCase();
|
|
29
|
-
return extension === undefined || extension === filename.toLowerCase()
|
|
30
|
-
? "application/octet-stream"
|
|
31
|
-
: mediaTypes[extension] ?? "application/octet-stream";
|
|
32
|
-
}
|
|
33
|
-
function remoteMedia(value, name) {
|
|
34
|
-
try {
|
|
35
|
-
const url = parseSafeRemoteAssetUrl(value);
|
|
9
|
+
const url = parseHttpAssetUrl(value);
|
|
36
10
|
return {
|
|
37
11
|
type: "media",
|
|
38
12
|
url: value,
|
|
39
|
-
mime:
|
|
13
|
+
mime: mediaTypeFromFilename(mediaFilename(url)) ?? "application/octet-stream",
|
|
40
14
|
name
|
|
41
15
|
};
|
|
42
16
|
}
|
|
43
17
|
catch (error) {
|
|
44
18
|
if (error instanceof UrlSafetyError)
|
|
45
|
-
throw new ToolInputError("invalid_asset_url", `/arguments/${
|
|
19
|
+
throw new ToolInputError("invalid_asset_url", `/arguments/${path}`, [], error);
|
|
46
20
|
throw error;
|
|
47
21
|
}
|
|
48
22
|
}
|
|
23
|
+
function prepareGenerationInput(model, parameters) {
|
|
24
|
+
const prompt = [];
|
|
25
|
+
const controls = Object.create(null);
|
|
26
|
+
const fields = new Map(model.parameters.map(field => [field.name, field]));
|
|
27
|
+
const references = [];
|
|
28
|
+
for (const [name, value] of Object.entries(parameters)) {
|
|
29
|
+
if (name === "prompt") {
|
|
30
|
+
if (typeof value !== "string")
|
|
31
|
+
throw new ToolInputError("prompt_must_be_text", "/arguments/prompt");
|
|
32
|
+
prompt.push({ type: "text", content: value });
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const field = fields.get(name);
|
|
36
|
+
if (field?.type === "uri" || field?.type === "uri[]") {
|
|
37
|
+
// assertModelArguments has checked and canonicalized these URI fields.
|
|
38
|
+
const uris = field.type === "uri[]" ? value : [value];
|
|
39
|
+
for (const [index, uri] of uris.entries()) {
|
|
40
|
+
const path = field.type === "uri[]" ? `${name}/${index}` : name;
|
|
41
|
+
references.push(uri.startsWith("file:") ? { type: "local", name, url: uri } : remoteMedia(uri, name, path));
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
assertNoLocalAssetPaths(value, `/arguments/${name}`, field?.type);
|
|
46
|
+
controls[name] = value;
|
|
47
|
+
}
|
|
48
|
+
return { prompt, controls, references };
|
|
49
|
+
}
|
|
49
50
|
export function createToolUseCases(dependencies) {
|
|
50
51
|
async function load(access, signal) {
|
|
51
52
|
signal.throwIfAborted();
|
|
@@ -61,12 +62,13 @@ export function createToolUseCases(dependencies) {
|
|
|
61
62
|
dependencies.telemetry.annotate({ tool_name: input.name,
|
|
62
63
|
...(typeof input.arguments.model === "string" ? { model_id: input.arguments.model } : {}) });
|
|
63
64
|
const catalog = await load(access, signal);
|
|
64
|
-
const model = await dependencies.telemetry.stage("input", () => {
|
|
65
|
+
const { model, parameters, generationInput } = await dependencies.telemetry.stage("input", () => {
|
|
65
66
|
const modelName = input.arguments.model;
|
|
66
67
|
if (typeof modelName !== "string")
|
|
67
68
|
throw new ToolInputError("model_required", "/arguments/model");
|
|
68
69
|
const selected = findToolModel(catalog, input.name, modelName);
|
|
69
70
|
assertModelArguments(selected, input.arguments);
|
|
71
|
+
const { model: _id, ...parameters } = input.arguments;
|
|
70
72
|
if (selected.execution?.kind === "canvas") {
|
|
71
73
|
for (const parameter of selected.parameters) {
|
|
72
74
|
const value = input.arguments[parameter.name];
|
|
@@ -77,86 +79,60 @@ export function createToolUseCases(dependencies) {
|
|
|
77
79
|
remoteMedia(uri, parameter.type === "uri[]" ? `${parameter.name}/${index}` : parameter.name);
|
|
78
80
|
}
|
|
79
81
|
}
|
|
82
|
+
return { model: selected, parameters };
|
|
80
83
|
}
|
|
81
|
-
return selected;
|
|
84
|
+
return { model: selected, parameters, generationInput: prepareGenerationInput(selected, parameters) };
|
|
82
85
|
});
|
|
83
|
-
const { model: ignoredModel, ...parameters } = input.arguments;
|
|
84
|
-
void ignoredModel;
|
|
85
86
|
dependencies.telemetry.annotate({
|
|
86
87
|
tool_name: model.tool,
|
|
87
88
|
model_id: model.model,
|
|
88
89
|
parameters
|
|
89
90
|
});
|
|
90
|
-
if (
|
|
91
|
+
if (!generationInput) {
|
|
91
92
|
const usage = { model: model.model, ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }) };
|
|
92
93
|
await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
|
|
93
94
|
return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
|
|
94
95
|
}
|
|
95
|
-
const prompt =
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
type: "media", url: upload.url, mime: upload.mediaType, name: parameter.name
|
|
117
|
-
}))
|
|
118
|
-
: remoteMedia(url, parameter.name);
|
|
119
|
-
prompt.push(media);
|
|
120
|
-
urls.push(media.url);
|
|
96
|
+
const { prompt, controls, references } = generationInput;
|
|
97
|
+
const explicitArguments = { ...parameters };
|
|
98
|
+
// Empty media lists remain explicit values, even though they add no prompt items.
|
|
99
|
+
for (const field of model.parameters) {
|
|
100
|
+
if (field.type === "uri[]" && Object.hasOwn(parameters, field.name))
|
|
101
|
+
explicitArguments[field.name] = [];
|
|
102
|
+
}
|
|
103
|
+
const prepareMedia = async () => {
|
|
104
|
+
const uploaded = new Map();
|
|
105
|
+
for (const ref of references) {
|
|
106
|
+
signal.throwIfAborted();
|
|
107
|
+
let media;
|
|
108
|
+
if (ref.type === "media")
|
|
109
|
+
media = ref;
|
|
110
|
+
else {
|
|
111
|
+
let asset = uploaded.get(ref.url);
|
|
112
|
+
if (!asset) {
|
|
113
|
+
asset = await dependencies.uploader.upload({ url: ref.url }, access, signal);
|
|
114
|
+
uploaded.set(ref.url, asset);
|
|
115
|
+
}
|
|
116
|
+
media = { type: "media", url: asset.url, mime: asset.mediaType, name: ref.name };
|
|
121
117
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
118
|
+
prompt.push(media);
|
|
119
|
+
if (Array.isArray(explicitArguments[ref.name]))
|
|
120
|
+
explicitArguments[ref.name].push(media.url);
|
|
121
|
+
else
|
|
122
|
+
explicitArguments[ref.name] = media.url;
|
|
125
123
|
}
|
|
126
124
|
};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
: parameter.type === "uri[]"
|
|
132
|
-
&& Array.isArray(value) && value.some((url) => url.startsWith("file:"));
|
|
133
|
-
});
|
|
134
|
-
if (hasLocalMedia) {
|
|
135
|
-
await dependencies.telemetry.stage("upload", prepare);
|
|
136
|
-
}
|
|
137
|
-
else {
|
|
138
|
-
await prepare();
|
|
139
|
-
}
|
|
125
|
+
if (references.some(ref => ref.type === "local"))
|
|
126
|
+
await dependencies.telemetry.stage("upload", prepareMedia);
|
|
127
|
+
else
|
|
128
|
+
await prepareMedia();
|
|
140
129
|
signal.throwIfAborted();
|
|
141
|
-
const
|
|
142
|
-
|
|
130
|
+
const mediaKind = model.tool === "video.generate" ? "video" : "image";
|
|
131
|
+
const requiresIntent = references.length > 0 || Object.values(controls).some(value => value === "");
|
|
143
132
|
const invocation = requiresIntent
|
|
144
|
-
? {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
prompt,
|
|
148
|
-
parameters: requestParameters,
|
|
149
|
-
explicitArguments: directArguments,
|
|
150
|
-
optionalMediaParameters: model.parameters
|
|
151
|
-
.filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
|
|
152
|
-
&& !parameter.required))
|
|
153
|
-
.map((parameter) => parameter.name)
|
|
154
|
-
}
|
|
155
|
-
: {
|
|
156
|
-
kind: "direct",
|
|
157
|
-
name: model.model,
|
|
158
|
-
arguments: directArguments
|
|
159
|
-
};
|
|
133
|
+
? { kind: "intent", model: model.model, mediaKind, prompt, parameters: controls, explicitArguments,
|
|
134
|
+
optionalMediaParameters: model.parameters.filter(field => !field.required && (field.type === "uri" || field.type === "uri[]")).map(field => field.name) }
|
|
135
|
+
: { kind: "direct", name: model.model, mediaKind, arguments: explicitArguments };
|
|
160
136
|
const usage = {
|
|
161
137
|
model: model.model,
|
|
162
138
|
...(model.cost === undefined ? {} : { cost: model.cost })
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Local CLI output contract exposed by `update check --schema`.
|
|
2
|
+
export const updateCheckSchema = {
|
|
3
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
4
|
+
type: "object",
|
|
5
|
+
additionalProperties: false,
|
|
6
|
+
required: ["status", "currentVersion"],
|
|
7
|
+
properties: {
|
|
8
|
+
status: { enum: ["available", "current", "managed", "unknown"] },
|
|
9
|
+
currentVersion: { type: "string" }, latestVersion: { type: "string" },
|
|
10
|
+
updateCommand: { type: "string" }, notice: { type: "string" }
|
|
11
|
+
},
|
|
12
|
+
oneOf: [
|
|
13
|
+
{ properties: { status: { const: "available" } }, required: ["latestVersion", "updateCommand"] },
|
|
14
|
+
{ properties: { status: { const: "current" }, notice: false, updateCommand: false }, required: ["latestVersion"] },
|
|
15
|
+
{ properties: { status: { enum: ["managed", "unknown"] }, latestVersion: false, updateCommand: false, notice: false } }
|
|
16
|
+
]
|
|
17
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// An IPC-enabled connector confirms that the notice reached its own stdout before the
|
|
2
|
+
// CLI spends its shared display window. Direct CLI / Skill calls use stdout acknowledgement.
|
|
3
|
+
export function waitForHostReceipt(signal, notice) {
|
|
4
|
+
if (!process.send || process.env.CLI_UPDATE_NOTICE_FORMAT !== "receipt")
|
|
5
|
+
return Promise.resolve();
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const failed = () => finish(new Error("Host did not deliver the update notice"));
|
|
8
|
+
const received = (value) => { if (value === "CLI_UPDATE_DISPLAYED")
|
|
9
|
+
finish(); };
|
|
10
|
+
const timer = setTimeout(failed, 2_000);
|
|
11
|
+
function finish(error) {
|
|
12
|
+
clearTimeout(timer);
|
|
13
|
+
signal.removeEventListener("abort", failed);
|
|
14
|
+
process.off("disconnect", failed);
|
|
15
|
+
process.off("message", received);
|
|
16
|
+
if (error)
|
|
17
|
+
reject(error);
|
|
18
|
+
else
|
|
19
|
+
resolve();
|
|
20
|
+
}
|
|
21
|
+
process.on("message", received);
|
|
22
|
+
process.once("disconnect", failed);
|
|
23
|
+
signal.addEventListener("abort", failed, { once: true });
|
|
24
|
+
if (!process.connected || signal.aborted)
|
|
25
|
+
failed();
|
|
26
|
+
else
|
|
27
|
+
process.send({ code: "CLI_UPDATE_READY", notice }, error => { if (error)
|
|
28
|
+
failed(); });
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { fstatSync } from "node:fs";
|
|
2
|
+
export function sameTerminal(stdout, stderr) {
|
|
3
|
+
if (stdout === stderr)
|
|
4
|
+
return true;
|
|
5
|
+
if (stdout !== process.stdout || stderr !== process.stderr || !process.stdout.isTTY || !process.stderr.isTTY)
|
|
6
|
+
return false;
|
|
7
|
+
try {
|
|
8
|
+
const a = fstatSync(1), b = fstatSync(2);
|
|
9
|
+
return a.rdev !== 0 && a.dev === b.dev && a.rdev === b.rdev && a.ino === b.ino;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function noticeWriter(stdout, stderr, shared, structured, label) {
|
|
16
|
+
return async (message, output) => {
|
|
17
|
+
const text = label + message + "\n";
|
|
18
|
+
const diagnostic = structured ? JSON.stringify({ notice: { code: "CLI_UPDATE_AVAILABLE", message } }) + "\n" : text;
|
|
19
|
+
async function send(sink, line) {
|
|
20
|
+
sink.write(line);
|
|
21
|
+
await sink.flush();
|
|
22
|
+
}
|
|
23
|
+
const writes = [send(stderr, diagnostic)];
|
|
24
|
+
if (output === "text" && !shared && !structured)
|
|
25
|
+
writes.push(send(stdout, text));
|
|
26
|
+
const results = await Promise.allSettled(writes);
|
|
27
|
+
if (results.every(result => result.status === "rejected"))
|
|
28
|
+
throw new Error("Update notice could not be delivered");
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { withFileLock } from "../../platform/file-lock.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import * as fileSystem from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
const STALE_LOCK_MS = 30_000;
|
|
6
|
+
export function createLocalUpdateNotificationLock(options) {
|
|
7
|
+
const path = join(options.directory, "update-check.lock");
|
|
8
|
+
return {
|
|
9
|
+
async acquire() {
|
|
10
|
+
await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
|
|
11
|
+
await fileSystem.chmod(options.directory, 0o700);
|
|
12
|
+
const first = await tryCreateLock(path);
|
|
13
|
+
if (first)
|
|
14
|
+
return releaseLock(path, first);
|
|
15
|
+
if (!await isStaleLock(path, options.now()))
|
|
16
|
+
return null;
|
|
17
|
+
// Two recoverers must not both unlink the lock: the first may already have
|
|
18
|
+
// replaced it with a live owner's file when the second resumes.
|
|
19
|
+
return withFileLock(path + ".recovery", async () => {
|
|
20
|
+
if (!await isStaleLock(path, options.now()))
|
|
21
|
+
return null;
|
|
22
|
+
await fileSystem.unlink(path).catch((error) => {
|
|
23
|
+
if (!isMissing(error))
|
|
24
|
+
throw error;
|
|
25
|
+
});
|
|
26
|
+
const recovered = await tryCreateLock(path);
|
|
27
|
+
return recovered ? releaseLock(path, recovered) : null;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
async function tryCreateLock(path) {
|
|
33
|
+
const token = randomUUID();
|
|
34
|
+
let handle;
|
|
35
|
+
try {
|
|
36
|
+
handle = await fileSystem.open(path, "wx", 0o600);
|
|
37
|
+
await handle.writeFile(token, "utf8");
|
|
38
|
+
await handle.sync();
|
|
39
|
+
await handle.close();
|
|
40
|
+
return token;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
await handle?.close().catch(() => undefined);
|
|
44
|
+
if (isExists(error))
|
|
45
|
+
return null;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function releaseLock(path, token) {
|
|
50
|
+
return async () => {
|
|
51
|
+
let current;
|
|
52
|
+
try {
|
|
53
|
+
current = await fileSystem.readFile(path, "utf8");
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (isMissing(error))
|
|
57
|
+
return;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
if (current === token)
|
|
61
|
+
await fileSystem.unlink(path);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
async function isStaleLock(path, now) {
|
|
65
|
+
try {
|
|
66
|
+
const stats = await fileSystem.stat(path);
|
|
67
|
+
return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
if (isMissing(error))
|
|
71
|
+
return true;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function isMissing(error) {
|
|
76
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
77
|
+
}
|
|
78
|
+
function isExists(error) {
|
|
79
|
+
return error instanceof Error && "code" in error && error.code === "EEXIST";
|
|
80
|
+
}
|