@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.
- package/LICENSE +21 -0
- package/README.md +132 -2
- package/bin/agent-chat-relay +22 -0
- package/package.json +65 -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/core/access.ts +240 -0
- package/src/core/instructions.ts +21 -0
- package/src/core/mcp.ts +160 -0
- package/src/core/relay.ts +949 -0
- package/src/core/retention.ts +44 -0
- package/src/harness/config.ts +137 -0
- package/src/harness/harness.ts +254 -0
- package/src/harness/log-file.ts +34 -0
- package/src/harness/pi/config.ts +49 -0
- package/src/harness/pi/state.ts +97 -0
- package/src/harness/pi/tool-approval.ts +70 -0
- package/src/home.ts +67 -0
- package/src/jev.ts +201 -0
- package/src/main.ts +255 -0
- package/src/prompt.ts +12 -0
- package/src/serve-args.ts +56 -0
- package/src/shutdown.ts +52 -0
- package/src/vendor/pi/adapter.js +3223 -0
- package/src/vendor/pi/managed-extension.ts +86 -0
- package/src/vendor/pi/managed-pi-rpc.ts +99 -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,70 @@
|
|
|
1
|
+
// pi 1.5.2 の tool_call と ui.confirm の接続に必要な部分だけを受ける。
|
|
2
|
+
type PiToolCall = { toolName: string; input: unknown }
|
|
3
|
+
type PiApprovalContext = {
|
|
4
|
+
hasUI: boolean
|
|
5
|
+
signal?: AbortSignal
|
|
6
|
+
ui: { confirm(title: string, message: string, options: { timeout: number; signal: AbortSignal }): Promise<boolean> }
|
|
7
|
+
}
|
|
8
|
+
type PiApprovalOptions = { sessionSignal?: AbortSignal; timeoutMs?: number }
|
|
9
|
+
type Blocked = { block: true; reason: string }
|
|
10
|
+
|
|
11
|
+
// 中継の実行承認と同じ 30 分を上限にする(src/core/relay.ts の PERMISSION_TIMEOUT_MS)。
|
|
12
|
+
const MAX_APPROVAL_WAIT_MS = 30 * 60 * 1000
|
|
13
|
+
|
|
14
|
+
function textField(input: unknown, key: string): string | undefined {
|
|
15
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return
|
|
16
|
+
const value: unknown = Object.getOwnPropertyDescriptor(input, key)?.value
|
|
17
|
+
if (typeof value === "string" && value.trim()) return value
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 改行や表示方向を変える文字を、対象の一部として見える形にする。 */
|
|
21
|
+
function quoted(text: string): string {
|
|
22
|
+
return JSON.stringify(text).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (ch) => `\\u{${(ch.codePointAt(0) ?? 0).toString(16)}}`)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 操作と対象だけを ACP の承認依頼に渡す。ツールの入力全体は転送しない。 */
|
|
26
|
+
export function describePiToolCall({ toolName, input }: PiToolCall): { title: string; message: string } {
|
|
27
|
+
if (toolName === "bash") {
|
|
28
|
+
const command = textField(input, "command")
|
|
29
|
+
return { title: "bash:シェルの実行", message: command === undefined ? "コマンドを確認できません" : `コマンド: ${quoted(command)}` }
|
|
30
|
+
}
|
|
31
|
+
if (toolName === "read" || toolName === "write" || toolName === "edit") {
|
|
32
|
+
const path = textField(input, "path")
|
|
33
|
+
const operation = { read: "ファイルの読み取り", write: "ファイルの作成・上書き", edit: "ファイルの編集" }[toolName]
|
|
34
|
+
return { title: `${toolName}:${operation}`, message: path === undefined ? "対象パスを確認できません" : `対象パス: ${quoted(path)}` }
|
|
35
|
+
}
|
|
36
|
+
return { title: "その他のツールの実行", message: `ツール: ${quoted(toolName)}(対象を確認できません)` }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 実行承認を求める。承認を省けるかどうかは、実際の読み取りなどを担う呼び出し側で判断する。 */
|
|
40
|
+
export async function approvePiToolCall(
|
|
41
|
+
event: PiToolCall,
|
|
42
|
+
ctx: PiApprovalContext,
|
|
43
|
+
{ sessionSignal, timeoutMs = MAX_APPROVAL_WAIT_MS }: PiApprovalOptions = {},
|
|
44
|
+
): Promise<Blocked | undefined> {
|
|
45
|
+
const blocked: Blocked = { block: true, reason: "実行が許可されませんでした" }
|
|
46
|
+
const turnSignal = ctx.signal
|
|
47
|
+
if (ctx.hasUI !== true || !turnSignal || turnSignal.aborted || sessionSignal?.aborted) return blocked
|
|
48
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_APPROVAL_WAIT_MS) return blocked
|
|
49
|
+
|
|
50
|
+
const deadline = performance.now() + timeoutMs
|
|
51
|
+
const timeout = new AbortController()
|
|
52
|
+
const signal = AbortSignal.any(sessionSignal ? [turnSignal, sessionSignal, timeout.signal] : [turnSignal, timeout.signal])
|
|
53
|
+
const timer = setTimeout(() => timeout.abort(), timeoutMs)
|
|
54
|
+
const cancelled = Promise.withResolvers<boolean>()
|
|
55
|
+
const cancel = () => cancelled.resolve(false)
|
|
56
|
+
signal.addEventListener("abort", cancel, { once: true })
|
|
57
|
+
try {
|
|
58
|
+
const { title, message } = describePiToolCall(event)
|
|
59
|
+
if (signal.aborted || performance.now() >= deadline) return blocked
|
|
60
|
+
const confirmed = await Promise.race([ctx.ui.confirm(title, message, { timeout: timeoutMs, signal }), cancelled.promise])
|
|
61
|
+
// タイマーのコールバックより先に届いた返事でも、期限後なら採用しない。
|
|
62
|
+
if (confirmed === true && !signal.aborted && performance.now() < deadline) return
|
|
63
|
+
} catch {
|
|
64
|
+
// UI や接続のエラーは拒否と同じ扱いにし、入力を含み得るエラーを出力しない。
|
|
65
|
+
} finally {
|
|
66
|
+
clearTimeout(timer)
|
|
67
|
+
signal.removeEventListener("abort", cancel)
|
|
68
|
+
}
|
|
69
|
+
return blocked
|
|
70
|
+
}
|
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
|
+
}
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// agent-chat-relay のエントリーポイント(ADR 0019)。開発時は scripts/relay.sh から呼ばれる。
|
|
2
|
+
//
|
|
3
|
+
// serve [harness] [--session-id <id>] [--workspace <dir>] [--harness-settings default] [--harness-memory]
|
|
4
|
+
// 中継を起動する(チャットサービスのコネクター、チャット用ツールの MCP、ハーネス)。
|
|
5
|
+
// harness の既定は RELAY_HARNESS、なければ claude。--session-id で、そのセッションを再開する。
|
|
6
|
+
// ほかのフラグは、環境変数 RELAY_WORKSPACE・RELAY_HARNESS_SETTINGS・RELAY_HARNESS_MEMORY の別名(ADR 0017)
|
|
7
|
+
// pair <code> ペアリングのコードを承認する(ルームの登録、DM の相手の許可)
|
|
8
|
+
// access 登録したルームと許可した人の一覧(ID は伏せる)
|
|
9
|
+
// access mode <番号か ID> <mention|exceptOthers|exceptOthersJev|all>
|
|
10
|
+
// 登録したルームの受信モードを変える。番号は access の一覧のもの(ADR 0028、0029)
|
|
11
|
+
// secrets <line|chatwork|discord|typesafe>
|
|
12
|
+
// 秘密情報を、画面に表示せずに入力してもらい、<home>/.env に保存する(typesafe は、承認依頼の送り先を推し、他人宛ての発言を判定する Jev の API キー。ADR 0026、0029)
|
|
13
|
+
// line-tunnel LINE の Webhook を Cloudflare Quick Tunnel で公開する(PATH 上の cloudflared を使う)
|
|
14
|
+
// line-quota LINE の今月の送信数
|
|
15
|
+
//
|
|
16
|
+
// データの置き場は RELAY_HOME(既定は ~/.agent-chat-relay)。秘密情報は <home>/.env(RELAY_ENV_FILE で変えられる)から読み、環境変数を優先する
|
|
17
|
+
|
|
18
|
+
import { randomBytes } from "node:crypto"
|
|
19
|
+
import { dirname, join, resolve } from "node:path"
|
|
20
|
+
import { AccessStore, isReceiveMode, localId, RECEIVE_MODES, serviceOf } from "./core/access.ts"
|
|
21
|
+
import { chatworkFromEnv } from "./connectors/chatwork.ts"
|
|
22
|
+
import { discordFromEnv } from "./connectors/discord.ts"
|
|
23
|
+
import { lineFromEnv } from "./connectors/line.ts"
|
|
24
|
+
import { harnessConfig, harnessOptionsFromEnv } from "./harness/config.ts"
|
|
25
|
+
import { startHarness, type HarnessConfig } from "./harness/harness.ts"
|
|
26
|
+
import { preparePiLaunch } from "./harness/pi/config.ts"
|
|
27
|
+
import { schedulePrune } from "./core/retention.ts"
|
|
28
|
+
import { mcpHandler } from "./core/mcp.ts"
|
|
29
|
+
import { parseServeArgs, type ServeArgs } from "./serve-args.ts"
|
|
30
|
+
import { type ConnectorFactory, type Log, noticeTimingFromEnv, Relay, type Routes } from "./core/relay.ts"
|
|
31
|
+
import { stopper, untilHarnessExits } from "./shutdown.ts"
|
|
32
|
+
import { relayDir, resolveWorkspace } from "./workspace.ts"
|
|
33
|
+
import { jevFromEnv, screenFromEnv } from "./jev.ts"
|
|
34
|
+
import { loadSecrets, relayHome, secretKeys, secretsFile, storeSecrets } from "./home.ts"
|
|
35
|
+
import { readSecret } from "./prompt.ts"
|
|
36
|
+
|
|
37
|
+
/** コネクターの一覧。秘密情報のあるものだけを動かす */
|
|
38
|
+
const CONNECTORS: ConnectorFactory[] = [lineFromEnv, chatworkFromEnv, discordFromEnv]
|
|
39
|
+
|
|
40
|
+
const home = relayHome(process.env)
|
|
41
|
+
const envFile = secretsFile(process.env, home)
|
|
42
|
+
/** このパッケージ(開発時はリポジトリ)の置き場。開発時は、秘密情報(.env・.env.keys)もここに置く */
|
|
43
|
+
const PACKAGE_ROOT = resolve(import.meta.dir, "..")
|
|
44
|
+
const accessPath = join(home, "access.json")
|
|
45
|
+
/** Webhook などのコネクターのエンドポイント。line-tunnel は、ここを公開する */
|
|
46
|
+
const HTTP_PORT = Number(process.env.RELAY_HTTP_PORT ?? 18080)
|
|
47
|
+
|
|
48
|
+
const format = (msg: string, extra?: Record<string, unknown>) => `${new Date().toISOString()} relay: ${msg}${extra ? ` ${JSON.stringify(extra)}` : ""}`
|
|
49
|
+
const log: Log = {
|
|
50
|
+
info: (msg, extra) => console.log(format(msg, extra)),
|
|
51
|
+
error: (msg, extra) => console.error(format(msg, extra)),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function serve(access: AccessStore, args: ServeArgs): Promise<void> {
|
|
55
|
+
// フラグは、同じ意味の環境変数より優先する
|
|
56
|
+
const env = { ...process.env, ...args.env }
|
|
57
|
+
// 不正な指定は、何も起動しないうちに拒否する
|
|
58
|
+
const harnessOptions = harnessOptionsFromEnv(env)
|
|
59
|
+
const noticeTiming = noticeTimingFromEnv(env)
|
|
60
|
+
const attribute = jevFromEnv(env, log)
|
|
61
|
+
const screen = screenFromEnv(env, log)
|
|
62
|
+
// 作業ディレクトリの中は承認なしで読めて返せるので、中継のデータと秘密情報の置き場を含めない(ADR 0017)。
|
|
63
|
+
// 秘密情報のファイル自体も渡すのは、ファイルがシンボリックリンクのとき、実体の場所も含めないため
|
|
64
|
+
const { path: workspace, specified } = resolveWorkspace(env, home, [home, PACKAGE_ROOT, dirname(envFile), envFile])
|
|
65
|
+
if (specified) log.info("管理者が指定した作業ディレクトリを使います", { workspace })
|
|
66
|
+
const { harness: harnessName, sessionId } = args
|
|
67
|
+
const harnessLog = join(home, "harness.log")
|
|
68
|
+
const launch = harnessName === "pi"
|
|
69
|
+
? preparePiLaunch({ home, cwd: workspace, sessionId, stderrPath: harnessLog, options: harnessOptions }, log)
|
|
70
|
+
: (mcp: HarnessConfig["mcp"], onPermission: Parameters<typeof startHarness>[1]) => startHarness({
|
|
71
|
+
...harnessConfig(harnessName, workspace, mcp, harnessOptions, log, specified, env),
|
|
72
|
+
// 秘密情報のファイルに手で足した行(RELAY_ 以外のキー)も渡さない
|
|
73
|
+
withheld: secretKeys(envFile),
|
|
74
|
+
sessionId,
|
|
75
|
+
stderrPath: harnessLog,
|
|
76
|
+
}, onPermission, log)
|
|
77
|
+
const inbox = join(relayDir(workspace), "inbox")
|
|
78
|
+
|
|
79
|
+
// 受け取った添付は 7 日で消す(ADR 0005)
|
|
80
|
+
schedulePrune(inbox, "受け取った添付", log)
|
|
81
|
+
|
|
82
|
+
const relay = new Relay(access, log, workspace, undefined, noticeTiming, attribute, screen)
|
|
83
|
+
if (attribute) log.info("送り手が複数いるターンの承認依頼は、Jev で依頼者を推して送り先を絞ります(ADR 0026)")
|
|
84
|
+
if (!screen && Object.values(access.load().rooms).some((p) => p.receive === "exceptOthersJev")) log.error(NO_JEV_KEY)
|
|
85
|
+
const connectors = CONNECTORS.map((make) => make(process.env, { relay, log, home })).filter((c) => c !== undefined)
|
|
86
|
+
if (connectors.length === 0) {
|
|
87
|
+
throw new Error("チャットサービスの秘密情報がありません。agent-chat-relay secrets line・secrets chatwork・secrets discord のどれかを実行してください(開発時は scripts/relay.sh secrets)")
|
|
88
|
+
}
|
|
89
|
+
for (const c of connectors) relay.addConnector(c)
|
|
90
|
+
|
|
91
|
+
const token = randomBytes(32).toString("base64url")
|
|
92
|
+
const mcp = Bun.serve({
|
|
93
|
+
hostname: "127.0.0.1",
|
|
94
|
+
port: Number(process.env.RELAY_MCP_PORT ?? 18090),
|
|
95
|
+
idleTimeout: 0,
|
|
96
|
+
routes: { "/mcp": mcpHandler(relay, inbox, token) },
|
|
97
|
+
fetch: () => new Response("not found", { status: 404 }),
|
|
98
|
+
})
|
|
99
|
+
// 終了時に閉じるもの
|
|
100
|
+
const closers: (() => void)[] = [() => void mcp.stop()]
|
|
101
|
+
log.info("チャット用ツールのエンドポイントを開きました", { mcp: `${mcp.url.href}mcp` })
|
|
102
|
+
|
|
103
|
+
// コネクターのエンドポイント(Webhook など)は、1 つのサーバーにまとめる。外へはトンネルで公開する。同じパスを 2 つのコネクターが出したら起動しない
|
|
104
|
+
const routes: Routes = {}
|
|
105
|
+
for (const c of connectors) {
|
|
106
|
+
for (const [path, route] of Object.entries(c.routes ?? {})) {
|
|
107
|
+
if (path in routes) throw new Error(`エンドポイントのパスが重なっています: ${path}(${c.label})`)
|
|
108
|
+
routes[path] = route
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (Object.keys(routes).length > 0) {
|
|
112
|
+
const http = Bun.serve({
|
|
113
|
+
hostname: "127.0.0.1",
|
|
114
|
+
port: HTTP_PORT,
|
|
115
|
+
routes,
|
|
116
|
+
fetch: () => new Response("not found", { status: 404 }),
|
|
117
|
+
})
|
|
118
|
+
closers.push(() => void http.stop())
|
|
119
|
+
log.info("コネクターのエンドポイントを開きました", { url: http.url.href, routes: Object.keys(routes) })
|
|
120
|
+
}
|
|
121
|
+
await Promise.all(connectors.map((c) => c.start()))
|
|
122
|
+
for (const c of connectors) closers.push(() => c.stop())
|
|
123
|
+
|
|
124
|
+
const harness = await launch({ url: `${mcp.url.href}mcp`, token }, req => relay.requestPermission(req))
|
|
125
|
+
relay.attach(harness.session)
|
|
126
|
+
|
|
127
|
+
// Ctrl+C は、端末と dotenvx の両方から届くことがある
|
|
128
|
+
const stop = stopper(() => {
|
|
129
|
+
log.info("停止します")
|
|
130
|
+
harness.stop()
|
|
131
|
+
})
|
|
132
|
+
process.on("SIGINT", stop.stop)
|
|
133
|
+
process.on("SIGTERM", stop.stop)
|
|
134
|
+
const code = await untilHarnessExits({ exited: harness.exited, name: harnessName, logPath: harnessLog }, relay, stop, log)
|
|
135
|
+
for (const close of closers) close()
|
|
136
|
+
process.exit(code)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 秘密情報の項目。サービスごとに、入力してもらう順 */
|
|
140
|
+
const SECRETS: Record<string, { intro: string; items: [key: string, label: string][] }> = {
|
|
141
|
+
line: {
|
|
142
|
+
intro: "LINE Developers コンソールの値を入力します。入力内容は画面に表示されません。",
|
|
143
|
+
items: [
|
|
144
|
+
["RELAY_LINE_CHANNEL_SECRET", "[1/2] チャネルシークレット: "],
|
|
145
|
+
["RELAY_LINE_CHANNEL_TOKEN", "[2/2] チャネルアクセストークン(長期): "],
|
|
146
|
+
],
|
|
147
|
+
},
|
|
148
|
+
chatwork: {
|
|
149
|
+
intro: "Bot の Chatwork アカウントの API トークンを入力します。入力内容は画面に表示されません。",
|
|
150
|
+
items: [["RELAY_CHATWORK_API_TOKEN", "API トークン: "]],
|
|
151
|
+
},
|
|
152
|
+
discord: {
|
|
153
|
+
intro: "Discord Developer Portal の Bot のトークンを入力します。入力内容は画面に表示されません。",
|
|
154
|
+
items: [["RELAY_DISCORD_BOT_TOKEN", "Bot のトークン: "]],
|
|
155
|
+
},
|
|
156
|
+
typesafe: {
|
|
157
|
+
intro: "TypeSafe AI の API キー(Jev。承認依頼の送り先を推すのと、他人宛ての発言を判定するのに使う)を入力します。入力内容は画面に表示されません。",
|
|
158
|
+
items: [["RELAY_TYPESAFE_API_KEY", "API キー: "]],
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function secrets(service: string | undefined): void {
|
|
163
|
+
const spec = service ? SECRETS[service] : undefined
|
|
164
|
+
if (!spec) throw new Error(`secrets の対象は ${Object.keys(SECRETS).join("・")} のどれかです`)
|
|
165
|
+
process.stderr.write(`${spec.intro}\n`)
|
|
166
|
+
const values: Record<string, string> = {}
|
|
167
|
+
for (const [key, label] of spec.items) values[key] = readSecret(label).trim()
|
|
168
|
+
storeSecrets(envFile, values)
|
|
169
|
+
console.log(`保存しました: ${envFile}`)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function lineTunnel(): Promise<number> {
|
|
173
|
+
const cloudflared = Bun.which("cloudflared")
|
|
174
|
+
if (!cloudflared) throw new Error("cloudflared が見つかりません。インストールして PATH に置いてください")
|
|
175
|
+
return Bun.spawn([cloudflared, "tunnel", "--no-autoupdate", "--url", `http://127.0.0.1:${HTTP_PORT}`], { stdio: ["inherit", "inherit", "inherit"] }).exited
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function lineQuota(): Promise<void> {
|
|
179
|
+
const token = process.env.RELAY_LINE_CHANNEL_TOKEN
|
|
180
|
+
if (!token) throw new Error("LINE のチャネルアクセストークンがありません。agent-chat-relay secrets line を実行してください")
|
|
181
|
+
for (const path of ["quota", "quota/consumption"]) {
|
|
182
|
+
const res = await fetch(`https://api.line.me/v2/bot/message/${path}`, { headers: { Authorization: `Bearer ${token}` } })
|
|
183
|
+
console.log(`${path}: ${await res.text()}`)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function mask(id: string): string {
|
|
188
|
+
// サービス名と、ローカル ID の先頭 1 文字(LINE の C・R・U、Chatwork の r・u、Discord の c・u)だけを残す
|
|
189
|
+
return `${serviceOf(id)}:${localId(id).slice(0, 1)}…`
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 受信モードが「他人宛てを除く(Jev)」のルームがあるのに、Jev の API キーがないとき(ADR 0029) */
|
|
193
|
+
const NO_JEV_KEY = "Jev の API キーがないため、受信モードが「他人宛てを除く(Jev)」のルームは、「他人宛てを除く」と同じに動きます。agent-chat-relay secrets typesafe で保存してください"
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* access:登録したルームと許可した人の一覧。ルームには番号を付ける(ID は伏せるため)。
|
|
197
|
+
* access mode <番号か ID> <受信モード>:登録したルームの受信モードを変える(ADR 0028)
|
|
198
|
+
*/
|
|
199
|
+
function accessCommand(access: AccessStore, args: string[]): void {
|
|
200
|
+
const a = access.load()
|
|
201
|
+
const rooms = Object.entries(a.rooms)
|
|
202
|
+
if (args[0] === "mode") {
|
|
203
|
+
const [target, mode] = args.slice(1)
|
|
204
|
+
if (!target || !isReceiveMode(mode)) throw new Error(`usage: agent-chat-relay access mode <ルームの番号か ID> <${Object.keys(RECEIVE_MODES).join("|")}>`)
|
|
205
|
+
const room = /^[1-9][0-9]*$/.test(target) ? rooms[Number(target) - 1]?.[0] : target
|
|
206
|
+
if (!room) throw new Error(`${target} 番のルームはありません。access で番号を確かめてください`)
|
|
207
|
+
access.setReceive(room, mode)
|
|
208
|
+
console.log(`受信モードを変えました: ${mask(room)}(${RECEIVE_MODES[mode]})`)
|
|
209
|
+
// 値は読まずに、キーがあるかだけを見る(秘密情報のファイルは暗号化していることがある)
|
|
210
|
+
if (mode === "exceptOthersJev" && !process.env.RELAY_TYPESAFE_API_KEY && !secretKeys(envFile).includes("RELAY_TYPESAFE_API_KEY")) console.error(NO_JEV_KEY)
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
console.log("ルーム:")
|
|
214
|
+
for (const [i, [room, p]] of rooms.entries()) console.log(` ${i + 1}. ${mask(room)} ${RECEIVE_MODES[p.receive]}${p.allowFrom.length ? ` 許可 ${p.allowFrom.length} 人` : ""}`)
|
|
215
|
+
console.log("DM と実行承認を許可した人:")
|
|
216
|
+
for (const u of a.allowFrom) console.log(` ${mask(u)}`)
|
|
217
|
+
console.log(`ペアリング待ち: ${Object.keys(a.pending).length} 件`)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function main(): Promise<void> {
|
|
221
|
+
const [cmd, ...rest] = process.argv.slice(2)
|
|
222
|
+
const arg = rest[0]
|
|
223
|
+
const access = new AccessStore(accessPath)
|
|
224
|
+
// 秘密情報は、使うコマンドでだけ読む。値は、まだない環境変数にだけ設定する
|
|
225
|
+
if (cmd === "serve" || cmd === "line-quota") loadSecrets(envFile, process.env, (msg) => log.error(msg))
|
|
226
|
+
switch (cmd) {
|
|
227
|
+
case "serve":
|
|
228
|
+
// 不正な引数は、何も起動しないうちに拒否する
|
|
229
|
+
return serve(access, parseServeArgs(rest, process.env.RELAY_HARNESS ?? "claude"))
|
|
230
|
+
case "secrets":
|
|
231
|
+
return secrets(arg)
|
|
232
|
+
case "line-tunnel":
|
|
233
|
+
process.exit(await lineTunnel())
|
|
234
|
+
return
|
|
235
|
+
case "line-quota":
|
|
236
|
+
return lineQuota()
|
|
237
|
+
case "pair": {
|
|
238
|
+
if (!arg) throw new Error("usage: agent-chat-relay pair <code>")
|
|
239
|
+
const p = access.approve(arg)
|
|
240
|
+
console.log(p.kind === "room" ? `ルームを登録しました: ${mask(p.target)}(受信モード:メンション時)` : `DM の相手を許可しました: ${mask(p.target)}(実行承認の依頼も届きます)`)
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
case "access":
|
|
244
|
+
return accessCommand(access, rest)
|
|
245
|
+
default:
|
|
246
|
+
throw new Error(
|
|
247
|
+
`usage: agent-chat-relay serve [harness] [--session-id <id>] [--workspace <dir>] [--harness-settings default] [--harness-memory] | pair <code> | access [mode <番号か ID> <${Object.keys(RECEIVE_MODES).join("|")}>] | secrets <line|chatwork|discord|typesafe> | line-tunnel | line-quota`,
|
|
248
|
+
)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
main().catch((err) => {
|
|
253
|
+
console.error(`relay: ${err instanceof Error ? err.message : String(err)}`)
|
|
254
|
+
process.exit(1)
|
|
255
|
+
})
|
package/src/prompt.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// 秘密情報を、画面に表示せずに入力してもらう。コマンドの引数に載せない(ps やシェルの履歴に残る)ため
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 1 行を読む。bash の read -s に任せる(表示を消すことと、Ctrl+C で中断したときに端末を元に戻すことを、bash がする)。
|
|
5
|
+
* 端末でなければ(パイプなど)、標準入力の次の行を読む。値はパイプで受け取り、引数には載せない
|
|
6
|
+
*/
|
|
7
|
+
export function readSecret(label: string): string {
|
|
8
|
+
process.stderr.write(label)
|
|
9
|
+
const r = Bun.spawnSync(["bash", "-c", 'read -rs v; echo >&2; printf %s "$v"'], { stdin: "inherit", stdout: "pipe", stderr: "inherit" })
|
|
10
|
+
if (r.signalCode || r.exitCode === 130) throw new Error("中止しました")
|
|
11
|
+
return r.stdout.toString().replace(/\r$/, "")
|
|
12
|
+
}
|