cuelo 0.10.263 → 0.10.265
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/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +56 -56
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/updates/apply/route.js +2 -2
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +2 -2
- package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +56 -56
- package/.next/server/chunks/5228.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{layout-ea2f66bbb3cf225b.js → layout-e1094925806bec9d.js} +1 -1
- package/.next/static/chunks/app/{page-5a80c9c459d8dc63.js → page-d3b9d5144b57dba9.js} +2 -2
- package/.next/trace +112 -112
- package/.next/trace-build +1 -1
- package/README.md +1 -0
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/index.ts +173 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/plugin.json +9 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/policy.ts +137 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/screen_find.py +142 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/setup.ts +127 -0
- package/Tools/OMP_Global_Config/agent/extensions/command-guard/task-guard.ts +28 -6
- package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +4 -2
- package/Tools/OMP_Global_Config/agent/rules/rule-enforcement.md +1 -1
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +1 -0
- package/Tools/OMP_Global_Config/agent/rules/task-guard.md +1 -0
- package/package.json +1 -1
- /package/.next/static/{4RZAh1nM0GnqwqwXF3Aey → Sn7BIbhcQMSVAqShu5LZ8}/_buildManifest.js +0 -0
- /package/.next/static/{4RZAh1nM0GnqwqwXF3Aey → Sn7BIbhcQMSVAqShu5LZ8}/_ssgManifest.js +0 -0
package/.next/trace-build
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
[{"name":"run-webpack","duration":
|
|
1
|
+
[{"name":"run-webpack","duration":84303314,"timestamp":395601,"id":14,"parentId":1,"tags":{},"startTime":1794707335321,"traceId":"e64b5aa4dc1794fd"},{"name":"run-typescript","duration":17987443,"timestamp":85169274,"id":11511,"parentId":1,"tags":{},"startTime":1794707420095,"traceId":"e64b5aa4dc1794fd"},{"name":"static-check","duration":2611143,"timestamp":103251184,"id":11514,"parentId":1,"tags":{},"startTime":1794707438177,"traceId":"e64b5aa4dc1794fd"},{"name":"static-generation","duration":5938229,"timestamp":105953952,"id":11732,"parentId":1,"tags":{},"startTime":1794707440879,"traceId":"e64b5aa4dc1794fd"},{"name":"collect-build-traces","duration":17011184,"timestamp":105935241,"id":11729,"parentId":1,"tags":{},"startTime":1794707440861,"traceId":"e64b5aa4dc1794fd"},{"name":"telemetry-flush","duration":44,"timestamp":122950307,"id":11741,"parentId":1,"tags":{},"startTime":1794707457876,"traceId":"e64b5aa4dc1794fd"},{"name":"next-build","duration":122619105,"timestamp":331262,"id":1,"tags":{"buildMode":"default","version":"16.2.12","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1794707335257,"traceId":"e64b5aa4dc1794fd"}]
|
package/README.md
CHANGED
|
@@ -140,6 +140,7 @@ Requires Node.js 22.19+ and Bun 1.4.4+ on Linux. Native Windows server installat
|
|
|
140
140
|
- 읽기 탐색 안내가 성공한 읽기와 실제 편집 대상을 기준으로 동작하도록 개선했습니다. (0.10.199)
|
|
141
141
|
- 보강 기록이 있으면 플러그인 카드에 마지막 보강 날짜와 요약이 표시되며, 기록이 없는 플러그인도 기존대로 동작합니다.
|
|
142
142
|
- "bash set -e 잔류 정리" 플러그인은 앞 bash 호출이 `set -e`를 남겼을 수 있으면 다음 호출 맨 앞에서 이를 꺼, 실패해도 되는 명령 뒤의 복구 단계가 그대로 실행되게 합니다. 호출을 막지 않으며 다른 플러그인처럼 사용자 권한으로 실행됩니다.
|
|
143
|
+
- "화면 조작 빠른 경로" 플러그인은 화면 글자 위치를 1~2초 만에 찾아 클릭하고 느린 좌표 질문을 막아 원격과 데스크톱 조작을 빠르게 합니다.
|
|
143
144
|
- 사이드챗 뒤에 위치한 오른쪽 덱의 "플러그인" 화면에서 온·오프 스위치, 문제 문구, 도구 목록, 패널 열기, 새 플러그인 만들기 동작을 지원합니다. 새 플러그인 만들기 버튼을 누르면 입력창에 시작 요청 문구만 채워지며 자동으로 전송되지는 않습니다. 플러그인 패널은 네트워크가 차단되고 스크립트만 허용되는 샌드박스 프레임에서 실행되며, 최대 4000자의 초안을 입력창에 넣을 수만 있을 뿐 자동 전송은 불가능하고 세션의 실시간 상태 줄을 수신하여 표시합니다.
|
|
144
145
|
|
|
145
146
|
**여러 에이전트와 함께 일하기**
|
|
@@ -9,7 +9,7 @@ const MEMORY_RE = /(const phase1Model = await resolveMemoryModel\(\{[^}]*?fallba
|
|
|
9
9
|
const MEMORY_DONE = /const phase1Model = await resolveMemoryModel\(\{[^}]*?fallbackRole: "smol"/;
|
|
10
10
|
const EXPECTED = {
|
|
11
11
|
name: 'cuelo',
|
|
12
|
-
version: '0.10.
|
|
12
|
+
version: '0.10.265',
|
|
13
13
|
distribution: 'cuelo',
|
|
14
14
|
coreVersion: '18.20.1',
|
|
15
15
|
};
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
|
|
2
|
+
import { appendFileSync } from "node:fs";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { allowingFailure, asksCoordinates, blockReason, displayProblem, imageQuestion, SYSTEM_BLOCK, type FindFailure } from "./policy";
|
|
7
|
+
import { ensureReady, realSetupDeps, runProcess, type Ready, type Run } from "./setup";
|
|
8
|
+
|
|
9
|
+
// 다른 앱 창 조작을 빠른 경로로 돌린다(2026-11-15 실측: AnyDesk 원격 명령 하나에 원격 vision 좌표 찾기 8회 61초,
|
|
10
|
+
// 로컬 OCR은 화면 전체 약 1초). lab_screen_find 도구, 좌표를 vision에 묻는 이미지 read 차단, 짧은 경로 안내.
|
|
11
|
+
|
|
12
|
+
const SCRIPT = join(import.meta.dir, "screen_find.py");
|
|
13
|
+
const MAX_LINES = 150;
|
|
14
|
+
export const EVENTS_FILE = "cuelo-screen-fast-path-events.jsonl";
|
|
15
|
+
|
|
16
|
+
type Log = (record: Record<string, unknown>) => void;
|
|
17
|
+
|
|
18
|
+
const defaultLog: Log = (record) => {
|
|
19
|
+
try {
|
|
20
|
+
// 설치된 플러그인 폴더(cuelo-plugins/<id>)에서 두 단계 위가 에이전트 폴더다. 정식 폴더는 프로필 동기화가 덮는다.
|
|
21
|
+
appendFileSync(join(import.meta.dir, "..", "..", EVENTS_FILE), `${JSON.stringify({ at: new Date().toISOString(), ...record })}\n`);
|
|
22
|
+
} catch {
|
|
23
|
+
// 기록 실패는 동작을 막지 않는다.
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export interface ScreenFastPathOptions {
|
|
28
|
+
env?: Record<string, string | undefined>;
|
|
29
|
+
platform?: string;
|
|
30
|
+
/** OCR 실행 환경 준비. 기본은 ~/.omp 아래 실제 설치·다운로드다. */
|
|
31
|
+
prepare?: (signal?: AbortSignal) => Promise<Ready>;
|
|
32
|
+
/** screen_find.py 실행. 테스트가 바꿔 끼운다. */
|
|
33
|
+
find?: (ready: Ready, args: string[], signal?: AbortSignal) => Promise<Run>;
|
|
34
|
+
log?: Log;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Params {
|
|
38
|
+
window?: string;
|
|
39
|
+
png?: string;
|
|
40
|
+
find?: string;
|
|
41
|
+
click?: string;
|
|
42
|
+
nth?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createScreenFastPath(options: ScreenFastPathOptions = {}) {
|
|
46
|
+
const env = options.env ?? process.env;
|
|
47
|
+
const platform = options.platform ?? process.platform;
|
|
48
|
+
const log = options.log ?? defaultLog;
|
|
49
|
+
const runFind = options.find ?? ((ready: Ready, args: string[], signal?: AbortSignal) =>
|
|
50
|
+
runProcess(ready.python, [SCRIPT, "--models", ready.modelsDir, ...args], { env: env as NodeJS.ProcessEnv, timeoutMs: 120_000, signal }));
|
|
51
|
+
|
|
52
|
+
return function screenFastPath(pi: ExtensionAPI): void {
|
|
53
|
+
const z = pi.zod;
|
|
54
|
+
const failures = new Map<string, FindFailure[]>();
|
|
55
|
+
let preparing: Promise<Ready> | undefined;
|
|
56
|
+
const sessionOf = (ctx: ExtensionContext | undefined) => ctx?.sessionManager?.getSessionId?.() ?? "";
|
|
57
|
+
const recordFailure = (ctx: ExtensionContext | undefined, failure: FindFailure) => {
|
|
58
|
+
const session = sessionOf(ctx);
|
|
59
|
+
failures.set(session, [...(failures.get(session) ?? []), failure]);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
pi.on("before_agent_start", (event) => {
|
|
63
|
+
if (event.reason !== "prompt") return;
|
|
64
|
+
return { systemPrompt: [...event.systemPrompt, SYSTEM_BLOCK] };
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
pi.on("tool_call", (event, ctx) => {
|
|
68
|
+
if (event.toolName !== "read") return;
|
|
69
|
+
const input: unknown = event.input;
|
|
70
|
+
const question = imageQuestion(input && typeof input === "object" && "path" in input ? input.path : undefined);
|
|
71
|
+
if (!question || !asksCoordinates(question.question)) return;
|
|
72
|
+
const allowed = allowingFailure(failures.get(sessionOf(ctx)) ?? [], question);
|
|
73
|
+
if (allowed) {
|
|
74
|
+
log({ event: "allowed", target: question.target, question: question.question.slice(0, 200), after: allowed });
|
|
75
|
+
return { additionalContext: `screen-fast-path: lab_screen_find가 이 대상에서 실패해(${JSON.stringify(allowed)}) 좌표 질문을 허용했다.` };
|
|
76
|
+
}
|
|
77
|
+
log({ event: "blocked", target: question.target, question: question.question.slice(0, 200) });
|
|
78
|
+
return { block: true, reason: blockReason(question) };
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
pi.registerTool({
|
|
82
|
+
name: "lab_screen_find",
|
|
83
|
+
label: "Screen find (local OCR)",
|
|
84
|
+
loadMode: "essential",
|
|
85
|
+
description:
|
|
86
|
+
"Find text on screen with local OCR (Korean + English, about 1 s) and optionally click it. For pixel-only windows (AnyDesk, RDP canvas, games) where AX/UIA cannot see controls. "
|
|
87
|
+
+ "Returns one line per text box: `x y score text` in global screen coordinates (image pixels with `png`). "
|
|
88
|
+
+ "`window` = title regex of the window to capture (largest visible match; default whole screen); `png` = OCR an existing image instead (no capture, no click); "
|
|
89
|
+
+ "`find` = keep only boxes containing this text (case-insensitive, spaces ignored); `click` = click the `nth` (default 1) box containing this text through XTEST and put the mouse back. "
|
|
90
|
+
+ "A `window` is read from its own pixels even when other windows cover it; `click` brings that window to the front first, because XTEST clicks land on whatever is on top. "
|
|
91
|
+
+ "The capture is deleted right away. Unfiltered output can include private screen text, so narrow with `find`/`click`. "
|
|
92
|
+
+ "First use installs rapidocr_onnxruntime into ~/.omp/python-env and downloads the Korean recognition model (sha256 checked). Needs an X11 session except with `png`.",
|
|
93
|
+
parameters: z.object({
|
|
94
|
+
window: z.string().optional().describe("Window title regex; default whole screen"),
|
|
95
|
+
png: z.string().optional().describe("Existing image to OCR instead of capturing; no click"),
|
|
96
|
+
find: z.string().optional().describe("Only boxes containing this text"),
|
|
97
|
+
click: z.string().optional().describe("Click the box containing this text"),
|
|
98
|
+
nth: z.number().int().min(1).optional().describe("Which match to click, 1-based (default 1)"),
|
|
99
|
+
}),
|
|
100
|
+
async execute(_callId, rawParams, signal, _onUpdate, ctx) {
|
|
101
|
+
const params = rawParams as Params;
|
|
102
|
+
const target: FindFailure = {
|
|
103
|
+
...(params.window ? { window: params.window } : {}),
|
|
104
|
+
...(params.click ?? params.find ? { find: params.click ?? params.find } : {}),
|
|
105
|
+
...(params.png ? { png: params.png } : {}),
|
|
106
|
+
};
|
|
107
|
+
const reply = (text: string) => ({ content: [{ type: "text" as const, text }] });
|
|
108
|
+
if (platform !== "linux") {
|
|
109
|
+
recordFailure(ctx, { ...target, environment: true });
|
|
110
|
+
return reply(`lab_screen_find: 이 PC(${platform})는 지원하지 않는다. 화면 캡처, XTEST 클릭, OCR 실행 환경 준비가 모두 Linux 기준이다.`);
|
|
111
|
+
}
|
|
112
|
+
if (params.png && params.click) return reply("lab_screen_find: png 좌표는 이미지 픽셀이라 click과 함께 쓸 수 없다. 화면에서 누르려면 window를 준다.");
|
|
113
|
+
if (!params.png) {
|
|
114
|
+
const problem = displayProblem(env);
|
|
115
|
+
if (problem) {
|
|
116
|
+
recordFailure(ctx, { ...target, environment: true });
|
|
117
|
+
return reply(`lab_screen_find: ${problem}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
let ready: Ready;
|
|
121
|
+
try {
|
|
122
|
+
// 준비는 같은 프로세스의 호출이 함께 기다리므로 첫 호출자의 중단 신호에 묶지 않는다.
|
|
123
|
+
preparing ??= (options.prepare ?? (() => ensureReady(realSetupDeps())))();
|
|
124
|
+
ready = await preparing;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
preparing = undefined;
|
|
127
|
+
recordFailure(ctx, { ...target, environment: true });
|
|
128
|
+
log({ event: "setup-failed", error: error instanceof Error ? error.message : String(error) });
|
|
129
|
+
return reply(`lab_screen_find: OCR 실행 환경 준비에 실패했다. ${error instanceof Error ? error.message : String(error)}`);
|
|
130
|
+
}
|
|
131
|
+
// `--name=value`로 넘겨 `-`로 시작하는 글자도 옵션으로 읽히지 않게 한다.
|
|
132
|
+
const args: string[] = [];
|
|
133
|
+
if (params.window) args.push(`--window=${params.window}`);
|
|
134
|
+
if (params.png) args.push(`--png=${params.png}`);
|
|
135
|
+
if (params.click) args.push(`--click=${params.click}`, `--nth=${params.nth ?? 1}`);
|
|
136
|
+
else if (params.find) args.push(`--find=${params.find}`);
|
|
137
|
+
// 캡처는 이 폴더에 두고 여기서 지운다. 파이썬이 시간 초과(SIGKILL)로 죽어도 화면 사진이 남지 않는다.
|
|
138
|
+
const scratch = params.png ? undefined : await mkdtemp(join(tmpdir(), "screen-find-"));
|
|
139
|
+
if (scratch) args.push(`--tmpdir=${scratch}`);
|
|
140
|
+
const started = Date.now();
|
|
141
|
+
let run: Run;
|
|
142
|
+
try {
|
|
143
|
+
run = await runFind(ready, args, signal);
|
|
144
|
+
} finally {
|
|
145
|
+
if (scratch) await rm(scratch, { recursive: true, force: true });
|
|
146
|
+
}
|
|
147
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
148
|
+
const prepared = ready.steps.length ? `\n(처음 사용 준비: ${ready.steps.join(", ")})` : "";
|
|
149
|
+
ready.steps = [];
|
|
150
|
+
const lines = run.stdout.trim().split("\n").filter(Boolean);
|
|
151
|
+
if (run.code !== 0) {
|
|
152
|
+
recordFailure(ctx, target);
|
|
153
|
+
const why = run.code === 3 ? "결과 없음" : "실패";
|
|
154
|
+
const narrowed = Boolean(target.window || target.find || target.png);
|
|
155
|
+
return reply([
|
|
156
|
+
`lab_screen_find: ${why} (${seconds}s). ${run.stderr.trim().slice(-400)}`,
|
|
157
|
+
...lines.slice(0, MAX_LINES),
|
|
158
|
+
narrowed
|
|
159
|
+
? "이 대상의 좌표는 이제 `read <이미지>?q=` 질문으로도 물을 수 있다."
|
|
160
|
+
: "대상을 좁히지 않은 실패라 좌표 질문은 열리지 않는다. window나 find로 대상을 정해 다시 찾는다.",
|
|
161
|
+
].join("\n") + prepared);
|
|
162
|
+
}
|
|
163
|
+
const shown = lines.slice(0, MAX_LINES);
|
|
164
|
+
const more = lines.length > shown.length ? `\n… ${lines.length - shown.length}개 더 있음. find로 좁힌다.` : "";
|
|
165
|
+
const privacy = params.find || params.click ? "" : "\n(화면의 모든 글자가 담길 수 있다. 다음에는 find나 click으로 좁힌다.)";
|
|
166
|
+
const boxes = lines.filter((line) => !line.startsWith("clicked ")).length;
|
|
167
|
+
return reply(`lab_screen_find: ${boxes}개 (${seconds}s, x y score text)\n${shown.join("\n")}${more}${privacy}${prepared}`);
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export default createScreenFastPath();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "screen-fast-path",
|
|
3
|
+
"name": "화면 조작 빠른 경로",
|
|
4
|
+
"description": "다른 앱 창을 조작할 때 빠른 경로를 쓰게 합니다. 그림뿐인 창(AnyDesk, RDP 화면)은 lab_screen_find가 로컬 OCR로 약 1초 만에 글자 위치를 찾고 누를 수 있으며, 화면 이미지의 클릭 좌표를 vision 모델에게 묻는 읽기는 그 대상에서 lab_screen_find가 실패한 뒤에만 통과시킵니다. 처음 쓸 때 OCR 실행 환경과 한국어 인식 모델(sha256 확인)을 스스로 준비하고, 화면이 없는 PC에서는 그 사실을 바로 알립니다.",
|
|
5
|
+
"createdAt": "2026-11-15T12:00:00+09:00",
|
|
6
|
+
"enhancements": [],
|
|
7
|
+
"extension": "index.ts",
|
|
8
|
+
"tools": ["lab_screen_find"]
|
|
9
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// screen-fast-path의 순수 판정: 이미지 read가 클릭 좌표를 vision 모델에게 묻는지, 이 PC에 화면 조작 경로가 있는지,
|
|
2
|
+
// lab_screen_find 실패 뒤 같은 대상의 좌표 질문을 허용할지.
|
|
3
|
+
|
|
4
|
+
const IMAGE_PATH = /\.(?:png|jpe?g|gif|webp|bmp)$/i;
|
|
5
|
+
|
|
6
|
+
// 좌표·클릭 지점을 찾는 질문. "위치" 단독은 레이아웃 판단(정렬, 겹침)과 겹치므로 클릭·찾기 동사와 묶일 때만 본다.
|
|
7
|
+
const COORDINATE_PATTERNS: RegExp[] = [
|
|
8
|
+
/좌표/,
|
|
9
|
+
/픽셀\s*(?:위치|좌표)/,
|
|
10
|
+
/(?:(?:클릭|탭|선택|드래그)(?:할|해야\s*할|하는)?|누를|눌러야\s*할|누르는)\s*(?:곳|위치|지점|자리|부분|데)/,
|
|
11
|
+
/어디(?:를|에|쯤)?\s*(?:클릭|눌러|누르|탭)/,
|
|
12
|
+
/위치(?:를|가|는)?\s*(?:알려|찾아|말해|구해|정확히|어디)/,
|
|
13
|
+
/위치[^.?!]*(?:클릭하려|클릭할게|클릭해야|누르려|누를게|눌러야)/,
|
|
14
|
+
/coordinat/i,
|
|
15
|
+
/\bcoords?\b/i,
|
|
16
|
+
/\bpixel\s*(?:position|location|coordinates?|offset)s?\b/i,
|
|
17
|
+
/\b(?:position|location)\b[^.?!]*\b(?:to|can|should|will|must|could)\s+(?:i\s+|we\s+)?(?:click|tap|press)\b/i,
|
|
18
|
+
// 클릭 의도(to click, I will click, I want to click)가 위치 요청보다 앞에 오는 문장.
|
|
19
|
+
/\b(?:to|i\s+will|i'll|i\s+want\s+to|so\s+(?:i|we)\s+can)\s+(?:click|tap|press)\b[^?!]*\b(?:position|location)\b/i,
|
|
20
|
+
/\b(?:click|tap)\s+(?:position|location)\s+of\b/i,
|
|
21
|
+
/\bbounding\s*box|\bbbox\b/i,
|
|
22
|
+
/where\s+(?:\w+\s+){0,3}(?:click|tap|press)/i,
|
|
23
|
+
/\b(?:click|tap)\s+(?:target|point|spot)\b/i,
|
|
24
|
+
/\bx\s*[,/]\s*y\b|\bx\s+and\s+y\b/i,
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
export interface ImageQuestion {
|
|
28
|
+
/** `?` 앞 경로 그대로. Linux에서는 역슬래시도 파일 이름 글자라 바꾸지 않는다. */
|
|
29
|
+
target: string;
|
|
30
|
+
question: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function decode(value: string): string {
|
|
34
|
+
try {
|
|
35
|
+
return decodeURIComponent(value.replace(/\+/g, " "));
|
|
36
|
+
} catch {
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 이미지 `read`의 `?q=` 질문을 꺼낸다. `?ocr=`(글자 판독)과 질문 없는 read, URL은 대상이 아니다. */
|
|
42
|
+
export function imageQuestion(path: unknown): ImageQuestion | undefined {
|
|
43
|
+
if (typeof path !== "string") return undefined;
|
|
44
|
+
const trimmed = path.trim();
|
|
45
|
+
if (!trimmed || /^https?:\/\//i.test(trimmed)) return undefined;
|
|
46
|
+
const at = trimmed.indexOf("?");
|
|
47
|
+
if (at < 0) return undefined;
|
|
48
|
+
const base = trimmed.slice(0, at);
|
|
49
|
+
if (!IMAGE_PATH.test(base)) return undefined;
|
|
50
|
+
const match = /(?:^|&)q=([^&]*)/.exec(trimmed.slice(at + 1));
|
|
51
|
+
if (!match) return undefined;
|
|
52
|
+
return { target: base, question: decode(match[1]) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 휴리스틱이다. 따옴표 안 글자(버튼이나 라벨 이름)는 빼고 본다: "'Click target' 라벨이 가운데인가"는 좌표 질문이 아니다. */
|
|
56
|
+
export function asksCoordinates(question: string): boolean {
|
|
57
|
+
const unquoted = question.replace(/'[^']*'|"[^"]*"|「[^」]*」|“[^”]*”|‘[^’]*’/g, " ");
|
|
58
|
+
return COORDINATE_PATTERNS.some((pattern) => pattern.test(unquoted));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const FAST_PATHS = [
|
|
62
|
+
"1. 리눅스 앱(이 PC의 GTK/Qt/Electron 창): eval의 `computer` AX(AT-SPI)로 요소를 찾고 누른다.",
|
|
63
|
+
"2. WinBoat VM 안 Windows 앱: skill winboat-desktop의 `scripts/vm-desktop.sh`(UIA)로 요소를 찾고 누른다.",
|
|
64
|
+
"3. 그림뿐인 창(AnyDesk, RDP 캔버스, 게임): `lab_screen_find`(window, find, click)로 로컬 OCR 좌표를 받거나 바로 누른다. 약 1초.",
|
|
65
|
+
"4. 원격 PC의 셸 작업: 아이콘을 클릭해 가지 말고 키보드 경로(Ctrl+Esc → powershell → 한 줄 붙여넣기)로 실행한다.",
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
export function blockReason(question: ImageQuestion): string {
|
|
69
|
+
return [
|
|
70
|
+
"screen-fast-path: 화면 이미지의 클릭 좌표를 vision 모델에게 묻는 read를 막았다. 한 번에 9초 안팎이 들고 좌표가 틀리거나 거부되기도 한다.",
|
|
71
|
+
"빠른 경로를 이 순서로 쓴다:",
|
|
72
|
+
...FAST_PATHS,
|
|
73
|
+
`\`lab_screen_find\`가 이 대상에서 결과 없음이나 실패를 돌려준 뒤에는 같은 대상(같은 이미지, 같은 찾는 글자, 같은 창 이름)의 좌표 질문이 통과한다. 지금 막힌 이미지: ${question.target}`,
|
|
74
|
+
"좌표가 아닌 설명 질문(상태, 레이아웃, 오류 내용)은 `?q=`로, 글자 판독은 `?ocr=`로 그대로 read하면 된다.",
|
|
75
|
+
].join("\n");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Linux에서 화면 캡처·클릭 경로가 없으면 그 이유. Linux가 아닌 PC는 호출자가 png 모드까지 통째로 거절한다. */
|
|
79
|
+
export function displayProblem(env: Record<string, string | undefined>): string | undefined {
|
|
80
|
+
const session = (env.XDG_SESSION_TYPE ?? "").toLowerCase();
|
|
81
|
+
// XWayland가 DISPLAY를 줘도 Wayland 창은 X11 캡처에 비어 보이므로, x11이라고 밝힌 세션만 화면 경로로 본다.
|
|
82
|
+
if (session === "wayland" || (session !== "x11" && env.WAYLAND_DISPLAY)) {
|
|
83
|
+
return "이 PC는 Wayland 세션이라 lab_screen_find의 화면 캡처와 XTEST 클릭을 쓸 수 없다.";
|
|
84
|
+
}
|
|
85
|
+
if (!env.DISPLAY) return "이 PC에는 화면 조작 경로가 없다(DISPLAY가 없는 서버나 클라우드). 기존 이미지는 png 인자로만 판독할 수 있다.";
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface FindFailure {
|
|
90
|
+
/** 환경 실패(화면 없음, 준비 실패)는 대상과 상관없이 좌표 질문을 허용한다. */
|
|
91
|
+
environment?: boolean;
|
|
92
|
+
window?: string;
|
|
93
|
+
find?: string;
|
|
94
|
+
png?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const norm = (text: string) => text.replace(/\s+/g, "").toLowerCase();
|
|
98
|
+
|
|
99
|
+
/** 같은 세션의 lab_screen_find 실패 가운데 이 좌표 질문을 허용하는 것. 대상을 좁히지 않은 실패는 아무것도 허용하지 않는다. */
|
|
100
|
+
export function allowingFailure(failures: readonly FindFailure[], question: ImageQuestion): FindFailure | undefined {
|
|
101
|
+
const asked = norm(question.question);
|
|
102
|
+
const target = norm(question.target);
|
|
103
|
+
return failures.find((failure) => {
|
|
104
|
+
if (failure.environment) return true;
|
|
105
|
+
// 경로는 Linux에서 대소문자, 공백, 역슬래시까지 다른 파일이므로 그대로 비교한다.
|
|
106
|
+
if (failure.png && failure.png === question.target) return true;
|
|
107
|
+
if (failure.find && norm(failure.find) && asked.includes(norm(failure.find))) return true;
|
|
108
|
+
if (failure.window) {
|
|
109
|
+
// lab_screen_find는 window를 창 제목 정규식으로 쓴다. 같은 정규식이 질문이나 이미지 경로에 걸려야 같은 창이다.
|
|
110
|
+
// 앵커(`^AnyDesk$`)가 있으면 글 전체로는 안 걸리므로 각 필드 안의 연속 낱말 묶음(길이 제한 없음)에 대어 본다.
|
|
111
|
+
// 질문과 경로는 섞지 않는다. 빈 글에도 걸리는 정규식(`.*`, `AnyDesk|`)은 대상을 좁히지 않은 것이라 아무것도 열지 않는다.
|
|
112
|
+
let title: RegExp;
|
|
113
|
+
try {
|
|
114
|
+
title = new RegExp(failure.window, "i");
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
if (title.test("")) return false;
|
|
119
|
+
const spans = (text: string) => {
|
|
120
|
+
const words = text.split(/[\s/\\]+/).map((word) => word.replace(/^[,;:'"`()[\]{}<>?!.]+|[,;:'"`()[\]{}<>?!.]+$/g, "")).filter(Boolean);
|
|
121
|
+
return [text, ...words.flatMap((_, i) => words.slice(i).map((__, n) => words.slice(i, i + n + 1).join(" ")))];
|
|
122
|
+
};
|
|
123
|
+
// 경로는 확장자를 뗀 파일 이름도 본다(`/tmp/AnyDesk.png` → AnyDesk).
|
|
124
|
+
const file = question.target.split("/").pop()?.replace(/\.[^.]+$/, "") ?? "";
|
|
125
|
+
if ([...spans(question.question.slice(0, 500)), ...spans(question.target), file].some((piece) => title.test(piece))) return true;
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const SYSTEM_BLOCK = `# Screen work fast path
|
|
132
|
+
When you operate another app's window, use the fastest path and bundle act-wait-check into one call so each step costs one model turn:
|
|
133
|
+
1. Linux app on this PC: \`computer\` AX (AT-SPI) in eval.
|
|
134
|
+
2. Windows app in the WinBoat VM: skill winboat-desktop \`scripts/vm-desktop.sh\` (UIA).
|
|
135
|
+
3. Pixel-only window (AnyDesk, RDP canvas, games): \`lab_screen_find\` (local OCR, about 1 s; \`click\` presses the match).
|
|
136
|
+
4. Shell work on a remote PC: keyboard path (open a console, paste one line), not icon clicks.
|
|
137
|
+
Never ask a vision model for click coordinates: \`read <image>?q=\` coordinate questions are blocked until \`lab_screen_find\` failed on that target. \`?ocr=\` and non-coordinate questions stay open.`;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Local OCR of a screen region with click targets (Korean + English), about 1 s per 2560x1376 frame.
|
|
3
|
+
|
|
4
|
+
Run by the screen-fast-path plugin with ~/.omp/python-env/bin/python and the X session's DISPLAY/XAUTHORITY.
|
|
5
|
+
screen_find.py --models DIR [--window REGEX] [--png PATH] [--find TEXT] [--click TEXT] [--nth N]
|
|
6
|
+
--window capture the largest visible window whose title matches (default: whole root window)
|
|
7
|
+
--png OCR an existing image instead of capturing (coordinates are image pixels; no click)
|
|
8
|
+
--find print only boxes whose text contains TEXT (case-insensitive, spaces ignored)
|
|
9
|
+
--click click the center of the Nth (default 1st) box containing TEXT through XTEST, then restore the mouse
|
|
10
|
+
Prints "x y score text" per box in global screen coordinates, then "clicked x y" after a click.
|
|
11
|
+
Exit codes: 0 ok, 2 bad arguments or no window, 3 nothing matched, 4 capture/click failure.
|
|
12
|
+
The captured png is deleted before OCR results are printed.
|
|
13
|
+
"""
|
|
14
|
+
import argparse, os, subprocess, sys, tempfile, time
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sh(*a):
|
|
18
|
+
return subprocess.run(a, check=True, capture_output=True, text=True).stdout.strip()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fail(code, message):
|
|
22
|
+
print(message, file=sys.stderr)
|
|
23
|
+
sys.exit(code)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find_window(pattern):
|
|
27
|
+
"""Largest visible window whose title matches; returns its X id."""
|
|
28
|
+
try:
|
|
29
|
+
ids = sh("xdotool", "search", "--onlyvisible", "--name", pattern).split()
|
|
30
|
+
except subprocess.CalledProcessError:
|
|
31
|
+
ids = []
|
|
32
|
+
best = None
|
|
33
|
+
for w in ids:
|
|
34
|
+
try:
|
|
35
|
+
g = dict(l.split("=", 1) for l in sh("xdotool", "getwindowgeometry", "--shell", w).splitlines())
|
|
36
|
+
except subprocess.CalledProcessError:
|
|
37
|
+
continue
|
|
38
|
+
area = int(g["WIDTH"]) * int(g["HEIGHT"])
|
|
39
|
+
if best is None or area > best[1]:
|
|
40
|
+
best = (w, area)
|
|
41
|
+
if not best or best[1] < 10000:
|
|
42
|
+
fail(2, f"no visible window title matches {pattern!r}")
|
|
43
|
+
return best[0]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Capture runs in the system python3, which has the GTK bindings; the OCR venv does not need them.
|
|
47
|
+
# A window is read from its own pixels, so a window covered by others (or a compositing WM's redirected window)
|
|
48
|
+
# still gives its own content; the root window gives whatever is on top.
|
|
49
|
+
# With "-" as the output path it only prints the origin, so a later position is read the same way as the capture's.
|
|
50
|
+
CAPTURE = (
|
|
51
|
+
"import gi,sys; gi.require_version('Gdk','3.0'); gi.require_version('GdkX11','3.0'); from gi.repository import Gdk,GdkX11; "
|
|
52
|
+
"w=GdkX11.X11Window.foreign_new_for_display(GdkX11.X11Display.get_default(),int(sys.argv[1])) if sys.argv[1]!='root' else Gdk.get_default_root_window(); "
|
|
53
|
+
"_,x,y=w.get_origin(); "
|
|
54
|
+
"p=None if sys.argv[2]=='-' else Gdk.pixbuf_get_from_window(w,0,0,w.get_width(),w.get_height()); "
|
|
55
|
+
"sys.argv[2]=='-' or p or sys.exit('capture returned nothing (window minimized or not viewable?)'); "
|
|
56
|
+
"p and p.savev(sys.argv[2],'png',[],[]); print(x,y)"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def capture(window, path):
|
|
61
|
+
"""Save the window (or whole screen) to path, or with path "-" only read its origin; returns the origin."""
|
|
62
|
+
run = subprocess.run(["/usr/bin/python3", "-c", CAPTURE, window or "root", path], capture_output=True, text=True)
|
|
63
|
+
if run.returncode != 0:
|
|
64
|
+
fail(4, f"screen capture failed: {(run.stderr or run.stdout).strip()[-300:]}")
|
|
65
|
+
x0, y0 = run.stdout.split()
|
|
66
|
+
return int(x0), int(y0)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def main():
|
|
70
|
+
p = argparse.ArgumentParser()
|
|
71
|
+
p.add_argument("--models", required=True)
|
|
72
|
+
p.add_argument("--window")
|
|
73
|
+
p.add_argument("--png")
|
|
74
|
+
p.add_argument("--find")
|
|
75
|
+
p.add_argument("--click")
|
|
76
|
+
p.add_argument("--nth", type=int, default=1)
|
|
77
|
+
p.add_argument("--tmpdir", help="where the capture goes; the caller removes it even if this process is killed")
|
|
78
|
+
a = p.parse_args()
|
|
79
|
+
if a.png and a.click:
|
|
80
|
+
fail(2, "--click needs a live screen; --png coordinates are image pixels")
|
|
81
|
+
if a.nth < 1:
|
|
82
|
+
fail(2, "--nth starts at 1")
|
|
83
|
+
origin = (0, 0)
|
|
84
|
+
png, tmp, window = a.png, None, None
|
|
85
|
+
if not png:
|
|
86
|
+
window = find_window(a.window) if a.window else None
|
|
87
|
+
fd, tmp = tempfile.mkstemp(suffix=".png", prefix="screen-find-", dir=a.tmpdir)
|
|
88
|
+
os.close(fd)
|
|
89
|
+
png = tmp
|
|
90
|
+
try:
|
|
91
|
+
if tmp:
|
|
92
|
+
origin = capture(window, tmp)
|
|
93
|
+
elif not os.path.isfile(png):
|
|
94
|
+
fail(2, f"no such image: {png}")
|
|
95
|
+
from rapidocr_onnxruntime import RapidOCR
|
|
96
|
+
eng = RapidOCR(
|
|
97
|
+
rec_model_path=os.path.join(a.models, "korean_PP-OCRv5_rec_mobile.onnx"),
|
|
98
|
+
rec_keys_path=os.path.join(a.models, "ppocrv5_korean_dict.txt"),
|
|
99
|
+
)
|
|
100
|
+
res, _ = eng(png)
|
|
101
|
+
finally:
|
|
102
|
+
if tmp and os.path.exists(tmp):
|
|
103
|
+
os.unlink(tmp)
|
|
104
|
+
boxes = []
|
|
105
|
+
for box, txt, score in res or []:
|
|
106
|
+
x = int(sum(pt[0] for pt in box) / 4) + origin[0]
|
|
107
|
+
y = int(sum(pt[1] for pt in box) / 4) + origin[1]
|
|
108
|
+
boxes.append((y, x, float(score), txt))
|
|
109
|
+
boxes.sort()
|
|
110
|
+
norm = lambda s: "".join(s.split()).lower()
|
|
111
|
+
want = a.click or a.find
|
|
112
|
+
if want:
|
|
113
|
+
boxes = [b for b in boxes if norm(want) in norm(b[3])]
|
|
114
|
+
for y, x, s, t in boxes:
|
|
115
|
+
print(x, y, round(s, 2), t)
|
|
116
|
+
if not boxes:
|
|
117
|
+
fail(3, f"no text matches {want!r}" if want else "no text recognised")
|
|
118
|
+
if a.click:
|
|
119
|
+
if len(boxes) < a.nth:
|
|
120
|
+
fail(3, f"only {len(boxes)} matches for {want!r}, nth={a.nth}")
|
|
121
|
+
y, x, _, _ = boxes[a.nth - 1]
|
|
122
|
+
m = None
|
|
123
|
+
try:
|
|
124
|
+
m = dict(l.split("=", 1) for l in sh("xdotool", "getmouselocation", "--shell").splitlines())
|
|
125
|
+
# XTEST clicks land on whatever is on top, so a covered window has to come to the front first.
|
|
126
|
+
if window:
|
|
127
|
+
sh("xdotool", "windowactivate", "--sync", window)
|
|
128
|
+
time.sleep(0.2)
|
|
129
|
+
# The window may have moved since the capture; shift the target by the same amount.
|
|
130
|
+
after = capture(window, "-")
|
|
131
|
+
x, y = x + after[0] - origin[0], y + after[1] - origin[1]
|
|
132
|
+
sh("xdotool", "mousemove", str(x), str(y), "click", "1")
|
|
133
|
+
except subprocess.CalledProcessError as e:
|
|
134
|
+
fail(4, f"click failed: {e.stderr.strip()[-300:]}")
|
|
135
|
+
finally:
|
|
136
|
+
if m:
|
|
137
|
+
subprocess.run(["xdotool", "mousemove", m["X"], m["Y"]], capture_output=True)
|
|
138
|
+
print(f"clicked {x} {y}")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
if __name__ == "__main__":
|
|
142
|
+
main()
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
// lab_screen_find가 처음 쓰일 때 집, 사무실, 클라우드에서 같은 방식으로 OCR 실행 환경을 갖춘다:
|
|
9
|
+
// ~/.omp/python-env에 rapidocr_onnxruntime(고정 버전)과 ~/.omp/ocr-models의 한국어 인식 모델 두 파일(sha256 확인).
|
|
10
|
+
// 검출 모델은 rapidocr_onnxruntime 휠에 들어 있다.
|
|
11
|
+
|
|
12
|
+
export const RAPIDOCR_SPEC = "rapidocr_onnxruntime==1.4.4";
|
|
13
|
+
|
|
14
|
+
// RapidOCR default_models.yaml v3.10.0의 Korean PP-OCRv5 mobile 인식 모델과 사전.
|
|
15
|
+
export const MODEL_FILES = [
|
|
16
|
+
{
|
|
17
|
+
name: "korean_PP-OCRv5_rec_mobile.onnx",
|
|
18
|
+
url: "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv5/rec/korean_PP-OCRv5_rec_mobile.onnx",
|
|
19
|
+
sha256: "cd6e2ea50f6943ca7271eb8c56a877a5a90720b7047fe9c41a2e541a25773c9b",
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: "ppocrv5_korean_dict.txt",
|
|
23
|
+
url: "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/paddle/PP-OCRv5/rec/korean_PP-OCRv5_rec_mobile/ppocrv5_korean_dict.txt",
|
|
24
|
+
sha256: "a88071c68c01707489baa79ebe0405b7beb5cca229f4fc94cc3ef992328802d7",
|
|
25
|
+
},
|
|
26
|
+
] as const;
|
|
27
|
+
|
|
28
|
+
export interface Run {
|
|
29
|
+
code: number;
|
|
30
|
+
stdout: string;
|
|
31
|
+
stderr: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SetupDeps {
|
|
35
|
+
pythonEnv: string;
|
|
36
|
+
modelsDir: string;
|
|
37
|
+
run(command: string, args: string[], options?: { env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<Run>;
|
|
38
|
+
download(url: string, signal?: AbortSignal): Promise<Uint8Array>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function runProcess(command: string, args: string[], options: { env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal } = {}): Promise<Run> {
|
|
42
|
+
const { promise, resolve } = Promise.withResolvers<Run>();
|
|
43
|
+
const child = spawn(command, args, { env: options.env ?? process.env, stdio: ["ignore", "pipe", "pipe"], signal: options.signal });
|
|
44
|
+
let stdout = "";
|
|
45
|
+
let stderr = "";
|
|
46
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
47
|
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
48
|
+
const timer = options.timeoutMs ? setTimeout(() => child.kill("SIGKILL"), options.timeoutMs) : undefined;
|
|
49
|
+
child.on("error", (error) => {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
resolve({ code: -1, stdout, stderr: stderr || String(error) });
|
|
52
|
+
});
|
|
53
|
+
child.on("close", (code) => {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
resolve({ code: code ?? -1, stdout, stderr });
|
|
56
|
+
});
|
|
57
|
+
return promise;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function realSetupDeps(): SetupDeps {
|
|
61
|
+
const omp = join(homedir(), ".omp");
|
|
62
|
+
return {
|
|
63
|
+
pythonEnv: join(omp, "python-env"),
|
|
64
|
+
modelsDir: join(omp, "ocr-models"),
|
|
65
|
+
run: runProcess,
|
|
66
|
+
async download(url, signal) {
|
|
67
|
+
const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(120_000), redirect: "follow" });
|
|
68
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
69
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
75
|
+
const tail = (run: Run) => (run.stderr || run.stdout).trim().slice(-400);
|
|
76
|
+
|
|
77
|
+
export interface Ready {
|
|
78
|
+
python: string;
|
|
79
|
+
modelsDir: string;
|
|
80
|
+
/** 이번 호출에서 새로 한 준비 단계. 이미 갖춰져 있었으면 비어 있다. */
|
|
81
|
+
steps: string[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 실행 환경을 갖춘다. 실패하면 사람에게 보여 줄 이유를 담은 Error를 던진다. */
|
|
85
|
+
export async function ensureReady(deps: SetupDeps, signal?: AbortSignal): Promise<Ready> {
|
|
86
|
+
const steps: string[] = [];
|
|
87
|
+
const python = join(deps.pythonEnv, "bin", "python");
|
|
88
|
+
if (!existsSync(python)) {
|
|
89
|
+
const fresh = !existsSync(deps.pythonEnv);
|
|
90
|
+
const venv = await deps.run("python3", ["-m", "venv", deps.pythonEnv], { timeoutMs: 120_000, signal });
|
|
91
|
+
if (venv.code !== 0 || !existsSync(python)) {
|
|
92
|
+
// 반쯤 만든 환경(bin/python은 있고 pip는 없음)이 남으면 다음 호출이 생성을 건너뛴다. 이번에 새로 만든 폴더면 통째로,
|
|
93
|
+
// 원래 있던 폴더면 이번 시도가 만든 bin/python만 지워 다음 호출이 venv 생성을 다시 하게 한다.
|
|
94
|
+
await rm(fresh ? deps.pythonEnv : python, { recursive: fresh, force: true });
|
|
95
|
+
throw new Error(`파이썬 환경(${deps.pythonEnv})을 만들지 못했다: ${tail(venv)}`);
|
|
96
|
+
}
|
|
97
|
+
steps.push(`파이썬 환경 생성(${deps.pythonEnv})`);
|
|
98
|
+
}
|
|
99
|
+
const probe = await deps.run(python, ["-c", "import rapidocr_onnxruntime"], { timeoutMs: 60_000, signal });
|
|
100
|
+
if (probe.code !== 0) {
|
|
101
|
+
const install = await deps.run(python, ["-m", "pip", "install", "--disable-pip-version-check", "-q", RAPIDOCR_SPEC], { timeoutMs: 600_000, signal });
|
|
102
|
+
if (install.code !== 0) throw new Error(`${RAPIDOCR_SPEC} 설치에 실패했다: ${tail(install)}`);
|
|
103
|
+
steps.push(`${RAPIDOCR_SPEC} 설치`);
|
|
104
|
+
}
|
|
105
|
+
await mkdir(deps.modelsDir, { recursive: true });
|
|
106
|
+
for (const model of MODEL_FILES) {
|
|
107
|
+
const path = join(deps.modelsDir, model.name);
|
|
108
|
+
if (existsSync(path) && sha256(await readFile(path)) === model.sha256) continue;
|
|
109
|
+
let bytes: Uint8Array;
|
|
110
|
+
try {
|
|
111
|
+
bytes = await deps.download(model.url, signal);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw new Error(`${model.name} 다운로드 실패(${model.url}): ${error instanceof Error ? error.message : String(error)}`);
|
|
114
|
+
}
|
|
115
|
+
const got = sha256(bytes);
|
|
116
|
+
if (got !== model.sha256) throw new Error(`${model.name}의 sha256이 맞지 않아 버렸다(기대 ${model.sha256}, 받은 값 ${got}).`);
|
|
117
|
+
const partial = `${path}.partial-${process.pid}`;
|
|
118
|
+
try {
|
|
119
|
+
await writeFile(partial, bytes);
|
|
120
|
+
await rename(partial, path);
|
|
121
|
+
} finally {
|
|
122
|
+
await rm(partial, { force: true });
|
|
123
|
+
}
|
|
124
|
+
steps.push(`${model.name} 다운로드(sha256 확인)`);
|
|
125
|
+
}
|
|
126
|
+
return { python, modelsDir: deps.modelsDir, steps };
|
|
127
|
+
}
|