@dotlabo/agent-chat-relay 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ import type { ExtensionFactory } from "@earendil-works/pi-coding-agent"
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js"
3
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
4
+ import { approvePiToolCall } from "../../harness/pi/tool-approval.ts"
5
+ import { managedRead } from "./managed-read.ts"
6
+
7
+ const required = ["reply", "fetch_messages", "download_attachment", "list_rooms"]
8
+ const chatTools = new Set([...required, "react", "edit_message", "create_thread"])
9
+ const builtinTools = ["read", "write", "edit", "bash"]
10
+ export const managedToolSelection = [...builtinTools, ...[...chatTools].map(name => `mcp__chat__${name}`)]
11
+ export const managedExtensionName = "relay-managed-chat"
12
+
13
+ export function managedChat({ url, authorization }: { url: string; authorization: string }, workspace: string, stateDir: string): ExtensionFactory {
14
+ return async (pi) => {
15
+ const client = new Client({ name: "agent-chat-relay-pi", version: "1" })
16
+ const transport = new StreamableHTTPClientTransport(new URL(url), {
17
+ requestInit: { headers: { Authorization: authorization } },
18
+ fetch: (resource, options) => fetch(resource, { ...options, redirect: "error" }),
19
+ })
20
+ const session = new AbortController()
21
+ const registered = new Set<string>()
22
+ let ready = false
23
+ const read = managedRead(workspace, stateDir, session.signal)
24
+ pi.registerTool(read)
25
+ const owns = (name: string) => pi.getAllTools().some(tool =>
26
+ tool.name === name && tool.sourceInfo.path === `<inline:${managedExtensionName}>`)
27
+ pi.on("tool_call", (event, ctx) => {
28
+ if (!ready) return { block: true, reason: "チャット用ツールの準備ができていません" }
29
+ // 継承した拡張が同名でも、承認を省くのは中継が登録したツールだけ。
30
+ if (event.toolName === read.name || registered.has(event.toolName)) {
31
+ if (owns(event.toolName)) return
32
+ return { block: true, reason: "中継のツールを確認できません" }
33
+ }
34
+ return approvePiToolCall(event, ctx, { sessionSignal: session.signal })
35
+ })
36
+ try {
37
+ await client.connect(transport, { timeout: 2500 })
38
+ if (client.getServerVersion()?.name !== "chat") throw new Error()
39
+ const { tools, nextCursor } = await client.listTools(undefined, { timeout: 2500 })
40
+ // 中継が提供するチャット用ツールの 1 ページだけを受け付ける。
41
+ const names = new Set(tools.map(tool => tool.name))
42
+ if (nextCursor || names.size !== tools.length || !required.every(name => names.has(name)) || tools.some(tool => !chatTools.has(tool.name))) {
43
+ throw new Error()
44
+ }
45
+ for (const tool of tools) {
46
+ const name = `mcp__chat__${tool.name}`
47
+ pi.registerTool({
48
+ name,
49
+ label: tool.name,
50
+ description: tool.description ?? tool.name,
51
+ parameters: tool.inputSchema,
52
+ async execute(_id, args, signal) {
53
+ if (!ready) throw new Error("チャット用ツールの準備ができていません")
54
+ try {
55
+ const result = await client.callTool({ name: tool.name, arguments: { ...args } }, undefined, { timeout: 5000, signal })
56
+ if (result.isError || !Array.isArray(result.content)) throw new Error()
57
+ const content = result.content.map(item => {
58
+ if (item.type !== "text") throw new Error()
59
+ return { type: "text" as const, text: item.text }
60
+ })
61
+ return { content, details: {} }
62
+ } catch {
63
+ // ヘッダー等を含み得る例外は RPC やモデルへ送らない。
64
+ throw new Error("チャット用ツールの MCP 呼び出しに失敗しました")
65
+ }
66
+ },
67
+ })
68
+ registered.add(name)
69
+ }
70
+ pi.on("session_start", (_event, ctx) => {
71
+ const expected = [...builtinTools, ...registered]
72
+ const active = new Set(pi.getActiveTools())
73
+ ready = owns(read.name) && [...registered].every(owns) && active.size === expected.length && expected.every(name => active.has(name))
74
+ ctx.ui.notify(ready ? "managed-chat:ready" : "managed-chat:failed", ready ? "info" : "error")
75
+ })
76
+ pi.on("session_shutdown", async () => {
77
+ ready = false
78
+ session.abort()
79
+ await client.close().catch(() => {})
80
+ })
81
+ } catch {
82
+ await client.close().catch(() => {})
83
+ throw new Error("チャット用ツールの MCP 初期化に失敗しました")
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,99 @@
1
+ // pi CLI を通さず、明示した中継専用のサービスで SDK の RPC を動かす。
2
+ import { readFileSync, realpathSync, statSync } from "node:fs"
3
+ import { isAbsolute, join, relative, sep } from "node:path"
4
+ import {
5
+ createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices,
6
+ ModelRuntime, runRpcMode, SessionManager, SettingsManager,
7
+ } from "@earendil-works/pi-coding-agent"
8
+ import { z } from "zod"
9
+ import { managedChat, managedExtensionName, managedToolSelection } from "./managed-extension.ts"
10
+
11
+ const chatInput = z.object({
12
+ url: z.string().regex(/^http:\/\/127\.0\.0\.1:[0-9]+\/mcp$/),
13
+ authorization: z.string().regex(/^Bearer [A-Za-z0-9_-]{43}$/),
14
+ })
15
+ const modelSettings = z.object({ defaultProvider: z.string().min(1), defaultModel: z.string().min(1) })
16
+ const relayPrompt = "あなたはチャット中継を通じて会話するアシスタントです。ルームへの返事には mcp__chat__reply を使います。"
17
+
18
+ function inside(parent: string, child: string): boolean {
19
+ const rel = relative(parent, child)
20
+ return !!rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
21
+ }
22
+
23
+ function directory(path: string | undefined): string {
24
+ if (!path || !isAbsolute(path)) throw new Error()
25
+ const real = realpathSync(path)
26
+ if (!statSync(real).isDirectory()) throw new Error()
27
+ return real
28
+ }
29
+
30
+ function openSession(workspace: string, stateDir: string): SessionManager {
31
+ const args = process.argv.slice(2)
32
+ if (!args.length) return SessionManager.create(workspace, stateDir)
33
+ const [flag, file] = args
34
+ if (args.length !== 2 || flag !== "--session" || !file || !isAbsolute(file)) throw new Error()
35
+ const target = realpathSync(file)
36
+ if (!inside(stateDir, target) || !statSync(target).isFile()) throw new Error()
37
+ const session = SessionManager.open(target)
38
+ if (session.getCwd() !== workspace) throw new Error()
39
+ return session
40
+ }
41
+
42
+ async function start(): Promise<void> {
43
+ const workspace = directory(process.env.PI_ACP_MANAGED_CHAT_WORKSPACE)
44
+ const agentDir = directory(process.env.PI_CODING_AGENT_DIR)
45
+ const stateDir = directory(join(agentDir, "sessions"))
46
+ if (process.cwd() !== workspace || workspace === agentDir || inside(workspace, agentDir) || inside(agentDir, workspace) || !inside(agentDir, stateDir)) {
47
+ throw new Error()
48
+ }
49
+ const sessionManager = openSession(workspace, stateDir)
50
+ // MCP の認証ヘッダーを引数・環境変数・RPC の行には載せない。
51
+ const mcp = chatInput.parse(JSON.parse(await Bun.file(3).text()))
52
+ const { defaultProvider, defaultModel } = modelSettings.parse(JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8")))
53
+ const inherited = process.env.PI_ACP_INHERITED_AGENT_DIR
54
+ if (inherited !== undefined && !isAbsolute(inherited)) throw new Error()
55
+ const runtime = await createAgentSessionRuntime(async options => {
56
+ if (options.cwd !== workspace || options.sessionManager !== sessionManager) throw new Error()
57
+ const source = inherited === undefined ? undefined : SettingsManager.create(workspace, inherited, { projectTrusted: true })
58
+ if (source?.drainErrors().length) throw new Error()
59
+ const services = await createAgentSessionServices({
60
+ cwd: workspace,
61
+ agentDir: inherited ?? agentDir,
62
+ modelRuntime: await ModelRuntime.create({ authPath: join(agentDir, "auth.json"), modelsPath: join(agentDir, "models.json") }),
63
+ // 継承するのは設定の値だけ。SDK から端末やプロジェクトの settings.json へは保存しない。
64
+ settingsManager: SettingsManager.inMemory({
65
+ ...source?.getSettings(), defaultProvider, defaultModel, enableSkillCommands: false,
66
+ // 承認依頼で示したコマンドに、設定由来のコマンドを付け足さない。
67
+ shellCommandPrefix: "",
68
+ ...(!source ? { compaction: { enabled: false }, retry: { enabled: false } } : {}),
69
+ }, { projectTrusted: source !== undefined }),
70
+ resourceLoaderOptions: {
71
+ ...(!source ? {
72
+ noContextFiles: true, noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true,
73
+ // 空文字で探索を止める。固定文を systemPrompt に渡すと、SDK はパスとしても解釈する。
74
+ systemPrompt: "", systemPromptOverride: () => relayPrompt, appendSystemPrompt: [],
75
+ } : { appendSystemPromptOverride: entries => [...entries, relayPrompt] }),
76
+ disabledBuiltinExtensions: ["mcp"],
77
+ extensionFactories: [{ name: managedExtensionName, factory: managedChat(mcp, workspace, stateDir) }],
78
+ },
79
+ })
80
+ const model = services.modelRuntime.getModel(defaultProvider, defaultModel)
81
+ if (!model || !services.modelRuntime.hasConfiguredAuth(defaultProvider) || services.diagnostics.length || services.resourceLoader.getExtensions().errors.length) {
82
+ throw new Error()
83
+ }
84
+ return {
85
+ ...await createAgentSessionFromServices({ ...options, services, model, scopedModels: [{ model }], tools: managedToolSelection }),
86
+ services,
87
+ diagnostics: [],
88
+ }
89
+ }, { cwd: workspace, agentDir, sessionManager })
90
+ await runRpcMode(runtime)
91
+ }
92
+
93
+ if (import.meta.main) {
94
+ await start().catch(() => {
95
+ // ファイル・認証・HTTP リクエストに由来する値をログに出さない。
96
+ process.stderr.write("Managed Pi RPC failed to start or run\n")
97
+ process.exitCode = 1
98
+ })
99
+ }
@@ -0,0 +1,99 @@
1
+ import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"
2
+ import { isUtf8 } from "node:buffer"
3
+ import { join } from "node:path"
4
+ import { createReadToolDefinition } from "@earendil-works/pi-coding-agent"
5
+ import { approvePiToolCall } from "../../harness/pi/tool-approval.ts"
6
+
7
+ const MAX_BYTES = 1024 * 1024
8
+ // Darwin の <sys/fcntl.h>。最後だけではなく、途中のシンボリックリンクもたどらない。
9
+ const O_NOFOLLOW_ANY = 0x20000000
10
+ const flags = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY | O_NOFOLLOW_ANY
11
+
12
+ function supportsNoFollow(stateDir: string): boolean {
13
+ if (process.platform !== "darwin") return false
14
+ let probe: string | undefined
15
+ try {
16
+ const dir = mkdtempSync(join(stateDir, ".read-probe-"))
17
+ probe = dir
18
+ const file = join(dir, "plain")
19
+ writeFileSync(file, "")
20
+ closeSync(openSync(file, flags))
21
+ symlinkSync("plain", join(dir, "file-link"))
22
+ symlinkSync(".", join(dir, "dir-link"))
23
+ return ["file-link", "dir-link/plain"].every(path => {
24
+ try {
25
+ closeSync(openSync(join(dir, path), flags))
26
+ return false
27
+ } catch (err) {
28
+ return (err as NodeJS.ErrnoException).code === "ELOOP"
29
+ }
30
+ })
31
+ } catch {
32
+ return false
33
+ } finally {
34
+ if (probe) rmSync(probe, { recursive: true, force: true })
35
+ }
36
+ }
37
+
38
+ function relativeReadPath(workspace: string, path: string): string | undefined {
39
+ const prefix = `${workspace}/`
40
+ const relative = path.startsWith(prefix) ? path.slice(prefix.length) : path.replace(/^\.\//, "")
41
+ // OS に渡すパスだけを判定する。Pi の ~ / @ やファイル名の補完には頼らない。
42
+ if (relative.startsWith("~") || relative.startsWith("@") || relative.includes("\0")) return
43
+ if (relative.split("/").some(part => part === "" || part === "." || part === "..")) return
44
+ return relative
45
+ }
46
+
47
+ function snapshot(workspace: string, path: string): Buffer | undefined {
48
+ const relative = relativeReadPath(workspace, path)
49
+ if (relative === undefined) return
50
+ try {
51
+ if (process.cwd() !== workspace) return
52
+ // 作業ディレクトリを起点にリンクをたどらず開く。確認後にパスを開き直さない。
53
+ const fd = openSync(relative, flags)
54
+ try {
55
+ const stat = fstatSync(fd, { bigint: true })
56
+ if (!stat.isFile() || stat.nlink !== 1n || stat.dev !== statSync(".", { bigint: true }).dev || stat.size < 0n || stat.size > BigInt(MAX_BYTES)) return
57
+ const bytes = Buffer.alloc(Number(stat.size) + 1)
58
+ for (let used = 0; used < bytes.length;) {
59
+ const count = readSync(fd, bytes, used, bytes.length - used, used)
60
+ if (count === 0) {
61
+ const data = bytes.subarray(0, used)
62
+ // 画像などは、承認を得てから Pi 標準の読み取りに任せる。
63
+ return data.includes(0) || !isUtf8(data) ? undefined : data
64
+ }
65
+ used += count
66
+ }
67
+ // 読み取り中に伸びた。この試行の結果は返さない。
68
+ } finally {
69
+ closeSync(fd)
70
+ }
71
+ } catch {
72
+ return
73
+ }
74
+ }
75
+
76
+ export function managedRead(workspace: string, stateDir: string, sessionSignal: AbortSignal) {
77
+ const noFollow = supportsNoFollow(stateDir)
78
+ const stock = createReadToolDefinition(workspace)
79
+ const tool: typeof stock = {
80
+ ...stock,
81
+ async execute(id, params, toolSignal, onUpdate, ctx) {
82
+ const signal = toolSignal ? AbortSignal.any([toolSignal, sessionSignal]) : sessionSignal
83
+ signal.throwIfAborted()
84
+ const bytes = noFollow && ctx.cwd === workspace ? snapshot(workspace, params.path) : undefined
85
+ if (bytes !== undefined) {
86
+ // Pi の行範囲・切り詰めを使うが、どのパスを渡されても実際に確認したバイトだけを返す。
87
+ const read = createReadToolDefinition(workspace, {
88
+ operations: { access: async () => {}, readFile: async () => bytes },
89
+ })
90
+ return read.execute(id, params, signal, onUpdate, ctx)
91
+ }
92
+ const blocked = await approvePiToolCall({ toolName: "read", input: params }, ctx, { sessionSignal: signal })
93
+ if (blocked) throw new Error(blocked.reason)
94
+ signal.throwIfAborted()
95
+ return stock.execute(id, params, signal, onUpdate, ctx)
96
+ },
97
+ }
98
+ return tool
99
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "pi-acp",
3
+ "version": "0.0.34",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "private": true
7
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mario Zechner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Sergii Kozak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/src/version.ts ADDED
@@ -0,0 +1,4 @@
1
+ // 中継のバージョン。package.json から読む(npm の配布物にも、package.json は必ず入る)
2
+ import pkg from "../package.json" with { type: "json" }
3
+
4
+ export const VERSION: string = pkg.version
@@ -0,0 +1,117 @@
1
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
3
+
4
+ /** 作業ディレクトリ。specified は、管理者が RELAY_WORKSPACE で指定したものか(ADR 0017) */
5
+ export type Workspace = { path: string; specified: boolean }
6
+
7
+ /**
8
+ * 作業ディレクトリを決める。RELAY_WORKSPACE があればそのディレクトリを、なければ <home>/workspace を使う。
9
+ * protect は、作業ディレクトリに含めてはいけない場所(中継のデータと秘密情報の置き場)。
10
+ * 作業ディレクトリの中は、実行承認なしで読めて、ルームへ返せるため
11
+ */
12
+ export function resolveWorkspace(env: Record<string, string | undefined>, home: string, protect: string[]): Workspace {
13
+ const given = env.RELAY_WORKSPACE
14
+ if (!given) {
15
+ const path = join(home, "workspace")
16
+ initWorkspace(path)
17
+ return { path, specified: false }
18
+ }
19
+ // 書き間違いで、意図しない空のディレクトリで動き出さないよう、作らない
20
+ const abs = resolve(given)
21
+ if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new Error(`RELAY_WORKSPACE のディレクトリがありません: ${abs}`)
22
+ const path = realpathSync(abs)
23
+ for (const p of protect) {
24
+ if (contains(path, realOrResolved(p))) throw new Error(`RELAY_WORKSPACE が、中継のデータか秘密情報の置き場を含むため、起動しません: ${p}`)
25
+ }
26
+ // 管理者のディレクトリなので、git init しない(上位のディレクトリの設定からの切り離しは保証しない)
27
+ return { path, specified: true }
28
+ }
29
+
30
+ /** dir が target と同じか、target を中に含むか */
31
+ function contains(dir: string, target: string): boolean {
32
+ const rel = relative(dir, target)
33
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
34
+ }
35
+
36
+ /** 実パスにする。まだないパス(初回の RELAY_HOME など)は、あるところまでを実パスにする */
37
+ function realOrResolved(p: string): string {
38
+ const abs = resolve(p)
39
+ if (existsSync(abs)) return realpathSync(abs)
40
+ const parent = dirname(abs)
41
+ return parent === abs ? abs : join(realOrResolved(parent), basename(abs))
42
+ }
43
+
44
+ /**
45
+ * 作業ディレクトリの中の、中継の置き場(.relay/。受け取った添付など)を用意して、その場所を返す。
46
+ * 管理者の git リポジトリを作業ディレクトリにしても、ルームから届いたファイルがコミットされないよう、
47
+ * 中に「すべて無視する」.gitignore を置く。.relay/ は中継のものなので、毎回置き換える。管理者の .gitignore には触れない
48
+ */
49
+ export function relayDir(workspace: string): string {
50
+ const dir = join(workspace, ".relay")
51
+ // ディレクトリがリンクだと、.gitignore の作成や、古い添付の削除が、リンク先に及ぶ
52
+ for (const p of [dir, join(dir, "inbox")]) {
53
+ if (isLink(p)) throw new Error(`作業ディレクトリの ${relative(workspace, p)} がシンボリックリンクのため、起動しません: ${p}`)
54
+ }
55
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
56
+ // すでにある .gitignore を通して書くと、リンクやハードリンクの先に及ぶ。消してから作ると、その間は無視されない。
57
+ // 新しいファイルに書いてから名前を付け替え、ディレクトリの項目を 1 回で置き換える
58
+ const tmp = join(dir, `.gitignore.${process.pid}.${crypto.randomUUID()}`)
59
+ try {
60
+ writeFileSync(tmp, "*\n", { flag: "wx" })
61
+ renameSync(tmp, join(dir, ".gitignore"))
62
+ } finally {
63
+ rmSync(tmp, { force: true })
64
+ }
65
+ return dir
66
+ }
67
+
68
+ function isLink(p: string): boolean {
69
+ try {
70
+ return lstatSync(p).isSymbolicLink()
71
+ } catch {
72
+ return false
73
+ }
74
+ }
75
+
76
+ /**
77
+ * git のリポジトリの場所を変える環境変数。git init は、作業ディレクトリではなく、これらが指す場所に書く。
78
+ * 確認で止まる前に作業ディレクトリの外へ書かないよう、git init の前に止める
79
+ */
80
+ const GIT_LOCATION_ENV = ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_INDEX_FILE"]
81
+
82
+ /**
83
+ * 作業ディレクトリを独立した git リポジトリにして、上位の設定や AGENTS.md を拾わせない。
84
+ * .git があるかではなく、git から見たリポジトリの最上位・git のディレクトリ・共有のディレクトリが、作業ディレクトリ自身のものであることを確かめる。
85
+ * git init は、.git がないか空のときだけ実行する。既存の .git に実行すると、環境変数(GIT_DEFAULT_HASH など)や
86
+ * .git/commondir 次第で、そのリポジトリや、指す先のリポジトリを書き換えうるため。.git は消さない(エージェントの履歴を失いうる)。
87
+ * 確かめられなければ起動しない。
88
+ * git の環境変数は取り除かず、ハーネスが受け取るのと同じ環境(env)で確かめる。別の場所を向いていれば、起動しない
89
+ */
90
+ export function initWorkspace(workspace: string, git = "git", env: Record<string, string | undefined> = process.env): void {
91
+ const relocating = GIT_LOCATION_ENV.filter((name) => env[name])
92
+ if (relocating.length > 0) {
93
+ throw new Error(`環境変数 ${relocating.join("・")} が git のリポジトリの場所を変えるため、起動しません。外してから起動してください: ${workspace}`)
94
+ }
95
+ const noGit = `作業ディレクトリを git リポジトリにできないため、起動しません。git がインストールされているか確かめてください: ${workspace}`
96
+ if (!Bun.which(git)) throw new Error(noGit)
97
+ mkdirSync(workspace, { recursive: true, mode: 0o700 })
98
+ // .git がリンクか、gitdir: を書いたファイルだと、git init がその先のリポジトリに書き、作業ディレクトリの外に及ぶ
99
+ const dotGit = join(workspace, ".git")
100
+ const dotGitStat = lstatSync(dotGit, { throwIfNoEntry: false })
101
+ if (dotGitStat && !dotGitStat.isDirectory()) {
102
+ throw new Error(`作業ディレクトリの .git がディレクトリではない(シンボリックリンクか、別の場所を指すファイル)ため、起動しません。.git を確かめるか、退避してから起動してください: ${dotGit}`)
103
+ }
104
+ if (isOwnRepository(workspace, git, env)) return
105
+ const notIsolated = `作業ディレクトリが、git から見て独立したリポジトリになっていないため、起動しません。.git を確かめるか、退避してから起動してください: ${workspace}`
106
+ if (dotGitStat && readdirSync(dotGit).length > 0) throw new Error(notIsolated)
107
+ if (!Bun.spawnSync([git, "init", "-q", workspace], { env }).success) throw new Error(noGit)
108
+ if (!isOwnRepository(workspace, git, env)) throw new Error(notIsolated)
109
+ }
110
+
111
+ /** git から見たリポジトリの最上位が workspace 自身で、git のディレクトリと共有のディレクトリが <workspace>/.git か */
112
+ function isOwnRepository(workspace: string, git: string, env: Record<string, string | undefined>): boolean {
113
+ const real = realpathSync(workspace)
114
+ const dotGit = join(real, ".git")
115
+ const found = Bun.spawnSync([git, "-C", real, "rev-parse", "--path-format=absolute", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"], { env })
116
+ return found.success && found.stdout.toString() === `${real}\n${dotGit}\n${dotGit}\n`
117
+ }