@dotlabo/agent-chat-relay 0.0.0-stage → 0.2.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/CHANGELOG.md +109 -0
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/bin/agent-chat-relay +22 -0
- package/package.json +69 -4
- package/src/connectors/chatwork.ts +289 -0
- package/src/connectors/common.ts +106 -0
- package/src/connectors/discord.ts +335 -0
- package/src/connectors/http.ts +137 -0
- package/src/connectors/line-media.ts +63 -0
- package/src/connectors/line.ts +444 -0
- package/src/connectors/terminal.ts +367 -0
- package/src/core/access.ts +250 -0
- package/src/core/instructions.ts +21 -0
- package/src/core/mcp.ts +160 -0
- package/src/core/relay.ts +1063 -0
- package/src/core/retention.ts +44 -0
- package/src/harness/config.ts +137 -0
- package/src/harness/harness.ts +327 -0
- package/src/harness/log-file.ts +34 -0
- package/src/harness/pi/config.ts +51 -0
- package/src/harness/pi/state.ts +97 -0
- package/src/harness/pi/tool-approval.ts +128 -0
- package/src/harness/protect.ts +37 -0
- package/src/home.ts +67 -0
- package/src/jev.ts +201 -0
- package/src/main.ts +275 -0
- package/src/prompt.ts +12 -0
- package/src/serve-args.ts +56 -0
- package/src/shutdown.ts +52 -0
- package/src/terminal.ts +172 -0
- package/src/vendor/pi/adapter.js +3238 -0
- package/src/vendor/pi/managed-extension.ts +94 -0
- package/src/vendor/pi/managed-pi-rpc.ts +102 -0
- package/src/vendor/pi/managed-read.ts +99 -0
- package/src/vendor/pi/package.json +7 -0
- package/src/vendor/pi/pi-LICENSE +21 -0
- package/src/vendor/pi/pi-acp-LICENSE +21 -0
- package/src/version.ts +4 -0
- package/src/workspace.ts +117 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync } from "node:fs"
|
|
2
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
|
|
3
|
+
|
|
4
|
+
const SESSION_ID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/
|
|
5
|
+
|
|
6
|
+
function contains(dir: string, path: string): boolean {
|
|
7
|
+
const rel = relative(dir, path)
|
|
8
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** まだない部分は、その親の実パスに名前を足す。リンク切れはエラーにする。 */
|
|
12
|
+
function realLocation(path: string): string {
|
|
13
|
+
if (lstatSync(path, { throwIfNoEntry: false })) return realpathSync(path)
|
|
14
|
+
return join(realLocation(dirname(path)), basename(path))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function directory(path: string, allowed: number, recursive = false): void {
|
|
18
|
+
try {
|
|
19
|
+
mkdirSync(path, { mode: 0o700, recursive })
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err
|
|
22
|
+
}
|
|
23
|
+
const entry = lstatSync(path)
|
|
24
|
+
if (!entry.isDirectory() || entry.uid !== process.getuid?.() || (entry.mode & 0o777 & ~allowed) !== 0 || realpathSync(path) !== path) {
|
|
25
|
+
throw new Error(`pi の管理領域は、自分が所有する実ディレクトリを指定してください: ${path}`)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 秘密情報・台帳を、リンク経由や他の利用者が読めるファイルから取らない。 */
|
|
30
|
+
function privateFile(path: string): Buffer {
|
|
31
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
32
|
+
try {
|
|
33
|
+
const entry = fstatSync(fd)
|
|
34
|
+
if (!entry.isFile() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || (entry.mode & 0o077) !== 0 || entry.size > 1024 * 1024) throw new Error()
|
|
35
|
+
return readFileSync(fd)
|
|
36
|
+
} finally {
|
|
37
|
+
closeSync(fd)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function preparePiState(home: string, cwd: string) {
|
|
42
|
+
const workspace = realpathSync(cwd)
|
|
43
|
+
const root = realLocation(resolve(home))
|
|
44
|
+
const pi = join(root, "pi")
|
|
45
|
+
if (contains(workspace, root) || contains(pi, workspace)) throw new Error("pi の管理領域と作業ディレクトリは分けてください")
|
|
46
|
+
directory(root, 0o755, true)
|
|
47
|
+
directory(pi, 0o700)
|
|
48
|
+
const agentDir = join(pi, "agent")
|
|
49
|
+
const childHome = join(pi, "home")
|
|
50
|
+
const temp = join(pi, "tmp")
|
|
51
|
+
const registry = join(pi, "registered-sessions")
|
|
52
|
+
for (const path of [agentDir, join(agentDir, "sessions"), childHome, temp, registry]) directory(path, 0o700)
|
|
53
|
+
// pi-acp が開いて更新するファイル。既存の対応表を通じて、別のファイルへ書かない。
|
|
54
|
+
const map = lstatSync(join(agentDir, "pi-acp-session-map.json"), { throwIfNoEntry: false })
|
|
55
|
+
if (map && (!map.isFile() || map.nlink !== 1 || map.uid !== process.getuid?.() || (map.mode & 0o022) !== 0)) {
|
|
56
|
+
throw new Error("pi-acp の対応表は、自分が所有する通常ファイルでなければ使えません")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sessionFile(id: string) {
|
|
60
|
+
if (!SESSION_ID.test(id)) throw new Error("pi のセッション ID が不正です")
|
|
61
|
+
return join(registry, `${id}.json`)
|
|
62
|
+
}
|
|
63
|
+
function record(id: string) {
|
|
64
|
+
return { harness: "pi", workspace, sessionId: id }
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
workspace, agentDir, childHome, temp,
|
|
68
|
+
checkModelFiles() {
|
|
69
|
+
const settings = join(agentDir, "settings.json")
|
|
70
|
+
const auth = join(agentDir, "auth.json")
|
|
71
|
+
const models = join(agentDir, "models.json")
|
|
72
|
+
for (const path of [settings, auth, ...(lstatSync(models, { throwIfNoEntry: false }) ? [models] : [])]) {
|
|
73
|
+
try {
|
|
74
|
+
const value: unknown = JSON.parse(privateFile(path).toString("utf8"))
|
|
75
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).length === 0) throw new Error()
|
|
76
|
+
} catch {
|
|
77
|
+
throw new Error(`pi 専用の設定・認証を、自分だけが読める通常の JSON ファイルに用意してください: ${path}`)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
requireSession(id: string) {
|
|
82
|
+
const path = sessionFile(id)
|
|
83
|
+
try {
|
|
84
|
+
const saved = JSON.parse(privateFile(path).toString("utf8")) as ReturnType<typeof record>
|
|
85
|
+
const expected = record(id)
|
|
86
|
+
if (saved.harness === expected.harness && saved.workspace === expected.workspace && saved.sessionId === expected.sessionId) return
|
|
87
|
+
} catch {
|
|
88
|
+
// 台帳を読めない場合も、記録がない場合と同じように起動しない。
|
|
89
|
+
}
|
|
90
|
+
throw new Error("同じ作業ディレクトリで中継が作った pi のセッションに限って再開できます")
|
|
91
|
+
},
|
|
92
|
+
registerSession(id: string) {
|
|
93
|
+
// セッション ID は新規。既存の台帳やリンクには書かない。
|
|
94
|
+
writeFileSync(sessionFile(id), JSON.stringify(record(id)) + "\n", { flag: "wx", mode: 0o600 })
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { homedir } from "node:os"
|
|
2
|
+
import { isAbsolute, join, sep } from "node:path"
|
|
3
|
+
import { fileURLToPath } from "node:url"
|
|
4
|
+
import { protectedBy, targetsOf } from "../protect.ts"
|
|
5
|
+
|
|
6
|
+
// pi 1.5.2 の tool_call と ui.confirm の接続に必要な部分だけを受ける。
|
|
7
|
+
type PiToolCall = { toolName: string; input: unknown }
|
|
8
|
+
type PiApprovalContext = {
|
|
9
|
+
hasUI: boolean
|
|
10
|
+
signal?: AbortSignal
|
|
11
|
+
ui: { confirm(title: string, message: string, options: { timeout: number; signal: AbortSignal }): Promise<boolean> }
|
|
12
|
+
}
|
|
13
|
+
type PiApprovalOptions = { sessionSignal?: AbortSignal; timeoutMs?: number }
|
|
14
|
+
type Blocked = { block: true; reason: string }
|
|
15
|
+
|
|
16
|
+
// 中継の実行承認と同じ 30 分を上限にする(src/core/relay.ts の PERMISSION_TIMEOUT_MS)。
|
|
17
|
+
const MAX_APPROVAL_WAIT_MS = 30 * 60 * 1000
|
|
18
|
+
|
|
19
|
+
function stringField(input: unknown, key: string): string | undefined {
|
|
20
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return
|
|
21
|
+
const value: unknown = Object.getOwnPropertyDescriptor(input, key)?.value
|
|
22
|
+
if (typeof value === "string") return value
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 表示に使う文字列。空白だけのものは、確認できないとして扱う */
|
|
26
|
+
function textField(input: unknown, key: string): string | undefined {
|
|
27
|
+
const value = stringField(input, key)
|
|
28
|
+
if (value?.trim()) return value
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 改行や表示方向を変える文字を、対象の一部として見える形にする。 */
|
|
32
|
+
function quoted(text: string): string {
|
|
33
|
+
return JSON.stringify(text).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (ch) => `\\u{${(ch.codePointAt(0) ?? 0).toString(16)}}`)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 操作と対象だけを ACP の承認依頼に渡す。ツールの入力全体は転送しない。 */
|
|
37
|
+
export function describePiToolCall({ toolName, input }: PiToolCall): { title: string; message: string } {
|
|
38
|
+
if (toolName === "bash") {
|
|
39
|
+
const command = textField(input, "command")
|
|
40
|
+
return { title: "bash:シェルの実行", message: command === undefined ? "コマンドを確認できません" : `コマンド: ${quoted(command)}` }
|
|
41
|
+
}
|
|
42
|
+
if (toolName === "read" || toolName === "write" || toolName === "edit") {
|
|
43
|
+
const path = textField(input, "path")
|
|
44
|
+
const operation = { read: "ファイルの読み取り", write: "ファイルの作成・上書き", edit: "ファイルの編集" }[toolName]
|
|
45
|
+
return { title: `${toolName}:${operation}`, message: path === undefined ? "対象パスを確認できません" : `対象パス: ${quoted(path)}` }
|
|
46
|
+
}
|
|
47
|
+
return { title: "その他のツールの実行", message: `ツール: ${quoted(toolName)}(対象を確認できません)` }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// pi 1.5.2 の dist/utils/paths.js の UNICODE_SPACES。pi はこれを普通の空白にしてから開く。
|
|
51
|
+
const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* pi 1.5.2 の resolveToCwd(dist/core/tools/path-utils.js、dist/utils/paths.js の normalizePath)と同じ規則で、
|
|
55
|
+
* ツールの path を絶対パスにする。pi はこれらの関数を公開していないので、規則を写す(テストが、入力の表について実物の pi のツールと突き合わせる)。
|
|
56
|
+
* ~ は、pi と同じく、このプロセスの HOME(中継が用意した pi のホーム)で展開する。.. は畳まない(targetsOf が両方を比べる)
|
|
57
|
+
*/
|
|
58
|
+
function piPath(path: string, cwd: string): string {
|
|
59
|
+
let p = path.replace(UNICODE_SPACES, " ")
|
|
60
|
+
if (p.startsWith("@")) p = p.slice(1)
|
|
61
|
+
if (p === "~") p = homedir()
|
|
62
|
+
else if (p.startsWith("~/")) p = join(homedir(), p.slice(2))
|
|
63
|
+
else if (p.startsWith("file://")) p = fileURLToPath(p)
|
|
64
|
+
return isAbsolute(p) ? p : `${cwd}${sep}${p}`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* read は、パスのファイルがなければ、macOS のファイル名の候補を開く(pi 1.5.2 の resolveReadPath)。
|
|
69
|
+
* どれを開くかはファイルの有無で決まるので、すべてを比べる。write・edit でも比べる(多めに拒否するだけ)
|
|
70
|
+
*/
|
|
71
|
+
function readVariants(p: string): string[] {
|
|
72
|
+
const nfd = p.normalize("NFD")
|
|
73
|
+
const curly = (s: string) => s.replace(/'/g, "\u2019")
|
|
74
|
+
return [p, p.replace(/ (AM|PM)\./gi, "\u202F$1."), nfd, curly(p), curly(nfd)]
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 端末の接続用のファイル(protect)に触れる read・write・edit を、承認者に尋ねずに拒否する(ADR 0030)。
|
|
79
|
+
* パスは pi と同じ規則で解き、シンボリックリンクをたどった実体で比べる。解けないパスも拒否する。
|
|
80
|
+
* bash などの、対象のパスを示さない操作は見分けられない(ADR 0030 の限界)
|
|
81
|
+
*/
|
|
82
|
+
export function guardPiToolCall({ toolName, input }: PiToolCall, cwd: string, protect: string[]): Blocked | undefined {
|
|
83
|
+
if (toolName !== "read" && toolName !== "write" && toolName !== "edit") return
|
|
84
|
+
// 空白だけのパスも、pi はその名前のファイルとして開くので、trim せずに比べる
|
|
85
|
+
const path = stringField(input, "path")
|
|
86
|
+
if (path === undefined) return
|
|
87
|
+
const blocked: Blocked = { block: true, reason: "端末の接続用のファイルには触れられません" }
|
|
88
|
+
let abs: string
|
|
89
|
+
try {
|
|
90
|
+
abs = piPath(path, cwd)
|
|
91
|
+
} catch {
|
|
92
|
+
return blocked
|
|
93
|
+
}
|
|
94
|
+
return readVariants(abs).flatMap(targetsOf).some(protectedBy(protect)) ? blocked : undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 実行承認を求める。承認を省けるかどうかは、実際の読み取りなどを担う呼び出し側で判断する。 */
|
|
98
|
+
export async function approvePiToolCall(
|
|
99
|
+
event: PiToolCall,
|
|
100
|
+
ctx: PiApprovalContext,
|
|
101
|
+
{ sessionSignal, timeoutMs = MAX_APPROVAL_WAIT_MS }: PiApprovalOptions = {},
|
|
102
|
+
): Promise<Blocked | undefined> {
|
|
103
|
+
const blocked: Blocked = { block: true, reason: "実行が許可されませんでした" }
|
|
104
|
+
const turnSignal = ctx.signal
|
|
105
|
+
if (ctx.hasUI !== true || !turnSignal || turnSignal.aborted || sessionSignal?.aborted) return blocked
|
|
106
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_APPROVAL_WAIT_MS) return blocked
|
|
107
|
+
|
|
108
|
+
const deadline = performance.now() + timeoutMs
|
|
109
|
+
const timeout = new AbortController()
|
|
110
|
+
const signal = AbortSignal.any(sessionSignal ? [turnSignal, sessionSignal, timeout.signal] : [turnSignal, timeout.signal])
|
|
111
|
+
const timer = setTimeout(() => timeout.abort(), timeoutMs)
|
|
112
|
+
const cancelled = Promise.withResolvers<boolean>()
|
|
113
|
+
const cancel = () => cancelled.resolve(false)
|
|
114
|
+
signal.addEventListener("abort", cancel, { once: true })
|
|
115
|
+
try {
|
|
116
|
+
const { title, message } = describePiToolCall(event)
|
|
117
|
+
if (signal.aborted || performance.now() >= deadline) return blocked
|
|
118
|
+
const confirmed = await Promise.race([ctx.ui.confirm(title, message, { timeout: timeoutMs, signal }), cancelled.promise])
|
|
119
|
+
// タイマーのコールバックより先に届いた返事でも、期限後なら採用しない。
|
|
120
|
+
if (confirmed === true && !signal.aborted && performance.now() < deadline) return
|
|
121
|
+
} catch {
|
|
122
|
+
// UI や接続のエラーは拒否と同じ扱いにし、入力を含み得るエラーを出力しない。
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
signal.removeEventListener("abort", cancel)
|
|
126
|
+
}
|
|
127
|
+
return blocked
|
|
128
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// 依頼の対象のパスを、端末の接続用のファイル(ADR 0030)と比べる。中継の本体(guardProtected)と、pi の拡張の両方で使う。
|
|
2
|
+
|
|
3
|
+
import { realpathSync } from "node:fs"
|
|
4
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 依頼のパス(絶対パス)の、比べる候補。どちらも、シンボリックリンクをたどった実体のパス。
|
|
8
|
+
* ツールが .. を OS のとおりに解くか(リンクの先の親)、文字列の上で畳んでから開くか(リンクのある場所の親)は分からないので、両方を返す
|
|
9
|
+
*/
|
|
10
|
+
export function targetsOf(abs: string): string[] {
|
|
11
|
+
return [real(abs), real(resolve(abs))]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 実体のパス dir が、守るパスのどれかであるか、どれかを中に含むかを返す関数 */
|
|
15
|
+
export function protectedBy(protect: string[]): (dir: string) => boolean {
|
|
16
|
+
const guarded = protect.map(real)
|
|
17
|
+
return (dir) => guarded.some((p) => inside(dir, p))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* シンボリックリンクをたどった実体のパス。まだないパスは、あるところまでをたどり、残りをつなぐ。
|
|
22
|
+
* OS と同じく、リンクをたどってから .. を解く realpath(native)を使う。Bun の JS 版は、先に .. を畳む
|
|
23
|
+
*/
|
|
24
|
+
function real(p: string): string {
|
|
25
|
+
try {
|
|
26
|
+
return realpathSync.native(p)
|
|
27
|
+
} catch {
|
|
28
|
+
const parent = dirname(p)
|
|
29
|
+
return parent === p ? p : join(real(parent), basename(p))
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** p が dir そのものか、その中にあるか。どちらも絶対パス(POSIX では、relative は絶対パスを返さない) */
|
|
34
|
+
function inside(dir: string, p: string): boolean {
|
|
35
|
+
const rel = relative(dir, p)
|
|
36
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`)
|
|
37
|
+
}
|
package/src/home.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// 中継のデータの置き場(RELAY_HOME)と、秘密情報のファイル(ADR 0019)。
|
|
2
|
+
// どちらも、起動したディレクトリには左右されない。起動したディレクトリや作業ディレクトリは、エージェントが書ける場所でありうるため
|
|
3
|
+
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
|
5
|
+
import { homedir } from "node:os"
|
|
6
|
+
import { dirname, join, resolve } from "node:path"
|
|
7
|
+
|
|
8
|
+
type Env = Record<string, string | undefined>
|
|
9
|
+
|
|
10
|
+
/** 中継のデータの置き場。既定は ~/.agent-chat-relay */
|
|
11
|
+
export function relayHome(env: Env): string {
|
|
12
|
+
return resolve(env.RELAY_HOME || join(homedir(), ".agent-chat-relay"))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** 秘密情報のファイル。既定は <home>/.env */
|
|
16
|
+
export function secretsFile(env: Env, home: string): string {
|
|
17
|
+
return resolve(env.RELAY_ENV_FILE || join(home, ".env"))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 秘密情報のファイルの KEY=VALUE を読む。空行と # で始まる行は飛ばし、値の両端の引用符は外す */
|
|
21
|
+
export function parseSecrets(text: string): Record<string, string> {
|
|
22
|
+
const out: Record<string, string> = {}
|
|
23
|
+
for (const raw of text.split("\n")) {
|
|
24
|
+
const line = raw.trim()
|
|
25
|
+
if (!line || line.startsWith("#")) continue
|
|
26
|
+
const eq = line.indexOf("=")
|
|
27
|
+
if (eq <= 0) continue
|
|
28
|
+
let value = line.slice(eq + 1).trim()
|
|
29
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) value = value.slice(1, -1)
|
|
30
|
+
out[line.slice(0, eq).trim()] = value
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 秘密情報のファイルを読み、まだない環境変数にだけ設定する(環境変数が優先)。
|
|
37
|
+
* scripts/relay.sh が dotenvx で読み込み済み(RELAY_ENV_LOADED)なら読まない。開発用の .env は暗号化されているため
|
|
38
|
+
*/
|
|
39
|
+
export function loadSecrets(path: string, env: Env, warn: (msg: string) => void): void {
|
|
40
|
+
if (env.RELAY_ENV_LOADED || !existsSync(path)) return
|
|
41
|
+
if ((statSync(path).mode & 0o077) !== 0) warn(`${path} を、自分以外も読めます。chmod 600 ${path} で絞ってください`)
|
|
42
|
+
for (const [k, v] of Object.entries(parseSecrets(readFileSync(path, "utf8")))) env[k] ??= v
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 秘密情報のファイルにあるキーの名前。ハーネスには、これらを渡さない(環境変数で渡したものも含む)。
|
|
47
|
+
* dotenvx で暗号化したファイルでも、キーの名前は平文なので読める
|
|
48
|
+
*/
|
|
49
|
+
export function secretKeys(path: string): string[] {
|
|
50
|
+
return existsSync(path) ? Object.keys(parseSecrets(readFileSync(path, "utf8"))) : []
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 秘密情報を保存する。ほかの行は残す。ファイルは 0600、新しく作るディレクトリは 0700 にする */
|
|
54
|
+
export function storeSecrets(path: string, values: Record<string, string>): void {
|
|
55
|
+
for (const [k, v] of Object.entries(values)) {
|
|
56
|
+
if (!v) throw new Error(`${k} が空です`)
|
|
57
|
+
if (/[\r\n]/.test(v)) throw new Error(`${k} に改行が含まれています`)
|
|
58
|
+
}
|
|
59
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
60
|
+
// 同じ項目の行と空行を除いて残し、新しい値を末尾に足す
|
|
61
|
+
const rest = (existsSync(path) ? readFileSync(path, "utf8").split("\n") : []).filter((l) => l && !Object.keys(values).some((k) => l.trim().startsWith(`${k}=`)))
|
|
62
|
+
const tmp = `${path}.${process.pid}.tmp`
|
|
63
|
+
const body = [...rest, ...Object.entries(values).map(([k, v]) => `${k}=${v}`)].join("\n")
|
|
64
|
+
writeFileSync(tmp, `${body}\n`, { mode: 0o600 })
|
|
65
|
+
chmodSync(tmp, 0o600)
|
|
66
|
+
renameSync(tmp, path)
|
|
67
|
+
}
|
package/src/jev.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Jev(TypeSafe AI の System One モデル)で判定する。
|
|
2
|
+
// - 承認依頼の依頼者を推す(ADR 0026)。送り手が複数いるターンでだけ使う。推せなければ undefined を返し、中核は全員に送る。
|
|
3
|
+
// - 受信モードが「他人宛てを除く(Jev)」のルームで、メンションも他人宛ての印もない発言が、他人宛てかを判定する(ADR 0029)。
|
|
4
|
+
// 判定できなければ undefined を返し、中核は渡す。
|
|
5
|
+
|
|
6
|
+
import { z } from "zod"
|
|
7
|
+
import type { AttributionQuery, Attributor, Log, ScreenQuery, Screener } from "./core/relay.ts"
|
|
8
|
+
|
|
9
|
+
const ENDPOINT = "https://api.typesafe.ai/v1/systemone"
|
|
10
|
+
/** 別名(jev-latest)は指す先が変わり、下限を合わせた確率の意味が変わるので、バージョンを固定する */
|
|
11
|
+
const MODEL = "jev-1.14.0"
|
|
12
|
+
const TIMEOUT_MS = 2000
|
|
13
|
+
const DEFAULT_MIN_PROBABILITY = 0.8
|
|
14
|
+
/** Jev に渡す長さ。題名・入力・エージェントの文・発言の本文・名前(表示名とルーム名)と、発言の数 */
|
|
15
|
+
const LIMITS = { title: 500, input: 2000, agentText: 2000, text: 1000, name: 100, messages: 30 }
|
|
16
|
+
/** 「どの人でもない」の選択肢。人の選択肢は p1, p2, … なので重ならない */
|
|
17
|
+
const NONE = "none"
|
|
18
|
+
|
|
19
|
+
/** Jev に問い合わせ、答えを schema で確かめて返す。失敗したら、ログに書いて undefined を返す */
|
|
20
|
+
async function ask<T>(key: string, body: unknown, schema: z.ZodType<T>, log: Log, fetchFn: typeof fetch): Promise<T | undefined> {
|
|
21
|
+
let res: Response
|
|
22
|
+
try {
|
|
23
|
+
res = await fetchFn(ENDPOINT, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
26
|
+
body: JSON.stringify(body),
|
|
27
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
28
|
+
})
|
|
29
|
+
} catch (err) {
|
|
30
|
+
log.error("Jev に問い合わせられませんでした", { error: String(err) })
|
|
31
|
+
return undefined
|
|
32
|
+
}
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
log.error("Jev がエラーを返しました", { status: res.status })
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
const parsed = schema.safeParse(await res.json().catch(() => undefined))
|
|
38
|
+
if (!parsed.success) {
|
|
39
|
+
log.error("Jev の答えの形が想定外です")
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
return parsed.data
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** API キー(RELAY_TYPESAFE_API_KEY)があれば、Jev で推す関数を返す。下限の指定が不正なら、起動しない */
|
|
46
|
+
export function jevFromEnv(env: Record<string, string | undefined>, log: Log, fetchFn: typeof fetch = fetch): Attributor | undefined {
|
|
47
|
+
const key = env.RELAY_TYPESAFE_API_KEY
|
|
48
|
+
if (!key) return undefined
|
|
49
|
+
const min = minProbability(env.RELAY_JEV_MIN_PROBABILITY)
|
|
50
|
+
return async (q) => {
|
|
51
|
+
const { body, people } = request(q)
|
|
52
|
+
const answer = await ask(key, body, RESPONSE, log, fetchFn)
|
|
53
|
+
if (!answer) return undefined
|
|
54
|
+
const { choice, probabilities } = answer.answers.requester
|
|
55
|
+
const probability = probabilities[choice]!
|
|
56
|
+
const sender = people.get(choice)
|
|
57
|
+
log.info("Jev で承認依頼の依頼者を推しました", { sender, probability, min })
|
|
58
|
+
if (!sender || probability < min) return undefined
|
|
59
|
+
return { sender, probability }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Jev の答え。選んだ選択肢の確率があるものだけを受け付ける */
|
|
64
|
+
const RESPONSE = z.object({
|
|
65
|
+
answers: z.object({
|
|
66
|
+
requester: z.object({ choice: z.string(), probabilities: z.record(z.string(), z.number()) }).refine((a) => a.choice in a.probabilities),
|
|
67
|
+
}),
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
/** 下限。0 より大きく 1 以下の数。空なら既定 */
|
|
71
|
+
function minProbability(v: string | undefined): number {
|
|
72
|
+
if (!v) return DEFAULT_MIN_PROBABILITY
|
|
73
|
+
const n = Number(v)
|
|
74
|
+
if (!(n > 0 && n <= 1)) throw new Error(`RELAY_JEV_MIN_PROBABILITY に指定できるのは、0 より大きく 1 以下の数です(今は ${JSON.stringify(v)})`)
|
|
75
|
+
return n
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Jev への要求。人には p1, p2, … の名前を付け、ID は送らない。people は、その名前から ID へ */
|
|
79
|
+
function request(q: AttributionQuery): { body: unknown; people: Map<string, string> } {
|
|
80
|
+
const people = new Map<string, string>()
|
|
81
|
+
const labels = new Map<string, string>()
|
|
82
|
+
const criteria: Record<string, string> = {}
|
|
83
|
+
const messages = q.messages.slice(-LIMITS.messages).map((m) => {
|
|
84
|
+
const name = m.name.slice(0, LIMITS.name)
|
|
85
|
+
let label = labels.get(m.sender)
|
|
86
|
+
if (!label) {
|
|
87
|
+
label = `p${labels.size + 1}`
|
|
88
|
+
labels.set(m.sender, label)
|
|
89
|
+
people.set(label, m.sender)
|
|
90
|
+
criteria[label] = name ? `The person ${label} (shown as "${name}")` : `The person ${label} (no display name)`
|
|
91
|
+
}
|
|
92
|
+
return { person: label, name, room: m.room.slice(0, LIMITS.name), mentioned: m.mentioned, text: m.text.slice(0, LIMITS.text) }
|
|
93
|
+
})
|
|
94
|
+
criteria[NONE] = "None of these people, or it cannot be told from the state"
|
|
95
|
+
return {
|
|
96
|
+
people,
|
|
97
|
+
body: {
|
|
98
|
+
model: MODEL,
|
|
99
|
+
state: {
|
|
100
|
+
permission_request: { tool: q.title.slice(0, LIMITS.title), input: q.input.slice(0, LIMITS.input) },
|
|
101
|
+
agent_text: q.agentText.slice(-LIMITS.agentText),
|
|
102
|
+
chat_messages: messages,
|
|
103
|
+
},
|
|
104
|
+
questions: {
|
|
105
|
+
requester: {
|
|
106
|
+
type: "choice",
|
|
107
|
+
instructions:
|
|
108
|
+
"An AI agent in a group chat asks for permission to run the tool in `permission_request`. `chat_messages` are the messages it received in this turn, and `agent_text` is what it wrote. Whose request is the agent carrying out with this tool?",
|
|
109
|
+
criteria,
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---- 他人宛ての判定(ADR 0029) ----
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 他人宛ての判定の問い。1 つの問いに 1 つの条件を書き、組み合わせはコードで決める(DROP)。
|
|
120
|
+
* 問いを変えたら、scripts/jev-eval.sh で、実際の Jev に評価の会話を流し直す(bun run pre-pr が挙げる。docs/addressing-eval.md)
|
|
121
|
+
*/
|
|
122
|
+
export const SCREEN_QUESTIONS = {
|
|
123
|
+
agent: {
|
|
124
|
+
type: "noul",
|
|
125
|
+
instructions: "Is `message.text` addressed to `agent`, the AI assistant in this group chat?",
|
|
126
|
+
},
|
|
127
|
+
other: {
|
|
128
|
+
type: "noul",
|
|
129
|
+
instructions: "Is `message.text` addressed to one or more specific people in the chat other than `agent`?",
|
|
130
|
+
criteria: {
|
|
131
|
+
true: "It speaks to particular people other than the agent, by name or by replying to what they said",
|
|
132
|
+
false: "It speaks to the agent, to everyone, to whoever can answer, or to no one in particular",
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
answers_agent: {
|
|
136
|
+
type: "noul",
|
|
137
|
+
instructions: "Does `message.text` answer a question or a request that `agent` made in `recent_messages`?",
|
|
138
|
+
},
|
|
139
|
+
} as const
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 外す条件。ほかの人宛てである確率が高く、agent 宛てである確率と、agent への答えである確率がどちらも低いときだけ外す。
|
|
143
|
+
* 外し過ぎると、エージェントが答えるべき発言を落とすので、迷う発言は渡す
|
|
144
|
+
*/
|
|
145
|
+
const DROP = { other: 0.8, agent: 0.2, answersAgent: 0.2 }
|
|
146
|
+
/** state に入れる直前の発言の数(RELAY_JEV_CONTEXT_MESSAGES) */
|
|
147
|
+
const CONTEXT = { default: 10, max: 30 }
|
|
148
|
+
|
|
149
|
+
const SCREEN_RESPONSE = z.object({
|
|
150
|
+
answers: z.object({
|
|
151
|
+
agent: z.object({ noul: z.number() }),
|
|
152
|
+
other: z.object({ noul: z.number() }),
|
|
153
|
+
answers_agent: z.object({ noul: z.number() }),
|
|
154
|
+
}),
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
/** API キーがあれば、他人宛てを判定する関数を返す。直前の発言の数の指定が不正なら、起動しない */
|
|
158
|
+
export function screenFromEnv(env: Record<string, string | undefined>, log: Log, fetchFn: typeof fetch = fetch): Screener | undefined {
|
|
159
|
+
const key = env.RELAY_TYPESAFE_API_KEY
|
|
160
|
+
if (!key) return undefined
|
|
161
|
+
const context = contextMessages(env.RELAY_JEV_CONTEXT_MESSAGES)
|
|
162
|
+
return async (q) => {
|
|
163
|
+
const answer = await ask(key, screenRequest(q, context), SCREEN_RESPONSE, log, fetchFn)
|
|
164
|
+
if (!answer) return undefined
|
|
165
|
+
const a = answer.answers
|
|
166
|
+
const probabilities = { agent: a.agent.noul, other: a.other.noul, answersAgent: a.answers_agent.noul }
|
|
167
|
+
const drop = probabilities.other >= DROP.other && probabilities.agent <= DROP.agent && probabilities.answersAgent <= DROP.answersAgent
|
|
168
|
+
return { drop, probabilities }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 直前の発言の数。0〜30 の整数。空なら既定 */
|
|
173
|
+
function contextMessages(v: string | undefined): number {
|
|
174
|
+
if (!v) return CONTEXT.default
|
|
175
|
+
const n = Number(v)
|
|
176
|
+
if (!/^\d+$/.test(v) || n > CONTEXT.max) throw new Error(`RELAY_JEV_CONTEXT_MESSAGES に指定できるのは 0〜${CONTEXT.max} の整数です(今は ${JSON.stringify(v)})`)
|
|
177
|
+
return n
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 他人宛ての判定の要求。人には p1, p2, … の名前を付け、ID は送らない。Bot の発言は agent にする */
|
|
181
|
+
export function screenRequest(q: ScreenQuery, context: number): unknown {
|
|
182
|
+
const labels = new Map<string, string>()
|
|
183
|
+
const person = (m: ScreenQuery["message"]) => {
|
|
184
|
+
if (m.fromMe) return { person: "agent" }
|
|
185
|
+
let label = labels.get(m.sender)
|
|
186
|
+
if (!label) labels.set(m.sender, (label = `p${labels.size + 1}`))
|
|
187
|
+
return { person: label, name: m.name.slice(0, LIMITS.name) }
|
|
188
|
+
}
|
|
189
|
+
// slice(-0) はすべてを返すので、0 は別に扱う
|
|
190
|
+
const recent = context === 0 ? [] : q.recent.slice(-context)
|
|
191
|
+
return {
|
|
192
|
+
model: MODEL,
|
|
193
|
+
state: {
|
|
194
|
+
chat: { service: q.service, room: q.room.slice(0, LIMITS.name) },
|
|
195
|
+
agent: "An AI assistant that is a member of this group chat. Its own messages appear as the person `agent`.",
|
|
196
|
+
recent_messages: recent.map((m) => ({ ...person(m), text: m.text.slice(0, LIMITS.text) })),
|
|
197
|
+
message: { ...person(q.message), text: q.message.text.slice(0, LIMITS.text) },
|
|
198
|
+
},
|
|
199
|
+
questions: SCREEN_QUESTIONS,
|
|
200
|
+
}
|
|
201
|
+
}
|