@infodb/p3 0.1.0 → 0.3.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 +6 -1
- package/dist/web/assets/{Outputs-Ni3pNuGU.js → Outputs-DqJdybkd.js} +1 -1
- package/dist/web/assets/{RequestStatus-K8TZwpur.js → RequestStatus-DN-2iAM0.js} +1 -1
- package/dist/web/assets/TagInput-D-1ILLDX.js +1 -0
- package/dist/web/assets/TaskDrawer-CHD7T-Su.js +3 -0
- package/dist/web/assets/_requestId-BzSepQIV.js +30 -0
- package/dist/web/assets/_requestId-pIds2tFU.js +1 -0
- package/dist/web/assets/board-BIkOpuC4.js +1 -0
- package/dist/web/assets/directTask-Dk3H5Q2B.js +1 -0
- package/dist/web/assets/done-BUAUhIRr.js +1 -0
- package/dist/web/assets/draft-CfJeyLOl.js +1 -0
- package/dist/web/assets/index-Byv9j77D.js +12 -0
- package/dist/web/assets/index-DTfUhuQw.css +2 -0
- package/dist/web/assets/new-6kly4-PX.js +1 -0
- package/dist/web/assets/preload-helper-DlN0ouRj.js +1 -0
- package/dist/web/assets/release-notes-iwQWmfX6.js +3 -0
- package/dist/web/assets/requestData-DJ1Rlx-u.js +1 -0
- package/dist/web/assets/routes-Ciot9p4x.js +2 -0
- package/dist/web/assets/settings-DBCi6lAY.js +1 -0
- package/dist/web/assets/ui-Sz7y5_TS.js +1 -0
- package/dist/web/assets/workTarget-Cijqq4yH.js +1 -0
- package/dist/web/index.html +4 -5
- package/docs/architecture.md +70 -14
- package/docs/development.md +83 -7
- package/docs/how-to-use.md +105 -12
- package/docs/installation.md +157 -11
- package/docs/publishing.md +27 -3
- package/package.json +8 -5
- package/skills/p3/SKILL.md +2 -0
- package/src/cli/args.ts +9 -2
- package/src/cli/help.ts +10 -4
- package/src/cli/main.ts +73 -4
- package/src/cli/output.ts +18 -0
- package/src/cli/preflightCommands.ts +10 -2
- package/src/cli/project.ts +269 -98
- package/src/cli/releaseNotesCommands.ts +21 -1
- package/src/core/context.ts +3 -2
- package/src/core/preflight/codexEngine.ts +2 -1
- package/src/core/preflight/render-image/Dockerfile +3 -0
- package/src/core/preflight/render-image/fonts-ja.conf +28 -0
- package/src/core/preflight/render-image/render.mjs +10 -1
- package/src/core/preflight/render.ts +5 -2
- package/src/core/preflight/service.ts +19 -2
- package/src/core/projectRegistry.ts +264 -0
- package/src/core/releaseNotes/generate.ts +12 -0
- package/src/core/store/locate.ts +6 -6
- package/src/core/userConfig.ts +25 -0
- package/src/server/api/chatgptRoutes.ts +6 -5
- package/src/server/api/manifest.ts +9 -0
- package/src/server/api/projectsRoutes.ts +89 -0
- package/src/server/api/routes.ts +33 -25
- package/src/server/server.ts +74 -15
- package/src/shared/directTask.ts +20 -0
- package/src/shared/types.ts +1 -1
- package/dist/web/assets/TagInput-BICKVH2x.js +0 -1
- package/dist/web/assets/TaskDrawer-BkDIstIN.js +0 -3
- package/dist/web/assets/_requestId-B5O_ytaq.js +0 -1
- package/dist/web/assets/_requestId-C66puEMO.js +0 -30
- package/dist/web/assets/board-CbfDjkls.js +0 -1
- package/dist/web/assets/done-CPQbCFHg.js +0 -1
- package/dist/web/assets/draft-dT3gLDIt.js +0 -1
- package/dist/web/assets/index-BUcs2J6N.js +0 -12
- package/dist/web/assets/index-C3DkqwJ9.css +0 -2
- package/dist/web/assets/link-_s8ndNKS.js +0 -1
- package/dist/web/assets/new-T60RB7de.js +0 -1
- package/dist/web/assets/preload-helper-dXqN7N-I.js +0 -1
- package/dist/web/assets/release-notes-DxrPhDbt.js +0 -3
- package/dist/web/assets/requestData-D8ZiSZss.js +0 -1
- package/dist/web/assets/routes-D9ZxXoLk.js +0 -2
- package/dist/web/assets/settings-DsHVyqzJ.js +0 -1
- package/dist/web/assets/supersede-CLXlhCq0.js +0 -1
- package/dist/web/assets/ui-Cvke4y4X.js +0 -1
|
@@ -5,6 +5,15 @@
|
|
|
5
5
|
import { readFile } from "node:fs/promises";
|
|
6
6
|
import { chromium } from "playwright";
|
|
7
7
|
|
|
8
|
+
// フォントを指定していない原稿も、ゴシック体(sans-serif)で描く(Chromium の既定は Times New Roman で、欧文が明朝系になる)。
|
|
9
|
+
// 原稿の先頭(doctype の後)に置き、詳細度 0 にするので、原稿のどの指定よりも弱い
|
|
10
|
+
const BASE_STYLE = "<style>:where(html){font-family:sans-serif}</style>";
|
|
11
|
+
const DOCTYPE = /^\uFEFF?\s*(?:<!--[\s\S]*?-->\s*)*<!doctype[^>]*>/i;
|
|
12
|
+
const withBaseStyle = (html) => {
|
|
13
|
+
const m = DOCTYPE.exec(html);
|
|
14
|
+
return m ? m[0] + BASE_STYLE + html.slice(m[0].length) : BASE_STYLE + html;
|
|
15
|
+
};
|
|
16
|
+
|
|
8
17
|
const MAX_HEIGHT = Number(process.env.P3_RENDER_MAX_HEIGHT ?? 16384);
|
|
9
18
|
const PAGE_TIMEOUT = Number(process.env.P3_RENDER_PAGE_TIMEOUT ?? 20000);
|
|
10
19
|
|
|
@@ -31,7 +40,7 @@ try {
|
|
|
31
40
|
});
|
|
32
41
|
const page = await context.newPage();
|
|
33
42
|
page.setDefaultTimeout(PAGE_TIMEOUT);
|
|
34
|
-
await page.setContent(await readFile(`/in/${job.file}`, "utf8"), { waitUntil: "load", timeout: PAGE_TIMEOUT });
|
|
43
|
+
await page.setContent(withBaseStyle(await readFile(`/in/${job.file}`, "utf8")), { waitUntil: "load", timeout: PAGE_TIMEOUT });
|
|
35
44
|
const path = `/out/${job.id}.png`;
|
|
36
45
|
await page.screenshot({ path, fullPage: true, animations: "disabled", timeout: PAGE_TIMEOUT });
|
|
37
46
|
// 縦に長すぎるときは上から切る
|
|
@@ -104,10 +104,13 @@ export function checkHtml(html: string): string[] {
|
|
|
104
104
|
|
|
105
105
|
// --- イメージ ----------------------------------------------------------------
|
|
106
106
|
|
|
107
|
-
/**
|
|
107
|
+
/** イメージの資材(render-image/ の中。全部をイメージの名前の hash に入れる) */
|
|
108
|
+
export const RENDER_IMAGE_FILES = ["Dockerfile", "fonts-ja.conf", "render.mjs"] as const;
|
|
109
|
+
|
|
110
|
+
/** イメージの名前(資材の中身から決める。どれかが変われば別の名前になり、作り直す) */
|
|
108
111
|
export async function renderImageTag(dir = RENDER_IMAGE_DIR): Promise<string> {
|
|
109
112
|
const h = createHash("sha256");
|
|
110
|
-
for (const f of
|
|
113
|
+
for (const f of RENDER_IMAGE_FILES) h.update(await readFile(join(dir, f)));
|
|
111
114
|
return `infodb-p3-render:${h.digest("hex").slice(0, 12)}`;
|
|
112
115
|
}
|
|
113
116
|
|
|
@@ -31,6 +31,7 @@ import { extractXlsx, XlsxError } from "./xlsx.ts";
|
|
|
31
31
|
import { applyUiShortage, IMAGE_TYPES, loadUiMaterials, readUiImage, UI_DIR, UiMaterialError } from "./uiMaterials.ts";
|
|
32
32
|
import { compareInput, normalizeInput, renderRequestSnapshot, runInput, StaleInputError } from "./input.ts";
|
|
33
33
|
import { changedLabel } from "../../shared/preflightInput.ts";
|
|
34
|
+
import { PREFLIGHT_CANCELLED } from "../../shared/directTask.ts";
|
|
34
35
|
|
|
35
36
|
/** 始められない理由をそのまま失敗にするエンジン(run の記録とログに残すため) */
|
|
36
37
|
const failing = (name: PreflightEngine["name"], message: string): PreflightEngine => ({
|
|
@@ -39,6 +40,9 @@ const failing = (name: PreflightEngine["name"], message: string): PreflightEngin
|
|
|
39
40
|
run: async () => Promise.reject(new Error(message)),
|
|
40
41
|
});
|
|
41
42
|
|
|
43
|
+
/** 同じ要望の Preflight が実行中(エンジンを使えないのとは別) */
|
|
44
|
+
export class PreflightBusyError extends Error {}
|
|
45
|
+
|
|
42
46
|
/** タスク案の題が、編集を始めたあとに外で変わった(409 code: rev_conflict。current に今の案) */
|
|
43
47
|
export class DraftConflictError extends Error {
|
|
44
48
|
constructor(readonly current: ProposedTask) {
|
|
@@ -130,7 +134,7 @@ export class PreflightService {
|
|
|
130
134
|
const input = normalizeInput(current);
|
|
131
135
|
const request: Request = { ...current, ...input };
|
|
132
136
|
if ([...this.active.values()].some((a) => a.run.requestId === requestId)) {
|
|
133
|
-
throw new
|
|
137
|
+
throw new PreflightBusyError(`${requestId} の preflight は実行中です`);
|
|
134
138
|
}
|
|
135
139
|
// 既定のエンジンは始めるたびに個人設定から決める。読めなければ、この run を設定のエラーとして失敗にする
|
|
136
140
|
// (古い設定や Mock に落とさない。serve とほかの操作は続ける)
|
|
@@ -228,6 +232,18 @@ export class PreflightService {
|
|
|
228
232
|
this.active.get(runId)?.abort.abort();
|
|
229
233
|
}
|
|
230
234
|
|
|
235
|
+
/** 実行中の run の数 */
|
|
236
|
+
running(): number {
|
|
237
|
+
return this.active.size;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 実行中の run が全部終わるまで待つ(cancel: 先に全部を取り消す)。serve を止める・登録から外れたプロジェクトを閉じる前に */
|
|
241
|
+
async settle(opts: { cancel?: boolean } = {}): Promise<void> {
|
|
242
|
+
const jobs = [...this.active.values()];
|
|
243
|
+
if (opts.cancel) for (const j of jobs) j.abort.abort();
|
|
244
|
+
await Promise.allSettled(jobs.map((j) => j.done));
|
|
245
|
+
}
|
|
246
|
+
|
|
231
247
|
private log(run: PreflightRun, e: Omit<PreflightLogEntry, "at">) {
|
|
232
248
|
// トークンらしいもの(Codex のエラーが一部を見せるキーなど)は残さない
|
|
233
249
|
const entry = { ...e, text: redact(e.text), at: nowIso() };
|
|
@@ -292,7 +308,8 @@ export class PreflightService {
|
|
|
292
308
|
} catch (e) {
|
|
293
309
|
run.status = "failed";
|
|
294
310
|
run.ui = withCurrent({ status: "missing", reason: "評価が終わらなかったので、画面資料を取り込んでいません", targets: [], items: [], problems: [] }, run);
|
|
295
|
-
|
|
311
|
+
// 取消はエンジンによらず同じ言い方で残す(失敗とは分けて扱う。shared/directTask.ts)
|
|
312
|
+
run.error = signal.aborted ? PREFLIGHT_CANCELLED : redact((e as Error).message);
|
|
296
313
|
this.log(run, { kind: "error", text: run.error });
|
|
297
314
|
} finally {
|
|
298
315
|
run.finishedAt = nowIso();
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { realpath } from "node:fs/promises";
|
|
3
|
+
import type { ChatGptAccount } from "./chatgpt.ts";
|
|
4
|
+
import { openProject, type P3Context } from "./context.ts";
|
|
5
|
+
import type { SettingsSource } from "./machineSettings.ts";
|
|
6
|
+
import { inspectUserProjects, PROJECT_NAME, userConfigPath, type InvalidProjectEntry, type UserProject } from "./userConfig.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* プロジェクトを跨ぐ serve(p3 serve --all-projects)が扱うプロジェクト。個人設定に登録した名前だけを対象にし、
|
|
10
|
+
* 任意のパスは開かない。
|
|
11
|
+
*
|
|
12
|
+
* - 一覧は refresh(明示の再取得)で個人設定から読み直す。壊れた・読めない個人設定は登録0件と区別して configError に、
|
|
13
|
+
* 形の違う登録は invalid に理由を付けて出し、ほかの登録は使えるようにする
|
|
14
|
+
* - 開くのは使うとき(open)。同時に開こうとしたら1回にまとめ、失敗したら覚えずに次の open でやり直す(直したら戻る)
|
|
15
|
+
* - 同じデータのフォルダ(実体のパス)を複数の名前で登録していたら、どれも開かない(Preflight・生成を二重に動かさない)
|
|
16
|
+
* - 登録世代(generation): 読み直したときに登録が無くなっていた・データのフォルダが変わっていたら変わる(読み直すまでの間に
|
|
17
|
+
* 外して同じフォルダで付け直したものは同じ登録。書く先は同じ)。画面は変える操作に世代を添え、違えば断る(古い画面の保存を
|
|
18
|
+
* 新しい登録先へ流さない)。参照先のパスだけの変更は今の文脈に反映して世代は変えない
|
|
19
|
+
* - 登録から外れた文脈には新しい要求を渡さず、実行中の Preflight・生成が終わるのを待ってから閉じる(取り消さない)
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export type RegistryErrorCode = "unknown" | "changed" | "duplicate" | "unavailable";
|
|
23
|
+
|
|
24
|
+
/** 開けない(unknown: 登録に無い / changed: 登録世代が違う / duplicate: 同じデータを複数の名前で登録 / unavailable: 開けない) */
|
|
25
|
+
export class RegistryError extends Error {
|
|
26
|
+
constructor(
|
|
27
|
+
readonly code: RegistryErrorCode,
|
|
28
|
+
message: string,
|
|
29
|
+
) {
|
|
30
|
+
super(message);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ProjectListItem {
|
|
35
|
+
name: string;
|
|
36
|
+
generation: string;
|
|
37
|
+
/** ok: 開ける(開いていなくてもよい) / error: 開けない(理由は error) */
|
|
38
|
+
state: "ok" | "error";
|
|
39
|
+
error?: string;
|
|
40
|
+
/** 文脈を開いている */
|
|
41
|
+
open: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ProjectListing {
|
|
45
|
+
projects: ProjectListItem[];
|
|
46
|
+
invalid: InvalidProjectEntry[];
|
|
47
|
+
/** 個人設定を読めない・壊れている(登録0件とは別) */
|
|
48
|
+
configError?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface Entry {
|
|
52
|
+
name: string;
|
|
53
|
+
dir: string;
|
|
54
|
+
repos: Record<string, string>;
|
|
55
|
+
generation: string;
|
|
56
|
+
/** 同じデータを別の名前でも登録している */
|
|
57
|
+
duplicate?: string;
|
|
58
|
+
ctx?: Promise<P3Context>;
|
|
59
|
+
/** 直前に開けなかった理由(次の open でやり直す) */
|
|
60
|
+
error?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface RegistryOptions {
|
|
64
|
+
settings: SettingsSource;
|
|
65
|
+
/** サインインの待ち受け(全プロジェクトで1つ) */
|
|
66
|
+
chatgpt: ChatGptAccount;
|
|
67
|
+
configPath?: string;
|
|
68
|
+
/** 開き方(テストで差し替える) */
|
|
69
|
+
open?: typeof openProject;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class ProjectRegistry {
|
|
73
|
+
private entries = new Map<string, Entry>();
|
|
74
|
+
private invalid: InvalidProjectEntry[] = [];
|
|
75
|
+
private configError?: string;
|
|
76
|
+
private counter = 0;
|
|
77
|
+
private refreshing: Promise<ProjectListing> = Promise.resolve({ projects: [], invalid: [] });
|
|
78
|
+
/** 登録から外れて、実行中の処理が終わるのを待っている文脈 */
|
|
79
|
+
private retiring = new Set<Promise<void>>();
|
|
80
|
+
private listeners = new Set<(kind: "projects" | "user" | "chatgpt") => void>();
|
|
81
|
+
private closed = false;
|
|
82
|
+
|
|
83
|
+
constructor(private opts: RegistryOptions) {}
|
|
84
|
+
|
|
85
|
+
get chatgpt(): ChatGptAccount {
|
|
86
|
+
return this.opts.chatgpt;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 個人設定から一覧を読み直す(同時に呼ばれたら順に) */
|
|
90
|
+
refresh(): Promise<ProjectListing> {
|
|
91
|
+
this.refreshing = this.refreshing.then(
|
|
92
|
+
() => this.load(),
|
|
93
|
+
() => this.load(),
|
|
94
|
+
);
|
|
95
|
+
return this.refreshing;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
list(): ProjectListing {
|
|
99
|
+
const projects = [...this.entries.values()]
|
|
100
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
101
|
+
.map((e): ProjectListItem => {
|
|
102
|
+
const error = e.duplicate ?? e.error;
|
|
103
|
+
return { name: e.name, generation: e.generation, state: error ? "error" : "ok", ...(error ? { error } : {}), open: !!e.ctx };
|
|
104
|
+
});
|
|
105
|
+
return { projects, invalid: this.invalid, ...(this.configError ? { configError: this.configError } : {}) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 登録した名前の文脈(必要なら開く)。generation を渡したら、今の登録世代と同じときだけ */
|
|
109
|
+
async open(name: string, generation?: string): Promise<P3Context> {
|
|
110
|
+
if (this.closed) throw new RegistryError("unavailable", "serve を止めています");
|
|
111
|
+
const e = PROJECT_NAME.test(name) ? this.entries.get(name) : undefined;
|
|
112
|
+
if (!e) throw new RegistryError("unknown", `プロジェクト「${name}」は個人設定に登録されていません(p3 project ls で確かめ、画面の一覧を読み直してください)`);
|
|
113
|
+
if (generation !== undefined && generation !== e.generation) {
|
|
114
|
+
throw new RegistryError("changed", `プロジェクト「${name}」の登録が変わりました(外した・付け直した・データのフォルダを変えた)。一覧を読み直して選び直してください(入力は送っていません)`);
|
|
115
|
+
}
|
|
116
|
+
if (e.duplicate) throw new RegistryError("duplicate", e.duplicate);
|
|
117
|
+
if (!e.ctx) {
|
|
118
|
+
e.ctx = (this.opts.open ?? openProject)(e.dir, { repos: e.repos, settings: this.opts.settings, projectName: e.name, chatgpt: this.opts.chatgpt });
|
|
119
|
+
e.ctx.then(
|
|
120
|
+
(ctx) => {
|
|
121
|
+
e.error = undefined;
|
|
122
|
+
void ctx.ws.watch();
|
|
123
|
+
// 開いている間に登録から外れた・変わった: 新しい要求には使わせず閉じる
|
|
124
|
+
if (this.entries.get(name) !== e || this.closed) this.retire(ctx);
|
|
125
|
+
},
|
|
126
|
+
(err: Error) => {
|
|
127
|
+
// 覚えずに次の open でやり直す(フォルダを戻した・共有ドライブをつないだら使える)
|
|
128
|
+
if (this.entries.get(name) === e) {
|
|
129
|
+
e.ctx = undefined;
|
|
130
|
+
e.error = err.message;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const ctx = await e.ctx;
|
|
137
|
+
if (this.entries.get(name) !== e) throw new RegistryError("changed", `プロジェクト「${name}」の登録が変わりました。一覧を読み直して選び直してください`);
|
|
138
|
+
return ctx;
|
|
139
|
+
} catch (err) {
|
|
140
|
+
if (err instanceof RegistryError) throw err;
|
|
141
|
+
throw new RegistryError("unavailable", `プロジェクト「${name}」を開けません: ${(err as Error).message}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 開いている文脈(変更の知らせを全部へ流すため) */
|
|
146
|
+
async openContexts(): Promise<P3Context[]> {
|
|
147
|
+
const opened = await Promise.allSettled([...this.entries.values()].flatMap((e) => (e.ctx ? [e.ctx] : [])));
|
|
148
|
+
return opened.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** プロジェクトに属さない変更(一覧・テーマ・ChatGPT の接続)を知らせる。開いている全プロジェクトの画面にも流す */
|
|
152
|
+
notify(kind: "projects" | "user" | "chatgpt") {
|
|
153
|
+
for (const l of this.listeners) l(kind);
|
|
154
|
+
if (kind === "projects") return;
|
|
155
|
+
void this.openContexts().then((all) => all.forEach((ctx) => ctx.ws.emit({ type: "changed", kind })));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
on(listener: (kind: "projects" | "user" | "chatgpt") => void): () => void {
|
|
159
|
+
this.listeners.add(listener);
|
|
160
|
+
return () => this.listeners.delete(listener);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 止める。新しい要求は断り、実行中の Preflight・生成を取り消して終わるまで待つ(timeoutMs まで)。監視を外す。
|
|
165
|
+
* 待ちきれなかった数を返す
|
|
166
|
+
*/
|
|
167
|
+
async close(opts: { timeoutMs?: number } = {}): Promise<{ pending: number }> {
|
|
168
|
+
this.closed = true;
|
|
169
|
+
const all = await this.openContexts();
|
|
170
|
+
for (const e of this.entries.values()) e.ctx = undefined;
|
|
171
|
+
const settle = Promise.all([
|
|
172
|
+
...all.map(async (ctx) => {
|
|
173
|
+
await Promise.all([ctx.preflight.settle({ cancel: true }), ctx.releaseGenerator.settle({ cancel: true })]);
|
|
174
|
+
ctx.ws.close();
|
|
175
|
+
}),
|
|
176
|
+
...this.retiring,
|
|
177
|
+
]).then(() => false);
|
|
178
|
+
const timedOut = await Promise.race([settle, new Promise<boolean>((r) => setTimeout(() => r(true), opts.timeoutMs ?? 10_000).unref())]);
|
|
179
|
+
for (const ctx of all) ctx.ws.close();
|
|
180
|
+
return { pending: timedOut ? all.reduce((n, c) => n + c.preflight.running() + c.releaseGenerator.running(), 0) : 0 };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private async load(): Promise<ProjectListing> {
|
|
184
|
+
let projects: Record<string, UserProject>;
|
|
185
|
+
try {
|
|
186
|
+
const r = await inspectUserProjects(this.opts.configPath ?? userConfigPath());
|
|
187
|
+
projects = r.projects;
|
|
188
|
+
this.invalid = r.invalid;
|
|
189
|
+
this.configError = undefined;
|
|
190
|
+
} catch (e) {
|
|
191
|
+
// 読めない・壊れている: 今の一覧と開いている文脈はそのまま(直して読み直せば戻る)
|
|
192
|
+
this.configError = (e as Error).message;
|
|
193
|
+
return this.list();
|
|
194
|
+
}
|
|
195
|
+
const before = this.list();
|
|
196
|
+
for (const [name, e] of this.entries) {
|
|
197
|
+
const next = projects[name];
|
|
198
|
+
if (!next || next.dir !== e.dir) this.drop(name, e);
|
|
199
|
+
}
|
|
200
|
+
for (const [name, p] of Object.entries(projects)) {
|
|
201
|
+
const cur = this.entries.get(name);
|
|
202
|
+
if (cur) {
|
|
203
|
+
// 参照先のパスだけの変更は今の文脈に反映する(次の Preflight から使う)
|
|
204
|
+
if (JSON.stringify(cur.repos) !== JSON.stringify(p.repos)) {
|
|
205
|
+
const old = cur.repos;
|
|
206
|
+
cur.repos = { ...p.repos };
|
|
207
|
+
void cur.ctx?.then((ctx) => {
|
|
208
|
+
for (const k of Object.keys(old)) if (!(k in p.repos)) ctx.ws.setLocalRepo(k, null);
|
|
209
|
+
for (const [k, v] of Object.entries(p.repos)) if (old[k] !== v) ctx.ws.setLocalRepo(k, v);
|
|
210
|
+
}, () => undefined);
|
|
211
|
+
}
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
this.entries.set(name, { name, dir: p.dir, repos: { ...p.repos }, generation: this.nextGeneration(p.dir) });
|
|
215
|
+
}
|
|
216
|
+
await this.markDuplicates();
|
|
217
|
+
const after = this.list();
|
|
218
|
+
if (JSON.stringify(before) !== JSON.stringify(after)) this.notify("projects");
|
|
219
|
+
return after;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 登録から外す。新しい要求には使わせず、実行中の処理が終わってから閉じる */
|
|
223
|
+
private drop(name: string, e: Entry) {
|
|
224
|
+
this.entries.delete(name);
|
|
225
|
+
void e.ctx?.then((ctx) => this.retire(ctx), () => undefined);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private retire(ctx: P3Context) {
|
|
229
|
+
const p = Promise.all([ctx.preflight.settle(), ctx.releaseGenerator.settle()]).then(() => ctx.ws.close());
|
|
230
|
+
this.retiring.add(p);
|
|
231
|
+
void p.finally(() => this.retiring.delete(p));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 同じ実体のフォルダを指す登録は、どれも開かない(どれを使うかは人が個人設定で決める) */
|
|
235
|
+
private async markDuplicates() {
|
|
236
|
+
const real = new Map<string, string[]>();
|
|
237
|
+
for (const e of this.entries.values()) {
|
|
238
|
+
const key = await realpath(e.dir).catch(() => e.dir);
|
|
239
|
+
real.set(key, [...(real.get(key) ?? []), e.name]);
|
|
240
|
+
}
|
|
241
|
+
for (const names of real.values()) {
|
|
242
|
+
for (const name of names) {
|
|
243
|
+
const e = this.entries.get(name)!;
|
|
244
|
+
const was = e.duplicate;
|
|
245
|
+
e.duplicate =
|
|
246
|
+
names.length > 1
|
|
247
|
+
? `同じデータのフォルダを複数の名前で登録しています: ${names.join(", ")}(二重に動かさないため、どれも開きません。p3 project rm <名前> で1つにしてください)`
|
|
248
|
+
: undefined;
|
|
249
|
+
// 重なりを外して開けるようになったら、別の登録として世代を変える
|
|
250
|
+
if (was && !e.duplicate) e.generation = this.nextGeneration(e.dir);
|
|
251
|
+
if (!was && e.duplicate && e.ctx) {
|
|
252
|
+
const ctx = e.ctx;
|
|
253
|
+
e.ctx = undefined;
|
|
254
|
+
void ctx.then((c) => this.retire(c), () => undefined);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private nextGeneration(dir: string): string {
|
|
261
|
+
this.counter += 1;
|
|
262
|
+
return `${createHash("sha256").update(dir).digest("hex").slice(0, 8)}-${this.counter}`;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
@@ -117,6 +117,18 @@ export class ReleaseGenerator {
|
|
|
117
117
|
return true;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/** 実行中の生成の数 */
|
|
121
|
+
running(): number {
|
|
122
|
+
return [...this.jobs.values()].filter((j) => j.status === "running").length;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 実行中の生成が全部終わるまで待つ(cancel: 先に全部を取り消す) */
|
|
126
|
+
async settle(opts: { cancel?: boolean } = {}): Promise<void> {
|
|
127
|
+
const ids = [...this.jobs.values()].filter((j) => j.status === "running").map((j) => j.id);
|
|
128
|
+
if (opts.cancel) for (const id of ids) this.cancel(id);
|
|
129
|
+
await Promise.allSettled(ids.flatMap((id) => this.done.get(id) ?? []));
|
|
130
|
+
}
|
|
131
|
+
|
|
120
132
|
private emit(j: ReleaseGeneration) {
|
|
121
133
|
this.ws.emit({ type: "release-generation", id: j.id, milestone: j.milestone, status: j.status });
|
|
122
134
|
}
|
package/src/core/store/locate.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { stat } from "node:fs/promises";
|
|
|
4
4
|
import { dirname, join, resolve, sep } from "node:path";
|
|
5
5
|
import type { UserConfig } from "../userConfig.ts";
|
|
6
6
|
|
|
7
|
-
/**
|
|
7
|
+
/** p3 init がデータを置く既定のフォルダ名(リポジトリのルートの直下) */
|
|
8
8
|
export const DATA_DIR_NAME = ".p3";
|
|
9
9
|
|
|
10
10
|
export interface ResolvedProject {
|
|
@@ -64,7 +64,7 @@ export async function checkDataDir(dataDir: string, projectName?: string): Promi
|
|
|
64
64
|
projectName
|
|
65
65
|
? ` 登録の場所を直すとき: p3 project ls で確かめ、p3 project rm ${name} → p3 project add ${name} <正しいフォルダ>(rm はデータを消さない)`
|
|
66
66
|
: " --dir で指すときは、project.yaml のあるフォルダを指す",
|
|
67
|
-
` 新しく作るなら: 管理したいリポジトリの中で p3 init --project ${name} --dir
|
|
67
|
+
` 新しく作るなら: 管理したいリポジトリの中で p3 init --project ${name} --dir <フォルダ>(ほかの人が作ったものに参加するなら p3 join)`,
|
|
68
68
|
]
|
|
69
69
|
.filter(Boolean)
|
|
70
70
|
.join("\n"),
|
|
@@ -93,7 +93,7 @@ export function onlyRegistrationNotice(p: ResolvedProject, write: boolean): stri
|
|
|
93
93
|
* 1. --dir <フォルダ> データのフォルダを直接指す
|
|
94
94
|
* 2. --project <名前> 個人設定に登録したプロジェクト
|
|
95
95
|
* 3. 今いる場所 登録したプロジェクトのデータのフォルダか、そのリポジトリ(作業ツリーを含む)の中
|
|
96
|
-
* 4. リポジトリの中の .p3/
|
|
96
|
+
* 4. リポジトリの中の .p3/ 個人設定に登録していないとき(git のメインの作業ツリー → 上へ辿る。デモ・登録前の clone など)
|
|
97
97
|
* 5. 登録が1つだけ それを使う
|
|
98
98
|
*/
|
|
99
99
|
export function resolveProject(o: { cwd: string; dir?: string; project?: string; user: UserConfig }): ResolvedProject {
|
|
@@ -135,13 +135,13 @@ export function resolveProject(o: { cwd: string; dir?: string; project?: string;
|
|
|
135
135
|
throw new ProjectNotResolvedError(
|
|
136
136
|
entries.length
|
|
137
137
|
? `操作するプロジェクトが決まりません(今いる場所: ${o.cwd})。\n${listing(o.user)}`
|
|
138
|
-
: "
|
|
138
|
+
: "プロジェクトがまだありません。管理したいリポジトリの中で次のどちらかを実行してください:\n 新しく作る: p3 init --project <名前>(データはリポジトリのルートの .p3。外に置くなら --dir <フォルダ>)\n 共有されたものに参加する: p3 join --project <名前>(ルートの .p3 に無ければ --dir <データのフォルダ>)",
|
|
139
139
|
);
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
function listing(user: UserConfig): string {
|
|
143
143
|
const entries = Object.entries(user.projects);
|
|
144
|
-
if (!entries.length) return " (登録済みのプロジェクトはありません。p3 init
|
|
144
|
+
if (!entries.length) return " (登録済みのプロジェクトはありません。p3 init で作るか、p3 join で参加してください)";
|
|
145
145
|
const w = Math.max(...entries.map(([n]) => n.length));
|
|
146
146
|
return [
|
|
147
147
|
" 登録済みのプロジェクト:",
|
|
@@ -153,7 +153,7 @@ function listing(user: UserConfig): string {
|
|
|
153
153
|
const inside = (path: string, dir: string) => path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep);
|
|
154
154
|
|
|
155
155
|
/**
|
|
156
|
-
* リポジトリの中の .p3/
|
|
156
|
+
* リポジトリの中の .p3/ を探す(個人設定に登録していないとき。登録していれば 3. の今いる場所で決まる)。
|
|
157
157
|
* 要望ごとの作業ツリーの中で実行しても、git のメインの作業ツリーの .p3/ を使う(各作業ツリーの .p3/ はブランチ時点の写し)。
|
|
158
158
|
*/
|
|
159
159
|
export function findDataDir(cwd: string): string | undefined {
|
package/src/core/userConfig.ts
CHANGED
|
@@ -108,6 +108,31 @@ export async function loadUserSettings(path = userConfigPath()): Promise<Pick<Us
|
|
|
108
108
|
return { settings };
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
/** 一覧に入れられなかった登録(名前の形・dir が無いなど)。normalizeUserConfig は黙って外すので、プロジェクトを跨ぐ serve の一覧で知らせる */
|
|
112
|
+
export interface InvalidProjectEntry {
|
|
113
|
+
name: string;
|
|
114
|
+
reason: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* プロジェクトを跨ぐ serve のために、個人設定の projects を診断つきで読む。読めない・壊れた YAML は UserConfigError
|
|
119
|
+
* (登録0件とは区別する)。projects の形が違う・名前や dir が不正な登録は invalid に理由を付けて返し、ほかの登録は使えるようにする
|
|
120
|
+
*/
|
|
121
|
+
export async function inspectUserProjects(path = userConfigPath()): Promise<{ projects: Record<string, UserProject>; invalid: InvalidProjectEntry[] }> {
|
|
122
|
+
const d = asRecord(parse(await readText(path), path).toJS());
|
|
123
|
+
const invalid: InvalidProjectEntry[] = [];
|
|
124
|
+
if (d.projects !== undefined && d.projects !== null && (typeof d.projects !== "object" || Array.isArray(d.projects))) {
|
|
125
|
+
throw new UserConfigError(`個人設定の projects の形が違います: ${path}(「名前: { dir: フォルダ }」の対応で書いてください)`);
|
|
126
|
+
}
|
|
127
|
+
for (const [name, v] of Object.entries(asRecord(d.projects))) {
|
|
128
|
+
const p = typeof v === "string" ? { dir: v } : v;
|
|
129
|
+
if (!PROJECT_NAME.test(name)) invalid.push({ name, reason: "名前に使えない文字があります(英数字で始まり、英数字と . _ -)" });
|
|
130
|
+
else if (!p || typeof p !== "object" || Array.isArray(p)) invalid.push({ name, reason: "登録の形が違います(dir: <データのフォルダ>)" });
|
|
131
|
+
else if (typeof (p as Record<string, unknown>).dir !== "string" || !(p as Record<string, unknown>).dir) invalid.push({ name, reason: "dir(データのフォルダ)がありません" });
|
|
132
|
+
}
|
|
133
|
+
return { projects: normalizeUserConfig(d).projects, invalid };
|
|
134
|
+
}
|
|
135
|
+
|
|
111
136
|
const asRecord = (v: unknown): Record<string, unknown> => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
|
|
112
137
|
|
|
113
138
|
/**
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
import { Hono } from "hono";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import type { ChatGptAccount } from "../../core/chatgpt.ts";
|
|
4
|
-
import type {
|
|
5
|
-
import type { Workspace } from "../../core/store/workspace.ts";
|
|
4
|
+
import type { EngineStatus } from "../../core/preflight/engine.ts";
|
|
6
5
|
import { localOnly } from "./local.ts";
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* /api/chatgpt。サインインの待ち受けは serve のプロセスが行う(同時に1つ。ページを読み直しても待っている試行を返す)。
|
|
10
9
|
* 返すのは状態だけで、トークンは返さない。
|
|
10
|
+
* changed: 接続が変わったことを画面へ知らせる(プロジェクトを跨ぐ serve では開いている全プロジェクトへ)。
|
|
11
|
+
* engine: Preflight のエンジンの状態(プロジェクトごと。プロジェクトを選んでいない入口では無い)
|
|
11
12
|
*/
|
|
12
|
-
export function chatgptRoutes(account: ChatGptAccount,
|
|
13
|
+
export function chatgptRoutes(account: ChatGptAccount, opts: { changed: () => void; engine?: () => Promise<EngineStatus> }) {
|
|
13
14
|
const app = new Hono();
|
|
14
|
-
const changed =
|
|
15
|
+
const changed = opts.changed;
|
|
15
16
|
app.use("*", async (c, next) => {
|
|
16
17
|
const why = localOnly(c, c.req.method !== "GET");
|
|
17
18
|
if (why) return c.json({ error: why }, 403);
|
|
18
19
|
await next();
|
|
19
20
|
});
|
|
20
21
|
|
|
21
|
-
app.get("/", async (c) => c.json({ ...(await account.status()), engine: await
|
|
22
|
+
app.get("/", async (c) => c.json({ ...(await account.status()), engine: opts.engine ? await opts.engine() : null }));
|
|
22
23
|
|
|
23
24
|
app.post("/login", async (c) => {
|
|
24
25
|
const attempt = await account.startLogin();
|
|
@@ -16,6 +16,15 @@ export const AI_MANIFEST = {
|
|
|
16
16
|
},
|
|
17
17
|
relationTypes: RELATION_TYPES, // タスクの関係は depends_on と supersedes だけ(Preflight のタスク化が張る。手で張る API は無い)
|
|
18
18
|
endpoints: [
|
|
19
|
+
{ method: "GET", path: "/api/mode", desc: "serve の形 {mode: single(project: 名前)| all-projects}" },
|
|
20
|
+
{
|
|
21
|
+
method: "GET",
|
|
22
|
+
path: "/api/projects",
|
|
23
|
+
desc:
|
|
24
|
+
"(all-projects だけ)個人設定を読み直した一覧 {projects: [{name, generation(登録世代), state: ok|error, error?, open}], invalid: [{name, reason}], configError?}。" +
|
|
25
|
+
"ここに無い API は /api/projects/:project/... の下に置く(通常の serve の /api/... と同じ)。変える操作には x-p3-project-generation が要る(無ければ 428、違えば 409 code: changed)。" +
|
|
26
|
+
"プロジェクトを書かないデータの API は 404 code: project_required。/api/chatgpt(engine は null)・/api/user-theme・/api/events(一覧・テーマ・接続の変更)はプロジェクトを選ばずに使える",
|
|
27
|
+
},
|
|
19
28
|
{ method: "GET", path: "/api/project", desc: "プロジェクト設定" },
|
|
20
29
|
{
|
|
21
30
|
method: "POST",
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Hono, type Context } from "hono";
|
|
2
|
+
import type { P3Context } from "../../core/context.ts";
|
|
3
|
+
import { ProjectRegistry, RegistryError } from "../../core/projectRegistry.ts";
|
|
4
|
+
import { PROJECT_NAME } from "../../core/userConfig.ts";
|
|
5
|
+
import { chatgptRoutes } from "./chatgptRoutes.ts";
|
|
6
|
+
import { apiRoutes, eventStream } from "./routes.ts";
|
|
7
|
+
import { userThemeRoutes, userThemeScriptRoute } from "./userThemeRoutes.ts";
|
|
8
|
+
import { AI_MANIFEST } from "./manifest.ts";
|
|
9
|
+
|
|
10
|
+
/** 変える操作に添える登録世代のヘッダー(GET でも添えれば、違うときは断る) */
|
|
11
|
+
export const GENERATION_HEADER = "x-p3-project-generation";
|
|
12
|
+
|
|
13
|
+
const STATUS: Record<RegistryError["code"], 404 | 409 | 503> = { unknown: 404, changed: 409, duplicate: 409, unavailable: 503 };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* プロジェクトを跨ぐ serve の API(/api の下)。個人設定に登録した名前だけを扱う。
|
|
17
|
+
*
|
|
18
|
+
* GET /mode { mode: "all-projects" }
|
|
19
|
+
* GET /projects 個人設定を読み直した一覧(登録世代・開けない理由・形の違う登録・個人設定の読めない理由)
|
|
20
|
+
* * /projects/:project/... そのプロジェクトの API(通常の serve の /api/... と同じ)。変える操作には登録世代のヘッダーが要る
|
|
21
|
+
* GET /events 一覧・テーマ・ChatGPT の接続の変更の知らせ(プロジェクトを選んでいない画面のため)
|
|
22
|
+
* /chatgpt・/user-theme・/user-theme.js・/ai/manifest プロジェクトを選ばなくても使える(ローカルだけの操作は今までどおり)
|
|
23
|
+
*
|
|
24
|
+
* プロジェクトを書かないデータの API(/api/requests など)は 404(code: project_required)で断る。
|
|
25
|
+
*/
|
|
26
|
+
export function projectsRoutes(registry: ProjectRegistry) {
|
|
27
|
+
const app = new Hono();
|
|
28
|
+
/** 文脈ごとの API(文脈を閉じたら消える) */
|
|
29
|
+
const routes = new WeakMap<P3Context, Hono>();
|
|
30
|
+
const routesOf = (ctx: P3Context) => {
|
|
31
|
+
let r = routes.get(ctx);
|
|
32
|
+
if (!r) {
|
|
33
|
+
r = new Hono();
|
|
34
|
+
r.route("/", apiRoutes(ctx, { notify: (kind) => registry.notify(kind) }));
|
|
35
|
+
// 無い API は 404 の JSON(画面の index.html に流さない)
|
|
36
|
+
r.all("*", (c) => c.json({ error: `API がありません: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
|
|
37
|
+
routes.set(ctx, r);
|
|
38
|
+
}
|
|
39
|
+
return r;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
app.get("/mode", (c) => c.json({ mode: "all-projects" }));
|
|
43
|
+
app.get("/projects", async (c) => {
|
|
44
|
+
c.header("cache-control", "no-store");
|
|
45
|
+
return c.json(await registry.refresh());
|
|
46
|
+
});
|
|
47
|
+
app.get("/events", (c) => eventStream(c, (push) => registry.on((kind) => push({ type: "changed", kind }))));
|
|
48
|
+
app.route("/chatgpt", chatgptRoutes(registry.chatgpt, { changed: () => registry.notify("chatgpt") }));
|
|
49
|
+
app.route("/user-theme", userThemeRoutes(() => registry.notify("user")));
|
|
50
|
+
app.route("/user-theme.js", userThemeScriptRoute());
|
|
51
|
+
app.get("/ai/manifest", (c) => c.json(AI_MANIFEST));
|
|
52
|
+
|
|
53
|
+
app.all("/projects/:project/*", async (c) => {
|
|
54
|
+
const name = c.req.param("project");
|
|
55
|
+
if (!PROJECT_NAME.test(name)) return c.json({ error: `プロジェクトの名前が正しくありません: ${name}`, code: "unknown" }, 404);
|
|
56
|
+
const generation = c.req.header(GENERATION_HEADER);
|
|
57
|
+
const mutating = c.req.method !== "GET" && c.req.method !== "HEAD";
|
|
58
|
+
if (mutating && !generation) {
|
|
59
|
+
return c.json({ error: `変える操作には登録世代(${GENERATION_HEADER})が要ります。一覧(GET /api/projects)を読んでから送ってください`, code: "generation_required" }, 428);
|
|
60
|
+
}
|
|
61
|
+
let ctx: P3Context;
|
|
62
|
+
try {
|
|
63
|
+
ctx = await registry.open(name, generation);
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (e instanceof RegistryError) return c.json({ error: e.message, code: e.code }, STATUS[e.code]);
|
|
66
|
+
throw e;
|
|
67
|
+
}
|
|
68
|
+
return forward(c, routesOf(ctx), `/projects/${name}`);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// プロジェクトを書かないデータの API は、どのプロジェクトか分からないので断る
|
|
72
|
+
app.all("*", (c) =>
|
|
73
|
+
c.json({ error: "プロジェクトを跨ぐ serve では、/api/projects/<名前>/... で対象のプロジェクトを指定してください", code: "project_required" }, 404),
|
|
74
|
+
);
|
|
75
|
+
return app;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** /api/projects/<名前> を外して、そのプロジェクトの API へ渡す(接続元の情報 c.env はそのまま。ローカルだけの操作の確かめに使う) */
|
|
79
|
+
async function forward(c: Context, target: Hono, prefix: string) {
|
|
80
|
+
const url = new URL(c.req.url);
|
|
81
|
+
const at = url.pathname.indexOf(prefix);
|
|
82
|
+
url.pathname = url.pathname.slice(at + prefix.length) || "/";
|
|
83
|
+
const raw = c.req.raw;
|
|
84
|
+
const body = raw.method === "GET" || raw.method === "HEAD" ? undefined : raw.body;
|
|
85
|
+
// 本文は流れのまま渡す(Node の fetch は流れの本文に duplex: "half" が要る。型の RequestInit には無い)
|
|
86
|
+
const init: RequestInit & { duplex?: "half" } = { method: raw.method, headers: raw.headers, body, signal: raw.signal, ...(body ? { duplex: "half" } : {}) };
|
|
87
|
+
const req = new Request(url, init);
|
|
88
|
+
return target.fetch(req, c.env);
|
|
89
|
+
}
|