Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(daemon): remove message post command (#483)

Gustavo Ye43a676bccfd5
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index d4ea0de19..c381d3707 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -56,7 +56,6 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),
ack: async (req) => ({ ok: true, applied: req.cursors, failed: [] }),
send: async () => ({ state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } }),
- createPost: async () => ({ ref: "/s/c/post", name: "post", seq: 1 }),
read: async () => ({ items: [], hasMore: false }),
resolve: async () => null,
listMembers: async () => ({ members: [], hasMore: false }),
@@ -219,6 +218,7 @@ describe("envelope contract", () => {
const out = cap.lines().join("");
expect(out).toContain("Usage:");
expect(out.trimStart().startsWith("{")).toBe(false);
+ expect(out).not.toMatch(/^\s+post\b/m);
});
it("BOUNDARY: normal commands + errors still emit JSON (only -h is text)", async () => {
@@ -641,74 +641,6 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
});
});
-describe("message post", () => {
- const okRes = { ref: "/s/ideas/my-post", name: "my-post", seq: 1 };
-
- it("forwards forum ref + title + body, returns the canonical post ref", async () => {
- const postSpy = vi.fn(async () => okRes);
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--text", "hello"]);
- const env = parseEnvelope(cap.lines());
- expect(env.success.posted).toBe("/s/ideas/my-post");
- expect(postSpy).toHaveBeenCalledWith(
- expect.objectContaining({ forum: "/s/ideas", title: "My Post", content: { text: "hello" } }),
- );
- });
-
- it("requires --target (forum ref), never calling createPost", async () => {
- const postSpy = vi.fn(async () => okRes);
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--title", "My Post", "--text", "hi"]);
- const env = parseEnvelope(cap.lines());
- expect(env.error).toContain("--target");
- expect(postSpy).not.toHaveBeenCalled();
- });
-
- it("requires --title, never calling createPost", async () => {
- const postSpy = vi.fn(async () => okRes);
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--target", "/s/ideas", "--text", "hi"]);
- const env = parseEnvelope(cap.lines());
- expect(env.error).toContain("--title");
- expect(postSpy).not.toHaveBeenCalled();
- });
-
- it("requires text OR an attachment (empty opener → error, never calls createPost)", async () => {
- const postSpy = vi.fn(async () => okRes);
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--target", "/s/ideas", "--title", "My Post"]);
- const env = parseEnvelope(cap.lines());
- expect(env.error).toContain("--text");
- expect(postSpy).not.toHaveBeenCalled();
- });
-
- it("allows an attachment-only post (no --text)", async () => {
- const postSpy = vi.fn(async () => okRes);
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--attachment", "att_1"]);
- const env = parseEnvelope(cap.lines());
- expect(env.success.posted).toBe("/s/ideas/my-post");
- expect(postSpy).toHaveBeenCalledWith(expect.objectContaining({ attachments: ["att_1"] }));
- });
-
- it("attaches a nonce and reuses it across a transient-5xx retry (no duplicate post)", async () => {
- let calls = 0;
- const nonces: (string | undefined)[] = [];
- const postSpy = vi.fn(async (req: { nonce?: string }) => {
- nonces.push(req.nonce);
- calls++;
- if (calls === 1) throw new Error("upstream returned 502 with non-JSON body from canonical messages door");
- return okRes;
- });
- setApiForTesting(stubApi({ createPost: postSpy }));
- await main(["message", "post", "--target", "/s/ideas", "--title", "My Post", "--text", "hi"]);
- const env = parseEnvelope(cap.lines());
- expect(env.success.posted).toBe("/s/ideas/my-post");
- expect(calls).toBe(2);
- expect(nonces[0]).toBe(nonces[1]); // same nonce → server dedupes, no second post
- });
-});
-
describe("server list", () => {
it("prints {success:{servers:[...]}} from a stubbed listServers", async () => {
setApiForTesting(
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 4c0fd9d89..9284f4cae 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -382,65 +382,6 @@ async function cmdMessageSend(opts: Record<string, unknown>, stdin: CliInputStre
}
}
-/**
- * createPost with the SAME bounded same-nonce transient retry as `sendWithRetry`
- * — createPost also carries a `nonce` the server dedupes on, so a
- * committed-but-response-lost create is absorbed here (server returns the
- * canonical post) instead of surfacing as an error the agent would re-run into a
- * second post. Only transient transport errors retry; a thrown 4xx (bad forum /
- * unauthorized / empty) passes straight through.
- */
-async function createPostWithRetry(
- api: ServerApi,
- req: Parameters<ServerApi["createPost"]>[0],
-): Promise<Awaited<ReturnType<ServerApi["createPost"]>>> {
- return withTransientMutationRetry(() => api.createPost(req));
-}
-
-async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {
- const api = getApi();
- const agent = agentId(opts);
- const forum = opts.target as string;
- if (!forum) throw new CliError("message post: --target <forum-ref> is required (e.g. /demo#1234/ideas)");
- const title = opts.title as string | undefined;
- if (!title || title.trim().length === 0) throw new CliError("message post: --title <name> is required");
-
- // `message post` keeps its legacy --text/--file body contract for now.
- let text: string | undefined;
- const fileFlag = opts.file as string | undefined;
- const textFlag = opts.text as string | undefined;
- if (fileFlag) {
- const fs = await import("fs");
- if (!fs.existsSync(fileFlag)) throw new CliError(`message post: file not found: ${fileFlag}`);
- text = fs.readFileSync(fileFlag, "utf8").trim();
- } else if (typeof textFlag === "string") {
- text = decodeTextEscapes(textFlag);
- }
-
- const attachmentIds = Array.isArray(opts.attachment) ? (opts.attachment as string[]) : [];
- const hasText = typeof text === "string" && text.trim().length > 0;
- // Opener contract: a post needs text OR at least one attachment (attachment-
- // only is a legitimate post — same as a forum post's first message).
- if (!hasText && attachmentIds.length === 0) {
- throw new CliError("message post: --text <text>, --file <path>, or --attachment <id> is required");
- }
-
- // One idempotency nonce per logical create, reused across sendWithRetry's
- // internal attempts (server dedupes on author+nonce) — same duplicate-guard
- // rationale as `message send`.
- const nonce = randomUUID();
- const res = await createPostWithRetry(api, {
- agentId: agent,
- forum,
- title: title.trim(),
- content: { text: text ?? "" },
- attachments: attachmentIds.length > 0 ? attachmentIds : undefined,
- nonce,
- });
- // Surface the canonical /server/forum/#N thread ref, usable as `--target`.
- return { posted: res.ref };
-}
-
async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const target = opts.target as string;
@@ -841,28 +782,6 @@ function buildProgram(stdin: CliInputStream): Command {
printEnvelope({ success: result });
});
- message
- .command("post")
- .description("create a new forum post in a forum")
- .option("--target <forum-ref>", "the forum to post in (path-style ref, e.g. /demo#1234/ideas)")
- .option("--title <name>", "the post title (its slug becomes the post's address)")
- .option("--text <text>", "inline post body (short)")
- .option("--file <path>", "read post body from a file (long)")
- .option(
- "-a, --attachment <id>",
- "attach an uploaded file by id (repeatable — order = body order)",
- (v, prev: string[] = []) => [...prev, v],
- [] as string[],
- )
- .exitOverride()
- .configureOutput({ writeOut: () => {}, writeErr: () => {} })
- .action(async function (this: Command) {
- const localOpts = this.opts();
- const globalOpts = program.opts();
- const result = await cmdMessagePost({ ...globalOpts, ...localOpts });
- printEnvelope({ success: result });
- });
-
message
.command("emoji")
.description("react to a message with a single emoji")
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index 8d9a9a4f7..b475a1fff 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -333,50 +333,6 @@ describe("createProxyServerApi — send (retargeted to the canonical messages do
});
});
-describe("createProxyServerApi — createPost (folded into the canonical messages door)", () => {
- it("maps the legacy CLI contract onto forum send and adapts the thread reply response", async () => {
- const seen: Array<{ url: string; init?: RequestInit }> = [];
- const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {
- seen.push({ url, init });
- return seen.length === 1
- ? jsonBody(JSON.stringify({
- state: "sent",
- message: { seq: "#12", channel: "/demo#1234/forum", content: { text: "Title" } },
- threadId: "thread_1",
- }))
- : jsonBody(JSON.stringify({
- state: "sent",
- message: { seq: "#1", channel: "/demo#1234/forum/#12", content: { text: "Body" } },
- }));
- });
- const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
- const out = await api.createPost({
- agentId: "a1",
- forum: "/demo#1234/forum",
- title: "Title",
- content: { text: "Body" },
- attachments: ["att_1"],
- nonce: "nonce_1",
- });
-
- expect(seen[0].url).toBe("http://proxy.test/api/community/channels/resolve/messages");
- expect(seen[0].init?.method).toBe("POST");
- expect(JSON.parse(String(seen[0].init?.body))).toEqual({
- channel: "/demo#1234/forum",
- content: { text: "Title" },
- attachments: ["att_1"],
- nonce: "nonce_1:opener",
- });
- expect(JSON.parse(String(seen[1].init?.body))).toEqual({
- channel: "/demo#1234/forum/#12",
- content: { text: "Body" },
- attachments: ["att_1"],
- nonce: "nonce_1:reply",
- });
- expect(out).toEqual({ ref: "/demo#1234/forum/#12", name: "Title", seq: 1 });
- });
-});
-
describe("createProxyServerApi — channelMember (retargeted to the canonical members door)", () => {
it("GETs channels/{id}/members with ?ref= (encoded); returns the ChannelMemberResult", async () => {
const seen: Array<{ url: string; init?: RequestInit }> = [];
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index 4dd0e3221..85d58e7d3 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -32,8 +32,6 @@ import type {
AckResponse,
SendRequest,
SendResponse,
- CreatePostRequest,
- CreatePostResponse,
ReadRequest,
ResolveRequest,
ListChannelsRequest,
@@ -218,54 +216,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
return parseJsonResponse<SendResponse>(res, "send");
}
- async function callCreatePost(req: CreatePostRequest): Promise<CreatePostResponse> {
- const endpoint = `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/messages`;
- const openerNonce = req.nonce !== undefined ? `${req.nonce}:opener` : undefined;
- const replyNonce = req.nonce !== undefined ? `${req.nonce}:reply` : undefined;
- const openerRes = await fetchImpl(endpoint, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${config.voucher}`,
- },
- body: JSON.stringify({
- channel: req.forum,
- content: { text: req.title },
- attachments: req.attachments ?? [],
- ...(openerNonce !== undefined ? { nonce: openerNonce } : {}),
- }),
- });
- const opener = await parseJsonResponse<{
- state: "sent";
- message: Message;
- threadId: string;
- }>(openerRes, "createPost opener");
- if (opener.state !== "sent" || !opener.message || !opener.threadId) {
- throw new Error("createPost: upstream response missing opener thread");
- }
- const threadRef = `${req.forum}/#${opener.message.seq.replace(/^#/, "")}`;
- const replyRes = await fetchImpl(endpoint, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${config.voucher}`,
- },
- body: JSON.stringify({
- channel: threadRef,
- content: req.content,
- attachments: req.attachments ?? [],
- ...(replyNonce !== undefined ? { nonce: replyNonce } : {}),
- }),
- });
- const reply = await parseJsonResponse<{ state: "sent"; message: Message }>(replyRes, "createPost reply");
- if (reply.state !== "sent" || !reply.message) throw new Error("createPost: upstream response missing reply");
- return {
- ref: reply.message.channel,
- name: req.title,
- seq: Number(reply.message.seq.replace(/^#/, "")),
- };
- }
-
async function callRead(req: ReadRequest): Promise<Page<Message>> {
// The ref + seq anchors go on the query string (a GET has no body). Encode
// the ref — it carries `/` and can carry `#`/`@` in DM handles. Precedent:
@@ -703,7 +653,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
inboxSnapshot: (_r: { agentId: AgentId }) => callInboxSnapshot(),
ack: callAck,
send: callSend,
- createPost: callCreatePost,
read: callRead,
resolve: callResolve,
listMembers: callListMembers,
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index d0a998146..bd757b493 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -147,8 +147,6 @@ describe("DEFAULT_CAPABILITY_RESOLVER", () => {
});
it("does not map deleted flat write verbs; inboxPull still matches the generic /inbox read family", () => {
- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/createPost")).toBeUndefined();
- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/createPost")).toBeUndefined();
// /api/inboxPull's flat ROUTE is deleted, but the resolver's generic
// `/inbox` substring rule (unrelated to the specific flat-verb rules)
// still fires on this path shape — the daemon proxy only rejects the
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index faed7d2ad..950bb7ebd 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -47,8 +47,6 @@ export type {
AckFailure,
SendRequest,
SendResponse,
- CreatePostRequest,
- CreatePostResponse,
CommunityAgentReactAddResponse,
MessageMarkRequest,
MessageMarkListResponse,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 2e4d2af76..32aaeb70d 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -426,34 +426,6 @@ export interface MessageMarkListResponse {
marked: Message[];
}
-/**
- * Create a new forum post (`alook message post`). `forum` is a forum REF
- * (`/server/forum`), resolved server-side (bots hold refs, not ids — same reason
- * `send` takes a ref). The canonical messages door stores `title` as an opener
- * message in the forum and `content` as the first reply in its ordinary thread.
- * The reply may contain text OR at least one attachment. `attachments` are
- * pending ids the bot uploaded against the forum before the thread exists.
- */
-export interface CreatePostRequest {
- agentId: AgentId;
- forum: ChannelRef;
- title: string;
- content: MessageContent;
- attachments?: string[];
- /** Idempotency key — reused across retries, server dedupes (same as `send`). */
- nonce?: string;
-}
-
-/**
- * The created thread's canonical address. `ref` is `/server/forum/#N`, where
- * `N` is the opener message seq; `seq` is the first reply's seq in that thread.
- */
-export interface CreatePostResponse {
- ref: ChannelRef;
- name: string;
- seq: Seq;
-}
-
export interface ReadRequest {
agentId: AgentId;
channel: ChannelRef;
@@ -646,9 +618,6 @@ export interface ServerApi {
/** Send a message to a channel ref. May be held by the freshness guard. */
send(req: SendRequest): Promise<SendResponse>;
- /** Create a new forum post in a forum ref, with its body as the first message. */
- createPost(req: CreatePostRequest): Promise<CreatePostResponse>;
-
/** Read history for a channel with seq-anchored pagination. */
read(req: ReadRequest): Promise<Page<Message>>;
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 09f0786b1..c120e3292 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -283,7 +283,6 @@ export {
CommunityAgentReadRequestSchema,
CommunityAgentResolveRequestSchema,
CommunityAgentListChannelsRequestSchema,
- CommunityAgentCreatePostRequestSchema,
CommunityAgentListMembersRequestSchema,
CommunityAgentChannelMemberRequestSchema,
CommunityAgentJoinServerRequestSchema,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index f49785053..4afd6baf1 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1266,27 +1266,6 @@ export type CommunityAgentListChannelsRequest = z.infer<
typeof CommunityAgentListChannelsRequestSchema
>;
-// CLI adapter input for `alook message post`. The daemon maps this shape onto
-// the canonical forum send body: title → opener message, content → the ordinary
-// thread's first reply. An attachment-only reply is legitimate; pending ids are
-// uploaded against the forum before the thread exists.
-export const CommunityAgentCreatePostRequestSchema = z
- .object({
- forum: z.string().min(1),
- title: z.string().min(1),
- content: CommunityAgentMessageContentSchema,
- attachments: z
- .array(z.string().min(1))
- .max(MAX_ATTACHMENTS_PER_MESSAGE)
- .default([]),
- nonce: z.string().min(1).max(128).optional(),
- })
- .refine(
- (d) => d.content.text.trim().length > 0 || d.attachments.length > 0,
- { message: "post must have text or attachments" }
- );
-export type CommunityAgentCreatePostRequest = z.infer<typeof CommunityAgentCreatePostRequestSchema>;
-
export const CommunityAgentListMembersRequestSchema = z.object({
server: z.string().min(1),
limit: z.number().int().positive().optional(),