@howaboua/pi-shepherdr 0.2.9 → 0.2.10
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 +10 -0
- package/README.md +35 -1
- package/index.ts +28 -5
- package/package.json +12 -9
- package/src/agents-discovery.ts +2 -2
- package/src/agents-spawn.ts +6 -0
- package/src/agents-tool.ts +3 -0
- package/src/board/archive.ts +77 -0
- package/src/board/config.ts +108 -0
- package/src/board/contract.ts +181 -0
- package/src/board/host.ts +413 -0
- package/src/board/identity.ts +155 -0
- package/src/board/paging.ts +55 -0
- package/src/board/protocol.ts +68 -0
- package/src/board/queries.ts +176 -0
- package/src/board/response.ts +56 -0
- package/src/board/settings.ts +98 -0
- package/src/board/store.ts +327 -0
- package/src/board/tool.ts +23 -0
- package/src/board/turns.ts +100 -0
- package/src/controller.ts +47 -3
- package/src/delivery.ts +8 -1
- package/src/messages.ts +2 -2
- package/src/peer-inbox.ts +7 -4
- package/src/shared-context.ts +16 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @howaboua/pi-shepherdr
|
|
2
2
|
|
|
3
|
+
## 0.2.10
|
|
4
|
+
|
|
5
|
+
- Requires Pi 1.0.0 or later.
|
|
6
|
+
|
|
7
|
+
- Added optional agent-tree message boards with channels, replies, search, subscriptions and persistent folder-local history. Boards require Node.js 22.13 or later.
|
|
8
|
+
- Added session, exact-folder and global board settings under `/herdr board`. Board notifications reach running turns without waking idle agents.
|
|
9
|
+
- Board history is stored as plaintext in `.pi/agent-message-board.sqlite` and remains after disabling boards. Keep this archive out of version control and restricted to its intended readers.
|
|
10
|
+
- Agent messages and worker reports now respect Codex Conversion's saved-Notes idle rollover before waking an idle agent.
|
|
11
|
+
- Updated coordination guidance to favor asynchronous implementation workers and ending the controller turn when only waiting. Blocked workers are directed to a question-asking tool instead of peer messages, and final replies replace duplicate completion reports.
|
|
12
|
+
|
|
3
13
|
## 0.2.9
|
|
4
14
|
|
|
5
15
|
- Non-blocking agent guidance now explicitly permits continued conversation, other work or an immediate reply. Completion and blockage arrive even after a reply, without polling or sleep waits.
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ With Pi Codex's compatible custom developer-message API active, asynchronous wor
|
|
|
14
14
|
pi install npm:@howaboua/pi-shepherdr
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
Requires Pi 0.
|
|
17
|
+
Requires Pi 1.0.0 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
20
|
herdr integration install pi
|
|
@@ -83,6 +83,40 @@ Idle messages start a prepared user turn. Messages arriving during a run use ste
|
|
|
83
83
|
|
|
84
84
|
For `answer` inside Code or Notebook Mode, update Pi Ask on workers together with Shepherdr on controllers.
|
|
85
85
|
|
|
86
|
+
## Message board
|
|
87
|
+
|
|
88
|
+
The board is off by default. In the root session, run `/herdr board` to open its settings menu. Choose a session override, a remembered folder default, or **Enable globally**. Disabling the board hides its tool and stops notifications without deleting history. Board storage requires Node.js 22.13 or newer. Pi Codex Conversion is not required.
|
|
89
|
+
|
|
90
|
+
Session overrides survive resume but do not carry into new root sessions or forks. Folder settings apply only to sessions launched in that exact folder, not its child directories. Global enablement is a separate setting. Precedence is session, folder, then global. Bound children inherit their root's choice even with a different working directory. Orchestration mode and shared notes remain independent.
|
|
91
|
+
|
|
92
|
+
The menu saves folder settings in `<launch-folder>/.pi/pi-shepherdr.json`:
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
{ "board": { "enabled": true } }
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The extension creates `pi-shepherdr.json` in Pi's global agent directory with this default:
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{ "board": { "enabledGlobally": false } }
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The agent directory defaults to `~/.pi/agent` and respects `PI_CODING_AGENT_DIR`. Enabling a board in the home folder writes `~/.pi/pi-shepherdr.json`, not the global setting. It does not enable boards in other folders. Storage location never implies activation scope. JSON edits are picked up before the next user turn or on `/reload`; invalid configuration disables the board with an explicit error.
|
|
105
|
+
|
|
106
|
+
Command equivalents are `/herdr board on` or `off` for this session, `/herdr board on folder` or `off folder` for a folder default, and `/herdr board on global` or `off global` for the global default. `/herdr board inherit` clears the session override; `/herdr board inherit folder` clears the folder override. A session override can mask changes to either default. Outside the TUI, `/herdr board` reports status and archive location.
|
|
107
|
+
|
|
108
|
+
Agents call `board` with `action: "help"` to discover channels, posts, replies, search, subscriptions and bounded reads. Code and Notebook Mode use `tools.board`. Agents choose when discussions are useful. Enabling the board, starting sessions, reading history and spawning children do not create an empty board. The first successful channel creation or post to a new channel creates it.
|
|
109
|
+
|
|
110
|
+
Results fit 8,000 serialized UTF-8 bytes, including JSON escaping and metadata. Reads may return smaller pages or text slices than requested. Continue with the returned cursor or `next_offset_chars`. A search with `after_message_id` requires a post in the selected board, even before an archive exists.
|
|
111
|
+
|
|
112
|
+
One archive at `<owning-folder>/.pi/agent-message-board.sqlite` retains all boards for that folder. Each root Pi session has an isolated board; resume keeps it and new root sessions get separate boards. Children spawned while the board is enabled inherit its location and board ID even with another working directory. The spawn result's `boardAgent` is their address for subscriptions and explicit notifications, distinct from a pane or shared-notes identity. Independently started agents, existing `assign` targets and children spawned while it is off do not join automatically. Board identity is independent of shared notes and `share_context`.
|
|
113
|
+
|
|
114
|
+
Calls default to the current board. `list_boards` lists saved boards, and `board_id` on read and search actions browses their history. Writes and subscriptions always target the current board. There is no task assignment, post editing or board deletion tool. These archives contain discussion text; keep them out of version control and do not share them with users who should not read that text.
|
|
115
|
+
|
|
116
|
+
Posting subscribes its author to discussion replies unless the author explicitly unsubscribed. Channel subscriptions concern only new first posts. Explicit notification targets receive a one-time preview without subscribing. Notifications reach running turns only: no waking idle agents and no queued offline notices. Full text remains available through reads.
|
|
117
|
+
|
|
118
|
+
Child board calls use the owning Pi sessions and existing SSH connections, not a separately provisioned service. The root and intermediate controllers must be running as processes, but need not be in an active model turn. Resume the owner and use `/herdr connect` after a lost connection. Future root sessions can browse the archive even when the old owner is offline. A fork starts a new independent identity. Profiles selecting an existing session cannot bind to an enabled board through `spawn`; use `assign` without board membership instead.
|
|
119
|
+
|
|
86
120
|
## Shared notes and history
|
|
87
121
|
|
|
88
122
|
With Pi Codex Conversion 3.0.40 or newer and notes-based continuity, enable **Share subagent context** under `/codex context` in the controller. It is off by default. Shared `spawn` gives each child a unique context identity before its first turn; `contextAgent` in the result identifies its notes and history. Shared nested spawns stay in the same family. Turning sharing off affects new spawns only; existing identity survives resume. `assign` and independently started agents remain unchanged. Older compatible Conversion versions keep ordinary delegation without sharing.
|
package/index.ts
CHANGED
|
@@ -2,6 +2,9 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
2
2
|
import registerPackageChangelog from "./changelog.js";
|
|
3
3
|
import { isBlockingAgentsCall } from "./src/agents-contract.js";
|
|
4
4
|
import { createAgentsTool } from "./src/agents-tool.js";
|
|
5
|
+
import { ensureBoardConfig } from "./src/board/config.js";
|
|
6
|
+
import { AgentBoard } from "./src/board/host.js";
|
|
7
|
+
import { createBoardTool } from "./src/board/tool.js";
|
|
5
8
|
import { registerAgentController } from "./src/controller.js";
|
|
6
9
|
import { registerDeveloperDelivery } from "./src/delivery.js";
|
|
7
10
|
import { AgentFleet } from "./src/fleet.js";
|
|
@@ -17,22 +20,28 @@ export default async function shepherdrExtension(
|
|
|
17
20
|
pi: ExtensionAPI,
|
|
18
21
|
): Promise<void> {
|
|
19
22
|
registerPackageChangelog(pi);
|
|
23
|
+
ensureBoardConfig();
|
|
20
24
|
await installAgentProfiles();
|
|
21
25
|
await registerDeveloperDelivery(pi);
|
|
22
26
|
registerPeerInbox(pi);
|
|
23
27
|
const fleet = new AgentFleet(pi);
|
|
24
|
-
const
|
|
25
|
-
const
|
|
28
|
+
const board = new AgentBoard(pi, fleet);
|
|
29
|
+
const sharedContext = await registerSharedAgentContext(pi, fleet, board);
|
|
30
|
+
const tool = createAgentsTool(fleet, sharedContext, board);
|
|
31
|
+
const boardTool = createBoardTool(board);
|
|
26
32
|
|
|
27
33
|
registerAgentEventRenderer(pi);
|
|
28
34
|
pi.registerTool(tool);
|
|
29
|
-
|
|
30
|
-
|
|
35
|
+
pi.registerTool(boardTool);
|
|
36
|
+
await registerAgentsInCodeMode(pi, tool, boardTool, board);
|
|
37
|
+
registerAgentController(pi, fleet, board);
|
|
31
38
|
}
|
|
32
39
|
|
|
33
40
|
async function registerAgentsInCodeMode(
|
|
34
41
|
pi: ExtensionAPI,
|
|
35
42
|
tool: ReturnType<typeof createAgentsTool>,
|
|
43
|
+
boardTool: ReturnType<typeof createBoardTool>,
|
|
44
|
+
board: AgentBoard,
|
|
36
45
|
) {
|
|
37
46
|
try {
|
|
38
47
|
const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
|
|
@@ -44,7 +53,21 @@ async function registerAgentsInCodeMode(
|
|
|
44
53
|
'await tools.agents({ action: "help" }) // Persistent agents; first call alone',
|
|
45
54
|
}),
|
|
46
55
|
]);
|
|
47
|
-
|
|
56
|
+
const boardRegistration = registerCodeModeExtensionTools(
|
|
57
|
+
pi,
|
|
58
|
+
() => [
|
|
59
|
+
adaptToolForCodeMode(boardTool, {
|
|
60
|
+
usage:
|
|
61
|
+
'await tools.board({ action: "help" }) // Shared discussion archive',
|
|
62
|
+
}),
|
|
63
|
+
],
|
|
64
|
+
{ isActive: (ctx) => board.enabled(ctx) },
|
|
65
|
+
);
|
|
66
|
+
board.setToolRefresh(() => boardRegistration.refresh());
|
|
67
|
+
pi.on("session_shutdown", () => {
|
|
68
|
+
registration.unregister();
|
|
69
|
+
boardRegistration.unregister();
|
|
70
|
+
});
|
|
48
71
|
return registration;
|
|
49
72
|
} catch (error) {
|
|
50
73
|
if (isMissingCodeModeExtension(error)) return undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-shepherdr",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "Persistent blocking and asynchronous Pi agents through Herdr.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -43,10 +43,10 @@
|
|
|
43
43
|
"pack:dry": "npm pack --dry-run"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
|
-
"@howaboua/pi-codex-conversion": ">=3.0.
|
|
47
|
-
"@earendil-works/pi-ai": ">=0.
|
|
48
|
-
"@earendil-works/pi-coding-agent": ">=0.
|
|
49
|
-
"@earendil-works/pi-tui": ">=0.
|
|
46
|
+
"@howaboua/pi-codex-conversion": ">=3.0.43",
|
|
47
|
+
"@earendil-works/pi-ai": ">=1.0.0",
|
|
48
|
+
"@earendil-works/pi-coding-agent": ">=1.0.0",
|
|
49
|
+
"@earendil-works/pi-tui": ">=1.0.0",
|
|
50
50
|
"typebox": "*"
|
|
51
51
|
},
|
|
52
52
|
"peerDependenciesMeta": {
|
|
@@ -54,12 +54,15 @@
|
|
|
54
54
|
"optional": true
|
|
55
55
|
}
|
|
56
56
|
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"unicode-case-folding": "1.1.2"
|
|
59
|
+
},
|
|
57
60
|
"devDependencies": {
|
|
58
|
-
"@howaboua/pi-codex-conversion": "3.0.
|
|
61
|
+
"@howaboua/pi-codex-conversion": "3.0.43",
|
|
59
62
|
"@biomejs/biome": "^2.5.10",
|
|
60
|
-
"@earendil-works/pi-ai": "0.
|
|
61
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
62
|
-
"@earendil-works/pi-tui": "0.
|
|
63
|
+
"@earendil-works/pi-ai": "1.0.0",
|
|
64
|
+
"@earendil-works/pi-coding-agent": "1.0.0",
|
|
65
|
+
"@earendil-works/pi-tui": "1.0.0",
|
|
63
66
|
"@types/node": "^26.2.0",
|
|
64
67
|
"typebox": "1.3.18",
|
|
65
68
|
"typescript": "^7.0.2"
|
package/src/agents-discovery.ts
CHANGED
|
@@ -46,10 +46,10 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
|
|
|
46
46
|
label: "2-3 words; tab/session",
|
|
47
47
|
answers: "[{selections?:string[],other?:string,comment?:string}]",
|
|
48
48
|
ask_id: "Exact pending Ask ID",
|
|
49
|
-
send: "
|
|
49
|
+
send: "Only for a needed answer or to change the recipient's current work. No courtesy updates, acknowledgements or completion echoes. Can wake idle agents; no wait/watch",
|
|
50
50
|
assign: "Delegate a task to an existing agent",
|
|
51
51
|
blocking:
|
|
52
|
-
"spawn/assign default true; profile blocking overrides spawn
|
|
52
|
+
"spawn/assign default true; profile blocking overrides spawn. Fan out independent implementation workers with false; end your turn when only waiting. Completion/blockage arrives after you reply; no polling or sleep waits",
|
|
53
53
|
share_context:
|
|
54
54
|
"Profile false isolates notes/history; otherwise follows controller sharing setting",
|
|
55
55
|
watch:
|
package/src/agents-spawn.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
settlementResult,
|
|
15
15
|
toolResult,
|
|
16
16
|
} from "./agents-work.js";
|
|
17
|
+
import type { AgentBoard } from "./board/host.js";
|
|
17
18
|
import type { AgentFleet, ConnectedMachine } from "./fleet.js";
|
|
18
19
|
import { isDispatchRejected } from "./herdr-client.js";
|
|
19
20
|
import {
|
|
@@ -46,6 +47,7 @@ export async function spawnAgent(
|
|
|
46
47
|
onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
|
|
47
48
|
sharedContext: SharedAgentContext,
|
|
48
49
|
ctx: ExtensionContext,
|
|
50
|
+
board: AgentBoard,
|
|
49
51
|
) {
|
|
50
52
|
const profiles = await loadAgentProfiles();
|
|
51
53
|
const profileName = required(params.agent_type, "agent_type");
|
|
@@ -111,6 +113,7 @@ export async function spawnAgent(
|
|
|
111
113
|
profile.shareContext === false
|
|
112
114
|
? undefined
|
|
113
115
|
: await sharedContext.prepare(ctx, runtime, name, agentArgs);
|
|
116
|
+
const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
|
|
114
117
|
const started = await startAgent(
|
|
115
118
|
runtime.client,
|
|
116
119
|
startParams,
|
|
@@ -122,8 +125,10 @@ export async function spawnAgent(
|
|
|
122
125
|
let promptAccepted = false;
|
|
123
126
|
let dispatch;
|
|
124
127
|
let shared: { agentName?: string; warning?: string } | undefined;
|
|
128
|
+
let boardAgent: string | undefined;
|
|
125
129
|
const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
|
|
126
130
|
try {
|
|
131
|
+
boardAgent = await boardBinding?.accept(started.agent);
|
|
127
132
|
shared = await sharing?.accept(started.agent);
|
|
128
133
|
dispatch = await dispatchAgentWork(
|
|
129
134
|
runtime,
|
|
@@ -154,6 +159,7 @@ export async function spawnAgent(
|
|
|
154
159
|
}
|
|
155
160
|
return toolResult(
|
|
156
161
|
{
|
|
162
|
+
...(boardAgent ? { boardAgent } : {}),
|
|
157
163
|
...(shared?.agentName ? { contextAgent: shared.agentName } : {}),
|
|
158
164
|
...(dispatch.command
|
|
159
165
|
? {
|
package/src/agents-tool.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
settlementResult,
|
|
21
21
|
toolResult,
|
|
22
22
|
} from "./agents-work.js";
|
|
23
|
+
import type { AgentBoard } from "./board/host.js";
|
|
23
24
|
import type { AgentFleet } from "./fleet.js";
|
|
24
25
|
import { resolvePiAgent } from "./herdr.js";
|
|
25
26
|
import { attributeAgentPrompt, modelAsk } from "./messages.js";
|
|
@@ -28,6 +29,7 @@ import type { SharedAgentContext } from "./shared-context.js";
|
|
|
28
29
|
export function createAgentsTool(
|
|
29
30
|
fleet: AgentFleet,
|
|
30
31
|
sharedContext: SharedAgentContext,
|
|
32
|
+
board: AgentBoard,
|
|
31
33
|
) {
|
|
32
34
|
return defineTool({
|
|
33
35
|
name: "agents",
|
|
@@ -59,6 +61,7 @@ export function createAgentsTool(
|
|
|
59
61
|
update,
|
|
60
62
|
sharedContext,
|
|
61
63
|
ctx,
|
|
64
|
+
board,
|
|
62
65
|
);
|
|
63
66
|
}
|
|
64
67
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import type { BoardParams } from "./contract.js";
|
|
3
|
+
import { agentPath, MUTATIONS } from "./contract.js";
|
|
4
|
+
import type { BoardBinding } from "./identity.js";
|
|
5
|
+
import { page } from "./paging.js";
|
|
6
|
+
import { boundedBoardRead, checkMutationBudget } from "./response.js";
|
|
7
|
+
|
|
8
|
+
export async function executeArchive(
|
|
9
|
+
caller: BoardBinding,
|
|
10
|
+
memberNames: readonly string[],
|
|
11
|
+
params: BoardParams,
|
|
12
|
+
requestId: string,
|
|
13
|
+
) {
|
|
14
|
+
const write = MUTATIONS.has(params.action);
|
|
15
|
+
if (write) checkMutationBudget(caller.agentName, params);
|
|
16
|
+
let storage: typeof import("./store.js");
|
|
17
|
+
try {
|
|
18
|
+
storage = await import("./store.js");
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (
|
|
21
|
+
error instanceof Error &&
|
|
22
|
+
"code" in error &&
|
|
23
|
+
error.code === "ERR_UNKNOWN_BUILTIN_MODULE"
|
|
24
|
+
)
|
|
25
|
+
throw new Error(
|
|
26
|
+
"Message boards require Node.js 22.13 or newer with SQLite support",
|
|
27
|
+
{ cause: error },
|
|
28
|
+
);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
storage.validateMutation(params);
|
|
32
|
+
if (write) {
|
|
33
|
+
for (const value of [
|
|
34
|
+
...(params.agents_to_notify ?? []),
|
|
35
|
+
...(params.target_agent === undefined ? [] : [params.target_agent]),
|
|
36
|
+
]) {
|
|
37
|
+
const target = agentPath(value, caller.agentName);
|
|
38
|
+
if (!memberNames.includes(target))
|
|
39
|
+
throw new Error(`Agent not bound to this tree: ${target}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const exists = existsSync(caller.databasePath);
|
|
43
|
+
if (
|
|
44
|
+
!exists &&
|
|
45
|
+
params.action === "search_posts" &&
|
|
46
|
+
params.after_message_id !== undefined
|
|
47
|
+
)
|
|
48
|
+
throw new Error("Post not found in this board");
|
|
49
|
+
if (
|
|
50
|
+
!exists &&
|
|
51
|
+
(!write ||
|
|
52
|
+
(params.action !== "create_channel" &&
|
|
53
|
+
params.new_channel_name === undefined))
|
|
54
|
+
) {
|
|
55
|
+
if (["get_channels", "search_posts", "list_boards"].includes(params.action))
|
|
56
|
+
return { value: page([], params), recipients: [] };
|
|
57
|
+
throw new Error("This board has no channels or posts yet");
|
|
58
|
+
}
|
|
59
|
+
const store = new storage.BoardStore(caller.databasePath, write);
|
|
60
|
+
try {
|
|
61
|
+
const scope = {
|
|
62
|
+
boardId: caller.boardId,
|
|
63
|
+
rootSessionId: caller.rootSessionId,
|
|
64
|
+
ownerFolder: caller.ownerFolder,
|
|
65
|
+
callerSessionId: caller.sessionId,
|
|
66
|
+
agentName: caller.agentName,
|
|
67
|
+
members: memberNames,
|
|
68
|
+
};
|
|
69
|
+
return write
|
|
70
|
+
? store.execute(scope, params, requestId)
|
|
71
|
+
: boundedBoardRead(params, (request) =>
|
|
72
|
+
store.execute(scope, request, requestId),
|
|
73
|
+
);
|
|
74
|
+
} finally {
|
|
75
|
+
store.close();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readFileSync,
|
|
6
|
+
renameSync,
|
|
7
|
+
rmSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { dirname, resolve } from "node:path";
|
|
11
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
|
|
13
|
+
const CONFIG_FILE = "pi-shepherdr.json";
|
|
14
|
+
export type BoardScope = "session" | "folder" | "global";
|
|
15
|
+
|
|
16
|
+
function object(value: unknown): value is Record<string, unknown> {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function readDocument(path: string): Record<string, unknown> {
|
|
21
|
+
if (!existsSync(path)) return {};
|
|
22
|
+
try {
|
|
23
|
+
const value: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
24
|
+
if (!object(value)) throw new Error("configuration must be an object");
|
|
25
|
+
if (value["board"] !== undefined && !object(value["board"]))
|
|
26
|
+
throw new Error("board must be an object");
|
|
27
|
+
return value;
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw new Error(`Could not read ${path}: ${String(error)}`, {
|
|
30
|
+
cause: error,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readEnabled(path: string, scope: "folder" | "global") {
|
|
36
|
+
const document = readDocument(path);
|
|
37
|
+
const board = object(document["board"]) ? document["board"] : {};
|
|
38
|
+
const field = scope === "global" ? "enabledGlobally" : "enabled";
|
|
39
|
+
const wrongField = scope === "global" ? "enabled" : "enabledGlobally";
|
|
40
|
+
if (wrongField in board)
|
|
41
|
+
throw new Error(`${path}: use board.${field} for ${scope} enablement`);
|
|
42
|
+
const value = board[field];
|
|
43
|
+
if (value !== undefined && typeof value !== "boolean")
|
|
44
|
+
throw new Error(`${path}: board.${field} must be a boolean`);
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function boardConfigPaths(folder: string) {
|
|
49
|
+
return {
|
|
50
|
+
global: resolve(getAgentDir(), CONFIG_FILE),
|
|
51
|
+
folder: resolve(folder, ".pi", CONFIG_FILE),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function ensureBoardConfig() {
|
|
56
|
+
const path = resolve(getAgentDir(), CONFIG_FILE);
|
|
57
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
58
|
+
try {
|
|
59
|
+
writeFileSync(
|
|
60
|
+
path,
|
|
61
|
+
`${JSON.stringify({ board: { enabledGlobally: false } }, null, 2)}\n`,
|
|
62
|
+
{
|
|
63
|
+
flag: "wx",
|
|
64
|
+
mode: 0o600,
|
|
65
|
+
},
|
|
66
|
+
);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function readBoardConfig(folder: string) {
|
|
74
|
+
const paths = boardConfigPaths(folder);
|
|
75
|
+
return {
|
|
76
|
+
paths,
|
|
77
|
+
folder: readEnabled(paths.folder, "folder"),
|
|
78
|
+
global: readEnabled(paths.global, "global") ?? false,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function writeBoardConfig(
|
|
83
|
+
folder: string,
|
|
84
|
+
scope: "folder" | "global",
|
|
85
|
+
enabled: boolean | undefined,
|
|
86
|
+
) {
|
|
87
|
+
if (scope === "global" && enabled === undefined)
|
|
88
|
+
throw new Error("Global enablement must be on or off");
|
|
89
|
+
const path = boardConfigPaths(folder)[scope];
|
|
90
|
+
readEnabled(path, scope);
|
|
91
|
+
const document = readDocument(path);
|
|
92
|
+
const board = object(document["board"]) ? { ...document["board"] } : {};
|
|
93
|
+
const field = scope === "global" ? "enabledGlobally" : "enabled";
|
|
94
|
+
if (enabled === undefined) delete board[field];
|
|
95
|
+
else board[field] = enabled;
|
|
96
|
+
if (enabled === undefined && !existsSync(path)) return;
|
|
97
|
+
document["board"] = board;
|
|
98
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
99
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
100
|
+
try {
|
|
101
|
+
writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\n`, {
|
|
102
|
+
mode: 0o600,
|
|
103
|
+
});
|
|
104
|
+
renameSync(temporary, path);
|
|
105
|
+
} finally {
|
|
106
|
+
rmSync(temporary, { force: true });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { StringEnum, Type } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { Static } from "typebox";
|
|
3
|
+
import { Check } from "typebox/value";
|
|
4
|
+
|
|
5
|
+
const BOARD_ACTIONS = [
|
|
6
|
+
"help",
|
|
7
|
+
"list_boards",
|
|
8
|
+
"create_channel",
|
|
9
|
+
"get_channels",
|
|
10
|
+
"post",
|
|
11
|
+
"list_threads",
|
|
12
|
+
"read_thread",
|
|
13
|
+
"read_post",
|
|
14
|
+
"search_posts",
|
|
15
|
+
"subscribe",
|
|
16
|
+
"unsubscribe",
|
|
17
|
+
] as const;
|
|
18
|
+
export const BoardParameters = Type.Object({
|
|
19
|
+
action: StringEnum(BOARD_ACTIONS),
|
|
20
|
+
});
|
|
21
|
+
const positive = Type.Optional(
|
|
22
|
+
Type.Integer({ minimum: 1, maximum: 0xffffffff }),
|
|
23
|
+
);
|
|
24
|
+
const string = Type.Optional(Type.String());
|
|
25
|
+
const Request = Type.Object(
|
|
26
|
+
{
|
|
27
|
+
action: StringEnum(BOARD_ACTIONS),
|
|
28
|
+
channel_name: string,
|
|
29
|
+
new_channel_name: string,
|
|
30
|
+
thread_id: string,
|
|
31
|
+
message_id: string,
|
|
32
|
+
text: string,
|
|
33
|
+
query: string,
|
|
34
|
+
author: string,
|
|
35
|
+
target_agent: string,
|
|
36
|
+
after_message_id: string,
|
|
37
|
+
board_id: string,
|
|
38
|
+
cursor: string,
|
|
39
|
+
subscribe: Type.Optional(Type.Boolean()),
|
|
40
|
+
recent_first: Type.Optional(Type.Boolean()),
|
|
41
|
+
sort: Type.Optional(StringEnum(["created", "activity"])),
|
|
42
|
+
limit: positive,
|
|
43
|
+
max_chars_per_post: positive,
|
|
44
|
+
limit_chars: positive,
|
|
45
|
+
offset_chars: Type.Optional(
|
|
46
|
+
Type.Integer({ minimum: 0, maximum: 0xffffffff }),
|
|
47
|
+
),
|
|
48
|
+
agents_to_notify: Type.Optional(
|
|
49
|
+
Type.Array(Type.String(), { maxItems: 256 }),
|
|
50
|
+
),
|
|
51
|
+
},
|
|
52
|
+
{ additionalProperties: false },
|
|
53
|
+
);
|
|
54
|
+
export type BoardParams = Static<typeof Request>;
|
|
55
|
+
export type BoardAction = BoardParams["action"];
|
|
56
|
+
export const MUTATIONS = new Set<BoardAction>([
|
|
57
|
+
"create_channel",
|
|
58
|
+
"post",
|
|
59
|
+
"subscribe",
|
|
60
|
+
"unsubscribe",
|
|
61
|
+
]);
|
|
62
|
+
const paging = ["limit", "cursor"];
|
|
63
|
+
const reads = ["board_id"];
|
|
64
|
+
const fields: Record<BoardAction, string[]> = {
|
|
65
|
+
help: [],
|
|
66
|
+
list_boards: paging,
|
|
67
|
+
create_channel: ["channel_name", "subscribe"],
|
|
68
|
+
get_channels: ["query", "recent_first", ...paging, ...reads],
|
|
69
|
+
post: [
|
|
70
|
+
"text",
|
|
71
|
+
"channel_name",
|
|
72
|
+
"new_channel_name",
|
|
73
|
+
"thread_id",
|
|
74
|
+
"agents_to_notify",
|
|
75
|
+
],
|
|
76
|
+
list_threads: [
|
|
77
|
+
"channel_name",
|
|
78
|
+
"sort",
|
|
79
|
+
"recent_first",
|
|
80
|
+
"max_chars_per_post",
|
|
81
|
+
...paging,
|
|
82
|
+
...reads,
|
|
83
|
+
],
|
|
84
|
+
read_thread: ["thread_id", "max_chars_per_post", ...paging, ...reads],
|
|
85
|
+
read_post: ["message_id", "offset_chars", "limit_chars", ...reads],
|
|
86
|
+
search_posts: [
|
|
87
|
+
"channel_name",
|
|
88
|
+
"query",
|
|
89
|
+
"author",
|
|
90
|
+
"after_message_id",
|
|
91
|
+
"max_chars_per_post",
|
|
92
|
+
...paging,
|
|
93
|
+
...reads,
|
|
94
|
+
],
|
|
95
|
+
subscribe: ["channel_name", "thread_id", "target_agent"],
|
|
96
|
+
unsubscribe: ["channel_name", "thread_id", "target_agent"],
|
|
97
|
+
};
|
|
98
|
+
const requiredFields: Partial<Record<BoardAction, string[]>> = {
|
|
99
|
+
create_channel: ["channel_name"],
|
|
100
|
+
post: ["text"],
|
|
101
|
+
list_threads: ["channel_name"],
|
|
102
|
+
read_thread: ["thread_id"],
|
|
103
|
+
read_post: ["message_id"],
|
|
104
|
+
};
|
|
105
|
+
export function parseBoardRequest(value: unknown): BoardParams {
|
|
106
|
+
if (!Check(Request, value))
|
|
107
|
+
throw new Error("Invalid board request; call board help");
|
|
108
|
+
const request = { ...(value as BoardParams) };
|
|
109
|
+
const allowed = new Set(["action", ...fields[request.action]]);
|
|
110
|
+
if (Object.keys(request).some((field) => !allowed.has(field)))
|
|
111
|
+
throw new Error(`Unknown ${request.action} field; board_id is read-only`);
|
|
112
|
+
for (const field of requiredFields[request.action] ?? []) {
|
|
113
|
+
if (!(field in request)) throw new Error(`${field} is required`);
|
|
114
|
+
}
|
|
115
|
+
for (const field of [
|
|
116
|
+
"thread_id",
|
|
117
|
+
"message_id",
|
|
118
|
+
"after_message_id",
|
|
119
|
+
"board_id",
|
|
120
|
+
] as const) {
|
|
121
|
+
const id = request[field];
|
|
122
|
+
if (
|
|
123
|
+
id !== undefined &&
|
|
124
|
+
!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(
|
|
125
|
+
id,
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
throw new Error(`${field} must be a UUID`);
|
|
129
|
+
if (id !== undefined) request[field] = id.toLowerCase();
|
|
130
|
+
}
|
|
131
|
+
if (request.action === "post")
|
|
132
|
+
exactlyOne(request, ["channel_name", "new_channel_name", "thread_id"]);
|
|
133
|
+
if (request.action === "subscribe" || request.action === "unsubscribe")
|
|
134
|
+
exactlyOne(request, ["channel_name", "thread_id"]);
|
|
135
|
+
return request;
|
|
136
|
+
}
|
|
137
|
+
function exactlyOne(value: BoardParams, keys: (keyof BoardParams)[]) {
|
|
138
|
+
if (keys.filter((key) => value[key] !== undefined).length !== 1)
|
|
139
|
+
throw new Error(`Provide exactly one of ${keys.join(", ")}`);
|
|
140
|
+
}
|
|
141
|
+
export function required(value: string | undefined, field: string): string {
|
|
142
|
+
if (value === undefined) throw new Error(`${field} is required`);
|
|
143
|
+
return value;
|
|
144
|
+
}
|
|
145
|
+
export function agentPath(value: string, caller: string): string {
|
|
146
|
+
const path = value.startsWith("/") ? value : `${caller}/${value}`;
|
|
147
|
+
if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(path))
|
|
148
|
+
throw new Error("Invalid agent path");
|
|
149
|
+
return path;
|
|
150
|
+
}
|
|
151
|
+
export const boardHelp = {
|
|
152
|
+
actions: Object.fromEntries(
|
|
153
|
+
Object.entries(fields).map(([action, values]) => [
|
|
154
|
+
action,
|
|
155
|
+
values
|
|
156
|
+
.map(
|
|
157
|
+
(field) =>
|
|
158
|
+
`${field}${requiredFields[action as BoardAction]?.includes(field) ? "" : "?"}`,
|
|
159
|
+
)
|
|
160
|
+
.join(" "),
|
|
161
|
+
]),
|
|
162
|
+
),
|
|
163
|
+
rules: {
|
|
164
|
+
scope:
|
|
165
|
+
"Defaults to your tree; board_id browses history, never writes. list_boards discovers saved boards",
|
|
166
|
+
post: "text required; exactly one of channel_name, new_channel_name, thread_id. Thread ID is the first post ID. New channel subscribes author to first posts",
|
|
167
|
+
subscriptions:
|
|
168
|
+
"Exactly one of channel_name/thread_id; channel covers first posts, thread covers replies. target_agent defaults to you. Posting subscribes author to thread unless explicitly unsubscribed",
|
|
169
|
+
notify:
|
|
170
|
+
"agents_to_notify is one-time, excludes author; only running turns, no waking or offline notices",
|
|
171
|
+
agents:
|
|
172
|
+
"Use spawn's boardAgent; absolute /root/... or child path relative to you, not a pane or contextAgent",
|
|
173
|
+
paging:
|
|
174
|
+
"limit default20, cap50; cursor opaque, keep query/sort unchanged. Concurrent posts may shift pages",
|
|
175
|
+
order:
|
|
176
|
+
"Newest first; get_channels by activity, list_threads sort=created|activity. read_thread pages newest replies with root on every page",
|
|
177
|
+
text: "Case-insensitive substring search; max_chars_per_post default1000. read_post offsets count Unicode characters, limit_chars default20000. Continue at next_offset_chars<n_chars",
|
|
178
|
+
budget:
|
|
179
|
+
"Post cap64KiB, channel1-128 UTF-8 bytes without edge whitespace/control characters. Results cap8000 serialized UTF-8 bytes; reads may reduce limits, continue with returned cursor/offset",
|
|
180
|
+
},
|
|
181
|
+
};
|