@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.
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Fusion: DeepSeek Pro plans, Flash builds.
3
+ *
4
+ * The provider CLI registers a virtual "fusion" model. OpenCode gets the same
5
+ * shape: a `fusion` model that routes its turns to the executor model, plus a
6
+ * `fusion_plan` tool that asks the planner model for a plan through the
7
+ * stateless generate API before any edit. The executor then carries the plan
8
+ * out, exactly like the CLI.
9
+ */
10
+ import { PROVIDER_ID } from "../constants.js";
11
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, } from "./api.js";
12
+ export const FUSION_ID = "fusion";
13
+ export const FUSION_PLANNER_ID = "deepseek-v4-pro";
14
+ export const FUSION_EXECUTOR_ID = "deepseek-v4-flash";
15
+ export const FUSION_FALLBACK_PLANNER_ID = "deepseek-v4-flash";
16
+ export const FUSION_GUIDELINE = `Fusion: if the task needs any file changes, first gather the context with read-only tools (read, grep, glob) and make no edits. Then call fusion_plan with a summary of what you found and what the task needs, BEFORE any edit or write; the planning model writes the plan and you carry it out. Once the plan exists, record it with the todo tool, then carry out the unfinished items yourself (edit, write tests, run them) and finish the user's task. Only a task that needs no file changes (a plain question) is answered directly without fusion_plan.`;
17
+ const PLAN_INPUT = {
18
+ type: "object",
19
+ additionalProperties: false,
20
+ required: ["summary"],
21
+ properties: {
22
+ summary: {
23
+ type: "string",
24
+ minLength: 1,
25
+ maxLength: 6_000,
26
+ description: "What you found during read-only exploration and what the task needs",
27
+ },
28
+ },
29
+ };
30
+ /**
31
+ * Picks the planner and executor from the live catalog, like the CLI: prefer
32
+ * the server-provided pair, then Pro when the account has premium credits, then
33
+ * Flash for both roles.
34
+ */
35
+ export function resolveFusionIds(modelIDs, defaultModelID, options = {}) {
36
+ const has = (id) => typeof id === "string" && modelIDs.includes(id);
37
+ const executor = has(FUSION_EXECUTOR_ID)
38
+ ? FUSION_EXECUTOR_ID
39
+ : has(defaultModelID)
40
+ ? defaultModelID
41
+ : undefined;
42
+ if (!executor)
43
+ return undefined;
44
+ const server = options.server;
45
+ if (server && has(server.planner) && has(server.executor)) {
46
+ return { planner: server.planner, executor: server.executor };
47
+ }
48
+ const planner = options.hasPremium !== false && has(FUSION_PLANNER_ID)
49
+ ? FUSION_PLANNER_ID
50
+ : has(FUSION_FALLBACK_PLANNER_ID)
51
+ ? FUSION_FALLBACK_PLANNER_ID
52
+ : executor;
53
+ return { planner, executor };
54
+ }
55
+ /**
56
+ * The CLI asks `/me` before offering the Pro planner: without premium credits
57
+ * the Pro model refuses the request, so Fusion plans with Flash instead. A
58
+ * failed check keeps Pro, matching the CLI.
59
+ */
60
+ export async function premiumPlannerAvailable(deps) {
61
+ const result = await freePiRequest(deps, {
62
+ path: "/me",
63
+ timeoutMs: 5_000,
64
+ });
65
+ if (!result.ok)
66
+ return true;
67
+ const premium = result.data?.premium_credits;
68
+ return typeof premium === "number" ? premium > 0 : true;
69
+ }
70
+ export function fusionName(ids) {
71
+ if (ids.planner === FUSION_PLANNER_ID) {
72
+ return "🧬 Fusion · DeepSeek Pro plans, Flash builds";
73
+ }
74
+ if (ids.planner === FUSION_FALLBACK_PLANNER_ID) {
75
+ return "🧬 Fusion · DeepSeek Flash plans and builds";
76
+ }
77
+ return "🧬 Fusion";
78
+ }
79
+ /** Adds the virtual model next to the catalog models. */
80
+ export function addFusionModel(models, ids) {
81
+ const base = models[ids.executor];
82
+ if (!base)
83
+ return undefined;
84
+ models[FUSION_ID] = {
85
+ ...base,
86
+ id: FUSION_ID,
87
+ name: fusionName(ids),
88
+ release_date: base.release_date,
89
+ };
90
+ return FUSION_ID;
91
+ }
92
+ function plannerPrompt(summary) {
93
+ return `You are the planning model in a two-model setup. Another model gathered the context below and will carry out the plan; it can edit files and run commands, but it cannot see this conversation.
94
+
95
+ Task context from the executor:
96
+ ${summary}
97
+
98
+ Write a concrete step-by-step plan: the files to change, the exact changes, and the tests to add and run. Be specific enough that the executor does not need to re-explore. Do not edit files or run commands. Reply with the plan only.`;
99
+ }
100
+ async function plan(ctx, deps, plannerID, summary) {
101
+ const generate = ctx.experimental?.generate?.text;
102
+ if (typeof generate !== "function") {
103
+ deps.log.warn("fusion_plan: this OpenCode build has no stateless generate");
104
+ return undefined;
105
+ }
106
+ try {
107
+ const result = await generate({
108
+ prompt: plannerPrompt(summary),
109
+ model: { providerID: PROVIDER_ID, id: plannerID },
110
+ });
111
+ const text = result?.text ?? result?.data?.text;
112
+ return typeof text === "string" && text.trim() ? text.trim() : undefined;
113
+ }
114
+ catch (error) {
115
+ deps.log.warn("fusion_plan: the planner request failed", {
116
+ planner: plannerID,
117
+ message: String(error?.message ?? error),
118
+ });
119
+ return undefined;
120
+ }
121
+ }
122
+ async function executeFusionPlan(ctx, deps, ids, raw, context) {
123
+ if (!isGatedSession(deps, context.sessionID))
124
+ return fail(GATED_TEXT);
125
+ const summary = typeof raw?.summary === "string"
126
+ ? raw.summary.trim()
127
+ : "";
128
+ if (!summary)
129
+ return fail("fusion_plan needs a summary of the task context.");
130
+ const startedAt = Date.now();
131
+ let usedPlanner = ids.planner;
132
+ let text = await plan(ctx, deps, ids.planner, summary);
133
+ if (!text && ids.planner !== FUSION_FALLBACK_PLANNER_ID) {
134
+ // Pro needs premium credits; without them it refuses the request, so let
135
+ // Flash plan instead of losing the turn.
136
+ usedPlanner = FUSION_FALLBACK_PLANNER_ID;
137
+ text = await plan(ctx, deps, usedPlanner, summary);
138
+ }
139
+ if (!text) {
140
+ deps.log.warn("fusion_plan could not reach the planner; planning locally", {
141
+ planner: ids.planner,
142
+ });
143
+ return done("The planner is unavailable, so write the step-by-step plan yourself with the todo tool, one item per step. Do not edit files until the plan is recorded, then carry it out.", { ok: false, planner: ids.planner });
144
+ }
145
+ deps.log.info("fusion_plan answered", {
146
+ planner: usedPlanner,
147
+ ms: Date.now() - startedAt,
148
+ chars: text.length,
149
+ });
150
+ return done(`Plan from the Fusion planner (${usedPlanner}). Record it with the todo tool if it is not already there, then carry it out:\n\n${text}`, { ok: true, planner: usedPlanner, elapsed_ms: Date.now() - startedAt });
151
+ }
152
+ export async function registerFusionTool(ctx, deps, ids) {
153
+ return ctx.tool.transform((editor) => {
154
+ editor.add({
155
+ name: "fusion_plan",
156
+ description: "Fusion only: hand off to the planning model once you have gathered enough context. Takes a summary of what you found and what the task needs, and returns a step-by-step plan to carry out.",
157
+ input: PLAN_INPUT,
158
+ options: { codemode: false },
159
+ execute: (input, context) => executeFusionPlan(ctx, deps, ids, input, context),
160
+ });
161
+ });
162
+ }
@@ -0,0 +1,13 @@
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
+ import type { Plugin } from "@opencode/plugin";
9
+ import type { Deps } from "../deps.js";
10
+ export declare function slug(value: string): string;
11
+ export declare function registerGenerateImageTool(ctx: Plugin.Context, deps: Deps): Promise<{
12
+ dispose: () => Promise<void>;
13
+ }>;
@@ -0,0 +1,143 @@
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
+ import { randomBytes } from "node:crypto";
9
+ import { mkdir, open } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, mappedText, } from "./api.js";
12
+ const MAX_BYTES = 8 * 1024 * 1024;
13
+ const TIMEOUT_MS = 120_000;
14
+ const EXT = {
15
+ "image/png": "png",
16
+ "image/jpeg": "jpg",
17
+ "image/webp": "webp",
18
+ };
19
+ const ERRORS = {
20
+ guest_login_required: "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.",
21
+ guest_unavailable: "The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
22
+ daily_cap: "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.",
23
+ rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
24
+ rate_limited: "Too many image requests right now. Do not call generate_image again in this turn unless the user asks.",
25
+ not_configured: "Image generation is not available on this server. Do not call generate_image again in this session.",
26
+ upstream_error: "The image provider failed. You may retry once.",
27
+ account_review: "This account is under review, so image generation is disabled. Do not retry; tell the user and continue without it.",
28
+ content_rejected: "The image provider rejected this prompt. Do not retry the same prompt; tell the user and offer to reword it.",
29
+ invalid_request: "The server rejected this request. Do not retry it unchanged.",
30
+ };
31
+ const IMAGE_INPUT = {
32
+ type: "object",
33
+ additionalProperties: false,
34
+ required: ["prompt"],
35
+ properties: {
36
+ prompt: {
37
+ type: "string",
38
+ minLength: 1,
39
+ maxLength: 1_000,
40
+ description: "What to draw: subject, style, any exact text to render, and composition",
41
+ },
42
+ aspect_ratio: {
43
+ type: "string",
44
+ enum: ["1:1", "16:9", "9:16", "4:3", "3:2"],
45
+ description: "Default 1:1",
46
+ },
47
+ name: {
48
+ type: "string",
49
+ maxLength: 60,
50
+ description: "Short file name hint, e.g. hero-banner; used only for the saved file's name",
51
+ },
52
+ },
53
+ };
54
+ export function slug(value) {
55
+ return (value
56
+ .toLowerCase()
57
+ .replace(/[^a-z0-9]+/g, "-")
58
+ .replace(/^-+/, "")
59
+ .slice(0, 40)
60
+ .replace(/-+$/, "") || "image");
61
+ }
62
+ async function saveImage(directory, relative, bytes) {
63
+ try {
64
+ await mkdir(join(directory, "images"), { recursive: true });
65
+ const handle = await open(join(directory, relative), "wx");
66
+ try {
67
+ await handle.writeFile(bytes);
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ return undefined;
73
+ }
74
+ catch (error) {
75
+ const reasons = {
76
+ EACCES: "permission denied",
77
+ EPERM: "permission denied",
78
+ ENOSPC: "the disk is full",
79
+ ENOENT: "the folder does not exist",
80
+ };
81
+ const why = reasons[error?.code ?? ""] ?? "it could not be written";
82
+ return why;
83
+ }
84
+ }
85
+ async function executeGenerateImage(ctx, deps, raw, context) {
86
+ if (!isGatedSession(deps, context.sessionID))
87
+ return fail(GATED_TEXT);
88
+ const input = raw;
89
+ const prompt = typeof input?.prompt === "string" ? input.prompt.trim() : "";
90
+ if (!prompt)
91
+ return fail("generate_image needs a prompt.");
92
+ const aspectRatio = typeof input?.aspect_ratio === "string" ? input.aspect_ratio : undefined;
93
+ const name = typeof input?.name === "string" ? input.name : undefined;
94
+ const result = await freePiRequest(deps, {
95
+ path: "/tools/image",
96
+ method: "POST",
97
+ body: { prompt, ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}) },
98
+ timeoutMs: TIMEOUT_MS,
99
+ signal: context.signal,
100
+ label: "The image request",
101
+ });
102
+ if (!result.ok)
103
+ return fail(mappedText(ERRORS, result));
104
+ const data = result.data ?? {};
105
+ const ext = EXT[data.media_type];
106
+ if (!ext) {
107
+ return fail(`The server returned an unsupported image type (${data.media_type}). Nothing was saved.`);
108
+ }
109
+ const bytes = Buffer.from(data.image_b64 ?? "", "base64");
110
+ if (bytes.length === 0) {
111
+ return fail("The server returned an empty image. Nothing was saved.");
112
+ }
113
+ if (bytes.length > MAX_BYTES) {
114
+ return fail("The generated image was too large to save (over 8 MB). Nothing was saved.");
115
+ }
116
+ const relative = `images/${slug(name ?? prompt)}-${randomBytes(3).toString("hex")}.${ext}`;
117
+ const failure = await saveImage(ctx.location.directory, relative, bytes);
118
+ if (failure)
119
+ return fail(`Couldn't save the image to images: ${failure}.`);
120
+ deps.log.info("generate_image saved an image", {
121
+ path: relative,
122
+ bytes: bytes.length,
123
+ mediaType: data.media_type,
124
+ model: data.model,
125
+ });
126
+ return done(`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.`, {
127
+ ok: true,
128
+ path: relative,
129
+ ...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
130
+ ...(typeof data.model === "string" ? { model: data.model } : {}),
131
+ });
132
+ }
133
+ export async function registerGenerateImageTool(ctx, deps) {
134
+ return ctx.tool.transform((editor) => {
135
+ editor.add({
136
+ name: "generate_image",
137
+ description: "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.",
138
+ input: IMAGE_INPUT,
139
+ options: { codemode: false },
140
+ execute: (input, context) => executeGenerateImage(ctx, deps, input, context),
141
+ });
142
+ });
143
+ }
@@ -0,0 +1,12 @@
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
+ import type { Plugin } from "@opencode/plugin";
8
+ import type { Deps } from "../deps.js";
9
+ export declare function formatUsage(stats: any): string;
10
+ export declare function registerUsageTool(ctx: Plugin.Context, deps: Deps): Promise<{
11
+ dispose: () => Promise<void>;
12
+ }>;
@@ -0,0 +1,125 @@
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
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, } from "./api.js";
8
+ const NO_INPUT = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ properties: {},
12
+ };
13
+ const NO_ARGUMENTS = "free_pi_usage takes no arguments.";
14
+ const SLOW_LANE_NOTICE = "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.";
15
+ const number = (value) => value.toLocaleString("en-US");
16
+ function formatRefillEt(date) {
17
+ const formatted = new Intl.DateTimeFormat("en-US", {
18
+ timeZone: "America/New_York",
19
+ hour: "numeric",
20
+ minute: "2-digit",
21
+ hour12: true,
22
+ }).format(date);
23
+ return `${formatted} ET`;
24
+ }
25
+ function percentUsed(spentUsd, capUsd) {
26
+ if (!(capUsd > 0))
27
+ return 100;
28
+ return Math.min(100, Math.max(0, Math.round((spentUsd / capUsd) * 100)));
29
+ }
30
+ function creditsLeftLine(remaining, allowance, refillAt) {
31
+ return `${number(remaining)} / ${number(allowance)} credits left today - refills ${formatRefillEt(refillAt)}`;
32
+ }
33
+ export function formatUsage(stats) {
34
+ const t = stats ?? {};
35
+ const remaining = t.remaining_credits_today;
36
+ const allowance = t.allowance_credits;
37
+ const refillAt = t.refill_at;
38
+ const tiered = t.credit_tiers === true &&
39
+ typeof t.premium_credits === "number" &&
40
+ typeof remaining === "number" &&
41
+ typeof allowance === "number" &&
42
+ typeof refillAt === "string";
43
+ const todayLine = typeof remaining === "number" &&
44
+ typeof allowance === "number" &&
45
+ typeof refillAt === "string"
46
+ ? creditsLeftLine(remaining, allowance, new Date(refillAt))
47
+ : `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
48
+ const tieredLines = tiered
49
+ ? [
50
+ creditsLeftLine(remaining, allowance, new Date(refillAt)),
51
+ `premium credits: ${number(t.premium_credits)} (bought ${number(t.premium_bought_credits ?? 0)} - gifted ${number(t.premium_gifted_credits ?? 0)})`,
52
+ ...(typeof t.regular_wallet_credits === "number" &&
53
+ t.regular_wallet_credits > 0
54
+ ? [`referral credits: ${number(t.regular_wallet_credits)}`]
55
+ : []),
56
+ `Premium credits do not reset.${t.premium_get_line ? ` ${t.premium_get_line}` : ""}`,
57
+ ]
58
+ : [];
59
+ return [
60
+ `tier: ${t.tier ?? "unknown"}`,
61
+ ...(tiered ? [tieredLines[0]] : [todayLine]),
62
+ ...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
63
+ ...(tiered
64
+ ? tieredLines.slice(1)
65
+ : [
66
+ ...(typeof t.credit_credits === "number"
67
+ ? [`credit: ${number(t.credit_credits)} credits remaining`]
68
+ : []),
69
+ ...(typeof t.bonus_wallet_credits === "number" &&
70
+ t.bonus_wallet_credits > 0
71
+ ? [`bonus: ${number(t.bonus_wallet_credits)} credits remaining`]
72
+ : []),
73
+ ]),
74
+ ...(typeof t.streak?.message === "string" && t.streak.message
75
+ ? [t.streak.message]
76
+ : []),
77
+ `today tokens: ${t.prompt_tokens_today ?? 0} prompt / ${t.completion_tokens_today ?? 0} completion`,
78
+ `lifetime: ${t.lifetime?.prompt_tokens ?? 0} prompt / ${t.lifetime?.completion_tokens ?? 0} completion tokens`,
79
+ ...(tiered ? [] : ["buy more credits: free_pi_buy_credits"]),
80
+ ...(t.guest
81
+ ? [
82
+ "guest trial: sign in with GitHub for up to 15,000 free credits a day",
83
+ ]
84
+ : []),
85
+ "see details at freepi.ai/dashboard",
86
+ ].join("\n");
87
+ }
88
+ async function executeUsage(deps, raw, context) {
89
+ if (raw && typeof raw === "object" && Object.keys(raw).length > 0) {
90
+ return fail(NO_ARGUMENTS);
91
+ }
92
+ if (!isGatedSession(deps, context.sessionID))
93
+ return fail(GATED_TEXT);
94
+ const result = await freePiRequest(deps, {
95
+ path: "/me/stats",
96
+ timeoutMs: 5_000,
97
+ signal: context.signal,
98
+ audience: "user",
99
+ });
100
+ if (!result.ok)
101
+ return fail(result.text);
102
+ const stats = result.data;
103
+ deps.log.info("free_pi_usage answered", {
104
+ tier: stats?.tier,
105
+ lane: stats?.lane,
106
+ });
107
+ return done(formatUsage(stats), {
108
+ ok: true,
109
+ tier: stats?.tier,
110
+ lane: stats?.lane,
111
+ remaining_credits_today: stats?.remaining_credits_today,
112
+ allowance_credits: stats?.allowance_credits,
113
+ });
114
+ }
115
+ export async function registerUsageTool(ctx, deps) {
116
+ return ctx.tool.transform((editor) => {
117
+ editor.add({
118
+ name: "free_pi_usage",
119
+ description: "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.",
120
+ input: NO_INPUT,
121
+ options: { codemode: false },
122
+ execute: (input, context) => executeUsage(deps, input, context),
123
+ });
124
+ });
125
+ }
@@ -0,0 +1,19 @@
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
+ import type { Logger } from "../logging.js";
10
+ /**
11
+ * Runs `run` while holding the vision slot. Returns `ok: false` when another
12
+ * process kept the slot occupied for longer than the queue budget.
13
+ */
14
+ export declare function withVisionSlot<T>(log: Logger, run: () => Promise<T>): Promise<{
15
+ ok: true;
16
+ value: T;
17
+ } | {
18
+ ok: false;
19
+ }>;
@@ -0,0 +1,149 @@
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
+ import { randomUUID } from "node:crypto";
10
+ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+ import { cacheDir } from "../utils/cache.js";
13
+ const OWNER_FILE = "owner.json";
14
+ const POLL_MS = 350;
15
+ /** A live owner may legitimately hold the lock for a 90 s request. */
16
+ const STALE_MS = 10 * 60_000;
17
+ const MAX_WAIT_MS = 120_000;
18
+ let chain = Promise.resolve();
19
+ function lockDir() {
20
+ return join(cacheDir(), "vision.lock");
21
+ }
22
+ function pidAlive(pid) {
23
+ try {
24
+ process.kill(pid, 0);
25
+ return true;
26
+ }
27
+ catch (error) {
28
+ // EPERM means the process exists but belongs to another user.
29
+ return error.code === "EPERM";
30
+ }
31
+ }
32
+ async function createLock(dir, owner) {
33
+ try {
34
+ await mkdir(dir);
35
+ }
36
+ catch (error) {
37
+ if (error.code === "EEXIST")
38
+ return false;
39
+ throw error;
40
+ }
41
+ try {
42
+ await writeFile(join(dir, OWNER_FILE), JSON.stringify(owner), "utf8");
43
+ }
44
+ catch {
45
+ // The owner file is a convenience; the directory itself is the lock.
46
+ }
47
+ return true;
48
+ }
49
+ async function abandoned(dir) {
50
+ try {
51
+ const raw = await readFile(join(dir, OWNER_FILE), "utf8");
52
+ const owner = JSON.parse(raw);
53
+ if (typeof owner.pid === "number")
54
+ return !pidAlive(owner.pid);
55
+ }
56
+ catch {
57
+ // Written just after the directory is created, so it can be briefly absent.
58
+ }
59
+ try {
60
+ const info = await stat(dir);
61
+ return Date.now() - info.mtimeMs > STALE_MS;
62
+ }
63
+ catch {
64
+ return true;
65
+ }
66
+ }
67
+ function sleep(ms) {
68
+ return new Promise((resolve) => setTimeout(resolve, ms));
69
+ }
70
+ async function acquire(log) {
71
+ const dir = lockDir();
72
+ const owner = {
73
+ pid: process.pid,
74
+ startedAt: Date.now(),
75
+ id: randomUUID(),
76
+ };
77
+ const startedAt = Date.now();
78
+ try {
79
+ await mkdir(cacheDir(), { recursive: true });
80
+ }
81
+ catch {
82
+ // Without a cache directory the file lock is unavailable; the in-process
83
+ // queue still serializes calls, so keep going.
84
+ }
85
+ while (Date.now() - startedAt < MAX_WAIT_MS) {
86
+ try {
87
+ if (await createLock(dir, owner)) {
88
+ return {
89
+ waitedMs: Date.now() - startedAt,
90
+ release: async () => {
91
+ try {
92
+ const raw = await readFile(join(dir, OWNER_FILE), "utf8");
93
+ if (JSON.parse(raw).id !== owner.id)
94
+ return;
95
+ }
96
+ catch {
97
+ // Fall through and remove the lock we created.
98
+ }
99
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
100
+ },
101
+ };
102
+ }
103
+ }
104
+ catch (error) {
105
+ log.warn("look_at_image could not use the shared vision lock", {
106
+ error: String(error),
107
+ });
108
+ return { waitedMs: 0, release: async () => { } };
109
+ }
110
+ if (await abandoned(dir)) {
111
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
112
+ continue;
113
+ }
114
+ await sleep(POLL_MS + Math.floor(Math.random() * 100));
115
+ }
116
+ return undefined;
117
+ }
118
+ /**
119
+ * Runs `run` while holding the vision slot. Returns `ok: false` when another
120
+ * process kept the slot occupied for longer than the queue budget.
121
+ */
122
+ export async function withVisionSlot(log, run) {
123
+ // Queue inside this process first: several sessions share the same module.
124
+ const previous = chain;
125
+ let releaseChain = () => { };
126
+ chain = new Promise((resolve) => {
127
+ releaseChain = resolve;
128
+ });
129
+ await previous.catch(() => { });
130
+ try {
131
+ const slot = await acquire(log);
132
+ if (!slot)
133
+ return { ok: false };
134
+ if (slot.waitedMs > 500) {
135
+ log.info("look_at_image waited for the previous image question", {
136
+ waitedMs: slot.waitedMs,
137
+ });
138
+ }
139
+ try {
140
+ return { ok: true, value: await run() };
141
+ }
142
+ finally {
143
+ await slot.release();
144
+ }
145
+ }
146
+ finally {
147
+ releaseChain();
148
+ }
149
+ }