@eduardo191labs/opencode-free-pi 0.3.21 → 0.4.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/README.md +64 -0
- package/dist/plugin.js +36 -5
- package/dist/session/hooks.d.ts +3 -1
- package/dist/session/hooks.js +28 -1
- package/dist/state.d.ts +1 -0
- package/dist/state.js +1 -0
- package/dist/tools/account.d.ts +10 -0
- package/dist/tools/account.js +103 -0
- package/dist/tools/api.d.ts +54 -0
- package/dist/tools/api.js +120 -0
- package/dist/tools/fusion.d.ts +45 -0
- package/dist/tools/fusion.js +162 -0
- package/dist/tools/image-generate.d.ts +13 -0
- package/dist/tools/image-generate.js +143 -0
- package/dist/tools/usage.d.ts +12 -0
- package/dist/tools/usage.js +125 -0
- package/dist/tools/vision-queue.d.ts +19 -0
- package/dist/tools/vision-queue.js +149 -0
- package/dist/tools/vision.js +150 -53
- package/dist/tools/web.d.ts +12 -0
- package/dist/tools/web.js +165 -0
- package/dist/types.d.ts +4 -0
- package/package.json +2 -2
- package/src/plugin.ts +50 -5
- package/src/session/hooks.ts +39 -0
- package/src/state.ts +2 -0
- package/src/tools/account.ts +135 -0
- package/src/tools/api.ts +178 -0
- package/src/tools/fusion.ts +221 -0
- package/src/tools/image-generate.ts +195 -0
- package/src/tools/usage.ts +163 -0
- package/src/tools/vision-queue.ts +161 -0
- package/src/tools/vision.ts +180 -56
- package/src/tools/web.ts +212 -0
- package/src/types.ts +1 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `generate_image`, the free-pi text-to-image tool.
|
|
3
|
+
*
|
|
4
|
+
* The models cannot see images, so the tool writes the server's image into
|
|
5
|
+
* `images/` inside the project and returns the relative path. Same endpoint,
|
|
6
|
+
* limits and error wording as the provider CLI.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { mkdir, open } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { Plugin } from "@opencode/plugin";
|
|
13
|
+
import type { Deps } from "../deps.js";
|
|
14
|
+
import {
|
|
15
|
+
done,
|
|
16
|
+
fail,
|
|
17
|
+
freePiRequest,
|
|
18
|
+
GATED_TEXT,
|
|
19
|
+
isGatedSession,
|
|
20
|
+
mappedText,
|
|
21
|
+
} from "./api.js";
|
|
22
|
+
|
|
23
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
24
|
+
const TIMEOUT_MS = 120_000;
|
|
25
|
+
|
|
26
|
+
const EXT: Record<string, string> = {
|
|
27
|
+
"image/png": "png",
|
|
28
|
+
"image/jpeg": "jpg",
|
|
29
|
+
"image/webp": "webp",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const ERRORS: Record<string, string> = {
|
|
33
|
+
guest_login_required:
|
|
34
|
+
"This tool needs a GitHub sign-in; the guest trial cannot use it. Do not retry or work around it; tell the user to sign in, and continue without this tool.",
|
|
35
|
+
guest_unavailable:
|
|
36
|
+
"The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
|
|
37
|
+
daily_cap:
|
|
38
|
+
"The user's free allowance for today is used up. Do not retry. Tell the user they can get credits at freepi.ai/extra-credits, and continue without this tool.",
|
|
39
|
+
rolling_cap:
|
|
40
|
+
"The user's short-term usage limit is reached. Do not retry; continue without this tool.",
|
|
41
|
+
rate_limited:
|
|
42
|
+
"Too many image requests right now. Do not call generate_image again in this turn unless the user asks.",
|
|
43
|
+
not_configured:
|
|
44
|
+
"Image generation is not available on this server. Do not call generate_image again in this session.",
|
|
45
|
+
upstream_error: "The image provider failed. You may retry once.",
|
|
46
|
+
account_review:
|
|
47
|
+
"This account is under review, so image generation is disabled. Do not retry; tell the user and continue without it.",
|
|
48
|
+
content_rejected:
|
|
49
|
+
"The image provider rejected this prompt. Do not retry the same prompt; tell the user and offer to reword it.",
|
|
50
|
+
invalid_request:
|
|
51
|
+
"The server rejected this request. Do not retry it unchanged.",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const IMAGE_INPUT = {
|
|
55
|
+
type: "object",
|
|
56
|
+
additionalProperties: false,
|
|
57
|
+
required: ["prompt"],
|
|
58
|
+
properties: {
|
|
59
|
+
prompt: {
|
|
60
|
+
type: "string",
|
|
61
|
+
minLength: 1,
|
|
62
|
+
maxLength: 1_000,
|
|
63
|
+
description:
|
|
64
|
+
"What to draw: subject, style, any exact text to render, and composition",
|
|
65
|
+
},
|
|
66
|
+
aspect_ratio: {
|
|
67
|
+
type: "string",
|
|
68
|
+
enum: ["1:1", "16:9", "9:16", "4:3", "3:2"],
|
|
69
|
+
description: "Default 1:1",
|
|
70
|
+
},
|
|
71
|
+
name: {
|
|
72
|
+
type: "string",
|
|
73
|
+
maxLength: 60,
|
|
74
|
+
description:
|
|
75
|
+
"Short file name hint, e.g. hero-banner; used only for the saved file's name",
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
} as const;
|
|
79
|
+
|
|
80
|
+
export function slug(value: string): string {
|
|
81
|
+
return (
|
|
82
|
+
value
|
|
83
|
+
.toLowerCase()
|
|
84
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
85
|
+
.replace(/^-+/, "")
|
|
86
|
+
.slice(0, 40)
|
|
87
|
+
.replace(/-+$/, "") || "image"
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function saveImage(
|
|
92
|
+
directory: string,
|
|
93
|
+
relative: string,
|
|
94
|
+
bytes: Buffer,
|
|
95
|
+
): Promise<string | undefined> {
|
|
96
|
+
try {
|
|
97
|
+
await mkdir(join(directory, "images"), { recursive: true });
|
|
98
|
+
const handle = await open(join(directory, relative), "wx");
|
|
99
|
+
try {
|
|
100
|
+
await handle.writeFile(bytes);
|
|
101
|
+
} finally {
|
|
102
|
+
await handle.close();
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
} catch (error: any) {
|
|
106
|
+
const reasons: Record<string, string> = {
|
|
107
|
+
EACCES: "permission denied",
|
|
108
|
+
EPERM: "permission denied",
|
|
109
|
+
ENOSPC: "the disk is full",
|
|
110
|
+
ENOENT: "the folder does not exist",
|
|
111
|
+
};
|
|
112
|
+
const why = reasons[error?.code ?? ""] ?? "it could not be written";
|
|
113
|
+
return why;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function executeGenerateImage(
|
|
118
|
+
ctx: Plugin.Context,
|
|
119
|
+
deps: Deps,
|
|
120
|
+
raw: unknown,
|
|
121
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
122
|
+
) {
|
|
123
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
124
|
+
const input = raw as any;
|
|
125
|
+
const prompt =
|
|
126
|
+
typeof input?.prompt === "string" ? input.prompt.trim() : "";
|
|
127
|
+
if (!prompt) return fail("generate_image needs a prompt.");
|
|
128
|
+
const aspectRatio =
|
|
129
|
+
typeof input?.aspect_ratio === "string" ? input.aspect_ratio : undefined;
|
|
130
|
+
const name = typeof input?.name === "string" ? input.name : undefined;
|
|
131
|
+
|
|
132
|
+
const result = await freePiRequest(deps, {
|
|
133
|
+
path: "/tools/image",
|
|
134
|
+
method: "POST",
|
|
135
|
+
body: { prompt, ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}) },
|
|
136
|
+
timeoutMs: TIMEOUT_MS,
|
|
137
|
+
signal: context.signal,
|
|
138
|
+
label: "The image request",
|
|
139
|
+
});
|
|
140
|
+
if (!result.ok) return fail(mappedText(ERRORS, result));
|
|
141
|
+
|
|
142
|
+
const data = result.data ?? {};
|
|
143
|
+
const ext = EXT[data.media_type];
|
|
144
|
+
if (!ext) {
|
|
145
|
+
return fail(
|
|
146
|
+
`The server returned an unsupported image type (${data.media_type}). Nothing was saved.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const bytes = Buffer.from(data.image_b64 ?? "", "base64");
|
|
150
|
+
if (bytes.length === 0) {
|
|
151
|
+
return fail("The server returned an empty image. Nothing was saved.");
|
|
152
|
+
}
|
|
153
|
+
if (bytes.length > MAX_BYTES) {
|
|
154
|
+
return fail(
|
|
155
|
+
"The generated image was too large to save (over 8 MB). Nothing was saved.",
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const relative = `images/${slug(name ?? prompt)}-${randomBytes(3).toString("hex")}.${ext}`;
|
|
160
|
+
const failure = await saveImage(ctx.location.directory, relative, bytes);
|
|
161
|
+
if (failure) return fail(`Couldn't save the image to images: ${failure}.`);
|
|
162
|
+
|
|
163
|
+
deps.log.info("generate_image saved an image", {
|
|
164
|
+
path: relative,
|
|
165
|
+
bytes: bytes.length,
|
|
166
|
+
mediaType: data.media_type,
|
|
167
|
+
model: data.model,
|
|
168
|
+
});
|
|
169
|
+
return done(
|
|
170
|
+
`Saved image to ${relative} (${ext}, ${bytes.length} bytes). You cannot see the image; reference this path in your answer or code, and tell the user you could not check how it looks.`,
|
|
171
|
+
{
|
|
172
|
+
ok: true,
|
|
173
|
+
path: relative,
|
|
174
|
+
...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
|
|
175
|
+
...(typeof data.model === "string" ? { model: data.model } : {}),
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function registerGenerateImageTool(
|
|
181
|
+
ctx: Plugin.Context,
|
|
182
|
+
deps: Deps,
|
|
183
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
184
|
+
return ctx.tool.transform((editor) => {
|
|
185
|
+
editor.add({
|
|
186
|
+
name: "generate_image",
|
|
187
|
+
description:
|
|
188
|
+
"Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; you cannot see the image. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
|
|
189
|
+
input: IMAGE_INPUT,
|
|
190
|
+
options: { codemode: false },
|
|
191
|
+
execute: (input: unknown, context: any) =>
|
|
192
|
+
executeGenerateImage(ctx, deps, input, context),
|
|
193
|
+
} as any);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `free_pi_usage`, the free-pi allowance tool.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors the provider CLI: `GET /me/stats` and a compact, human-readable
|
|
5
|
+
* summary. Read-only and gated to free-pi sessions.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Plugin } from "@opencode/plugin";
|
|
9
|
+
import type { Deps } from "../deps.js";
|
|
10
|
+
import {
|
|
11
|
+
done,
|
|
12
|
+
fail,
|
|
13
|
+
freePiRequest,
|
|
14
|
+
friendlyStatus,
|
|
15
|
+
GATED_TEXT,
|
|
16
|
+
isGatedSession,
|
|
17
|
+
} from "./api.js";
|
|
18
|
+
|
|
19
|
+
const NO_INPUT = {
|
|
20
|
+
type: "object",
|
|
21
|
+
additionalProperties: false,
|
|
22
|
+
properties: {},
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
const NO_ARGUMENTS = "free_pi_usage takes no arguments.";
|
|
26
|
+
|
|
27
|
+
const SLOW_LANE_NOTICE =
|
|
28
|
+
"You're out of free credits for today. You can keep working on our spare capacity while it lasts, or buy credits to keep going at full speed.";
|
|
29
|
+
|
|
30
|
+
const number = (value: number) => value.toLocaleString("en-US");
|
|
31
|
+
|
|
32
|
+
function formatRefillEt(date: Date): string {
|
|
33
|
+
const formatted = new Intl.DateTimeFormat("en-US", {
|
|
34
|
+
timeZone: "America/New_York",
|
|
35
|
+
hour: "numeric",
|
|
36
|
+
minute: "2-digit",
|
|
37
|
+
hour12: true,
|
|
38
|
+
}).format(date);
|
|
39
|
+
return `${formatted} ET`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function percentUsed(spentUsd: number, capUsd: number): number {
|
|
43
|
+
if (!(capUsd > 0)) return 100;
|
|
44
|
+
return Math.min(100, Math.max(0, Math.round((spentUsd / capUsd) * 100)));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function creditsLeftLine(
|
|
48
|
+
remaining: number,
|
|
49
|
+
allowance: number,
|
|
50
|
+
refillAt: Date,
|
|
51
|
+
): string {
|
|
52
|
+
return `${number(remaining)} / ${number(allowance)} credits left today - refills ${formatRefillEt(refillAt)}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function formatUsage(stats: any): string {
|
|
56
|
+
const t = stats ?? {};
|
|
57
|
+
const remaining = t.remaining_credits_today;
|
|
58
|
+
const allowance = t.allowance_credits;
|
|
59
|
+
const refillAt = t.refill_at;
|
|
60
|
+
const tiered =
|
|
61
|
+
t.credit_tiers === true &&
|
|
62
|
+
typeof t.premium_credits === "number" &&
|
|
63
|
+
typeof remaining === "number" &&
|
|
64
|
+
typeof allowance === "number" &&
|
|
65
|
+
typeof refillAt === "string";
|
|
66
|
+
|
|
67
|
+
const todayLine =
|
|
68
|
+
typeof remaining === "number" &&
|
|
69
|
+
typeof allowance === "number" &&
|
|
70
|
+
typeof refillAt === "string"
|
|
71
|
+
? creditsLeftLine(remaining, allowance, new Date(refillAt))
|
|
72
|
+
: `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
|
|
73
|
+
|
|
74
|
+
const tieredLines = tiered
|
|
75
|
+
? [
|
|
76
|
+
creditsLeftLine(remaining, allowance, new Date(refillAt)),
|
|
77
|
+
`premium credits: ${number(t.premium_credits)} (bought ${number(t.premium_bought_credits ?? 0)} - gifted ${number(t.premium_gifted_credits ?? 0)})`,
|
|
78
|
+
...(typeof t.regular_wallet_credits === "number" &&
|
|
79
|
+
t.regular_wallet_credits > 0
|
|
80
|
+
? [`referral credits: ${number(t.regular_wallet_credits)}`]
|
|
81
|
+
: []),
|
|
82
|
+
`Premium credits do not reset.${t.premium_get_line ? ` ${t.premium_get_line}` : ""}`,
|
|
83
|
+
]
|
|
84
|
+
: [];
|
|
85
|
+
|
|
86
|
+
return [
|
|
87
|
+
`tier: ${t.tier ?? "unknown"}`,
|
|
88
|
+
...(tiered ? [tieredLines[0]!] : [todayLine]),
|
|
89
|
+
...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
|
|
90
|
+
...(tiered
|
|
91
|
+
? tieredLines.slice(1)
|
|
92
|
+
: [
|
|
93
|
+
...(typeof t.credit_credits === "number"
|
|
94
|
+
? [`credit: ${number(t.credit_credits)} credits remaining`]
|
|
95
|
+
: []),
|
|
96
|
+
...(typeof t.bonus_wallet_credits === "number" &&
|
|
97
|
+
t.bonus_wallet_credits > 0
|
|
98
|
+
? [`bonus: ${number(t.bonus_wallet_credits)} credits remaining`]
|
|
99
|
+
: []),
|
|
100
|
+
]),
|
|
101
|
+
...(typeof t.streak?.message === "string" && t.streak.message
|
|
102
|
+
? [t.streak.message]
|
|
103
|
+
: []),
|
|
104
|
+
`today tokens: ${t.prompt_tokens_today ?? 0} prompt / ${t.completion_tokens_today ?? 0} completion`,
|
|
105
|
+
`lifetime: ${t.lifetime?.prompt_tokens ?? 0} prompt / ${t.lifetime?.completion_tokens ?? 0} completion tokens`,
|
|
106
|
+
...(tiered ? [] : ["buy more credits: free_pi_buy_credits"]),
|
|
107
|
+
...(t.guest
|
|
108
|
+
? [
|
|
109
|
+
"guest trial: sign in with GitHub for up to 15,000 free credits a day",
|
|
110
|
+
]
|
|
111
|
+
: []),
|
|
112
|
+
"see details at freepi.ai/dashboard",
|
|
113
|
+
].join("\n");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function executeUsage(
|
|
117
|
+
deps: Deps,
|
|
118
|
+
raw: unknown,
|
|
119
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
120
|
+
) {
|
|
121
|
+
if (raw && typeof raw === "object" && Object.keys(raw as object).length > 0) {
|
|
122
|
+
return fail(NO_ARGUMENTS);
|
|
123
|
+
}
|
|
124
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
125
|
+
|
|
126
|
+
const result = await freePiRequest(deps, {
|
|
127
|
+
path: "/me/stats",
|
|
128
|
+
timeoutMs: 5_000,
|
|
129
|
+
signal: context.signal,
|
|
130
|
+
audience: "user",
|
|
131
|
+
});
|
|
132
|
+
if (!result.ok) return fail(result.text);
|
|
133
|
+
|
|
134
|
+
const stats = result.data;
|
|
135
|
+
deps.log.info("free_pi_usage answered", {
|
|
136
|
+
tier: stats?.tier,
|
|
137
|
+
lane: stats?.lane,
|
|
138
|
+
});
|
|
139
|
+
return done(formatUsage(stats), {
|
|
140
|
+
ok: true,
|
|
141
|
+
tier: stats?.tier,
|
|
142
|
+
lane: stats?.lane,
|
|
143
|
+
remaining_credits_today: stats?.remaining_credits_today,
|
|
144
|
+
allowance_credits: stats?.allowance_credits,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function registerUsageTool(
|
|
149
|
+
ctx: Plugin.Context,
|
|
150
|
+
deps: Deps,
|
|
151
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
152
|
+
return ctx.tool.transform((editor) => {
|
|
153
|
+
editor.add({
|
|
154
|
+
name: "free_pi_usage",
|
|
155
|
+
description:
|
|
156
|
+
"Report how much of the caller's free daily allowance is used, remaining credits, token counts and account tier. Read-only, takes no arguments, makes no changes.",
|
|
157
|
+
input: NO_INPUT,
|
|
158
|
+
options: { codemode: false },
|
|
159
|
+
execute: (input: unknown, context: any) =>
|
|
160
|
+
executeUsage(deps, input, context),
|
|
161
|
+
} as any);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes vision questions across sessions and OpenCode processes.
|
|
3
|
+
*
|
|
4
|
+
* free-pi answers one `/tools/vision` request at a time: a second concurrent
|
|
5
|
+
* question gets `rate_limited`. OpenCode can run several sessions, and users can
|
|
6
|
+
* run several OpenCode processes, so calls are queued in-process and coordinated
|
|
7
|
+
* through a lock directory in the free-pi cache.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import type { Logger } from "../logging.js";
|
|
14
|
+
import { cacheDir } from "../utils/cache.js";
|
|
15
|
+
|
|
16
|
+
type Owner = { pid: number; startedAt: number; id: string };
|
|
17
|
+
|
|
18
|
+
const OWNER_FILE = "owner.json";
|
|
19
|
+
const POLL_MS = 350;
|
|
20
|
+
/** A live owner may legitimately hold the lock for a 90 s request. */
|
|
21
|
+
const STALE_MS = 10 * 60_000;
|
|
22
|
+
const MAX_WAIT_MS = 120_000;
|
|
23
|
+
|
|
24
|
+
let chain: Promise<void> = Promise.resolve();
|
|
25
|
+
|
|
26
|
+
function lockDir(): string {
|
|
27
|
+
return join(cacheDir(), "vision.lock");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function pidAlive(pid: number): boolean {
|
|
31
|
+
try {
|
|
32
|
+
process.kill(pid, 0);
|
|
33
|
+
return true;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
// EPERM means the process exists but belongs to another user.
|
|
36
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function createLock(dir: string, owner: Owner): Promise<boolean> {
|
|
41
|
+
try {
|
|
42
|
+
await mkdir(dir);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") return false;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
await writeFile(join(dir, OWNER_FILE), JSON.stringify(owner), "utf8");
|
|
49
|
+
} catch {
|
|
50
|
+
// The owner file is a convenience; the directory itself is the lock.
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function abandoned(dir: string): Promise<boolean> {
|
|
56
|
+
try {
|
|
57
|
+
const raw = await readFile(join(dir, OWNER_FILE), "utf8");
|
|
58
|
+
const owner = JSON.parse(raw) as Partial<Owner>;
|
|
59
|
+
if (typeof owner.pid === "number") return !pidAlive(owner.pid);
|
|
60
|
+
} catch {
|
|
61
|
+
// Written just after the directory is created, so it can be briefly absent.
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const info = await stat(dir);
|
|
65
|
+
return Date.now() - info.mtimeMs > STALE_MS;
|
|
66
|
+
} catch {
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function sleep(ms: number): Promise<void> {
|
|
72
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type Slot = {
|
|
76
|
+
readonly release: () => Promise<void>;
|
|
77
|
+
readonly waitedMs: number;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
async function acquire(log: Logger): Promise<Slot | undefined> {
|
|
81
|
+
const dir = lockDir();
|
|
82
|
+
const owner: Owner = {
|
|
83
|
+
pid: process.pid,
|
|
84
|
+
startedAt: Date.now(),
|
|
85
|
+
id: randomUUID(),
|
|
86
|
+
};
|
|
87
|
+
const startedAt = Date.now();
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
await mkdir(cacheDir(), { recursive: true });
|
|
91
|
+
} catch {
|
|
92
|
+
// Without a cache directory the file lock is unavailable; the in-process
|
|
93
|
+
// queue still serializes calls, so keep going.
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
while (Date.now() - startedAt < MAX_WAIT_MS) {
|
|
97
|
+
try {
|
|
98
|
+
if (await createLock(dir, owner)) {
|
|
99
|
+
return {
|
|
100
|
+
waitedMs: Date.now() - startedAt,
|
|
101
|
+
release: async () => {
|
|
102
|
+
try {
|
|
103
|
+
const raw = await readFile(join(dir, OWNER_FILE), "utf8");
|
|
104
|
+
if ((JSON.parse(raw) as Owner).id !== owner.id) return;
|
|
105
|
+
} catch {
|
|
106
|
+
// Fall through and remove the lock we created.
|
|
107
|
+
}
|
|
108
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
} catch (error) {
|
|
113
|
+
log.warn("look_at_image could not use the shared vision lock", {
|
|
114
|
+
error: String(error),
|
|
115
|
+
});
|
|
116
|
+
return { waitedMs: 0, release: async () => {} };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (await abandoned(dir)) {
|
|
120
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
await sleep(POLL_MS + Math.floor(Math.random() * 100));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Runs `run` while holding the vision slot. Returns `ok: false` when another
|
|
131
|
+
* process kept the slot occupied for longer than the queue budget.
|
|
132
|
+
*/
|
|
133
|
+
export async function withVisionSlot<T>(
|
|
134
|
+
log: Logger,
|
|
135
|
+
run: () => Promise<T>,
|
|
136
|
+
): Promise<{ ok: true; value: T } | { ok: false }> {
|
|
137
|
+
// Queue inside this process first: several sessions share the same module.
|
|
138
|
+
const previous = chain;
|
|
139
|
+
let releaseChain: () => void = () => {};
|
|
140
|
+
chain = new Promise<void>((resolve) => {
|
|
141
|
+
releaseChain = resolve;
|
|
142
|
+
});
|
|
143
|
+
await previous.catch(() => {});
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
const slot = await acquire(log);
|
|
147
|
+
if (!slot) return { ok: false };
|
|
148
|
+
if (slot.waitedMs > 500) {
|
|
149
|
+
log.info("look_at_image waited for the previous image question", {
|
|
150
|
+
waitedMs: slot.waitedMs,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
return { ok: true, value: await run() };
|
|
155
|
+
} finally {
|
|
156
|
+
await slot.release();
|
|
157
|
+
}
|
|
158
|
+
} finally {
|
|
159
|
+
releaseChain();
|
|
160
|
+
}
|
|
161
|
+
}
|