Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(cli): accept literal message input

Guse928e17bd34b
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index f779d0a2e..b7c3ba558 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { Readable } from "node:stream";
const mockDaemonStart = vi.hoisted(() => vi.fn(async () => {}));
const mockDaemonStartById = vi.hoisted(() => vi.fn(async () => {}));
@@ -16,7 +17,7 @@ vi.mock("./messageReminderClient", async (importOriginal) => ({
...await importOriginal<typeof import("./messageReminderClient")>(),
armMessageReminderFromEnv: mockArmMessageReminder,
}));
-import { main, setApiForTesting, decodeTextEscapes } from "./index";
+import { main, setApiForTesting, decodeTextEscapes, type CliInputStream } from "./index";
import type { ServerApi } from "../server/contract";
import { MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared/constants/community";
@@ -35,6 +36,16 @@ function parseEnvelope(lines: string[]): Record<string, unknown> {
return JSON.parse(lines[0]);
}
+function testStdin(text: string, isTTY = false): CliInputStream {
+ const input = Readable.from([Buffer.from(text, "utf8")]) as CliInputStream;
+ Object.defineProperty(input, "isTTY", { value: isTTY });
+ return input;
+}
+
+function mainWithStdin(argv: string[], text = "hi", isTTY = false): Promise<number> {
+ return main(argv, { stdin: testStdin(text, isTTY) });
+}
+
/** Minimal ServerApi stub; override per test. */
function stubApi(over: Partial<ServerApi> = {}): ServerApi {
return {
@@ -162,7 +173,7 @@ describe("envelope contract", () => {
}),
}),
);
- const code = await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ const code = await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect(code).toBe(0);
expect(env).toEqual({ success: { sent: "/s#0042/general#7" } });
@@ -225,7 +236,7 @@ describe("channel alignment (message send)", () => {
setApiForTesting(
stubApi({ send: async () => ({ state: "blocked", reason: "unaligned", unreadCount: 3, latestSeq: 12 }) }),
);
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect("success" in env).toBe(false);
expect(env.error).toContain("not aligned");
@@ -246,7 +257,7 @@ describe("message send --remind-after", () => {
it("keeps the no-flag result shape byte-compatible and makes no local arm call", async () => {
setApiForTesting(stubApi({ send: async () => ok }));
- await main(["message", "send", "--target", "/s#0042/general/#3", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general/#3", "--stdin"]);
expect(parseEnvelope(cap.lines())).toEqual({ success: { sent: "/s#0042/general/#3#7" } });
expect(mockArmMessageReminder).not.toHaveBeenCalled();
});
@@ -254,8 +265,8 @@ describe("message send --remind-after", () => {
it.each(["0m", "25h", "1s", "1.5h"])("rejects invalid duration %s before sending", async (duration) => {
const send = vi.fn(async () => ok);
setApiForTesting(stubApi({ send }));
- await main([
- "message", "send", "--target", "/s#0042/general/#3", "--text", "hi", "--remind-after", duration,
+ await mainWithStdin([
+ "message", "send", "--target", "/s#0042/general/#3", "--stdin", "--remind-after", duration,
]);
expect(parseEnvelope(cap.lines()).error).toContain("--remind-after");
expect(send).not.toHaveBeenCalled();
@@ -264,8 +275,8 @@ describe("message send --remind-after", () => {
it("arms only after success using the server's canonical channel and seq", async () => {
setApiForTesting(stubApi({ send: async () => ok }));
- await main([
- "message", "send", "--target", "/alias#0042/input", "--text", "hi", "--remind-after", "2m",
+ await mainWithStdin([
+ "message", "send", "--target", "/alias#0042/input", "--stdin", "--remind-after", "2m",
]);
expect(mockArmMessageReminder).toHaveBeenCalledWith({
channel: "/s#0042/general/#3",
@@ -284,15 +295,15 @@ describe("message send --remind-after", () => {
setApiForTesting(stubApi({
send: async () => ({ state: "blocked", reason: "unaligned", unreadCount: 1, latestSeq: 9 }),
}));
- await main([
- "message", "send", "--target", "/s#0042/general", "--text", "hi", "--remind-after", "1m",
+ await mainWithStdin([
+ "message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "1m",
]);
expect(mockArmMessageReminder).not.toHaveBeenCalled();
cap.lines().length = 0;
setApiForTesting(stubApi({ send: async () => { throw new Error("forbidden"); } }));
- await main([
- "message", "send", "--target", "/s#0042/general", "--text", "hi", "--remind-after", "1m",
+ await mainWithStdin([
+ "message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "1m",
]);
expect(mockArmMessageReminder).not.toHaveBeenCalled();
});
@@ -300,8 +311,8 @@ describe("message send --remind-after", () => {
it("keeps sent success when local arming returns false or throws", async () => {
setApiForTesting(stubApi({ send: async () => ok }));
mockArmMessageReminder.mockResolvedValueOnce({ armed: false, reason: "newer_message_observed" });
- await main([
- "message", "send", "--target", "/s#0042/general", "--text", "hi", "--remind-after", "1m",
+ await mainWithStdin([
+ "message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "1m",
]);
expect(parseEnvelope(cap.lines())).toEqual({
success: {
@@ -312,8 +323,8 @@ describe("message send --remind-after", () => {
cap.lines().length = 0;
mockArmMessageReminder.mockRejectedValueOnce(new Error("vch_secret"));
- await main([
- "message", "send", "--target", "/s#0042/general", "--text", "hi", "--remind-after", "1m",
+ await mainWithStdin([
+ "message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "1m",
]);
const envelope = parseEnvelope(cap.lines());
expect(envelope.success).toEqual({
@@ -338,7 +349,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "on it", "--reply", "#37"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "#37"], "on it");
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
});
@@ -348,7 +359,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "on it", "--reply", "37"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "37"], "on it");
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
});
@@ -358,7 +369,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: undefined }));
});
@@ -368,7 +379,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi", "--reply", "x"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "x"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("--reply must be a message seq");
expect(sendSpy).not.toHaveBeenCalled();
@@ -380,7 +391,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi", "--reply", "0"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("--reply must be a message seq");
expect(sendSpy).not.toHaveBeenCalled();
@@ -536,7 +547,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("attaches a nonce to the send request", async () => {
const sendSpy = vi.fn(async () => okRes);
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const arg = sendSpy.mock.calls[0]![0] as { nonce?: string };
expect(typeof arg.nonce).toBe("string");
expect((arg.nonce ?? "").length).toBeGreaterThan(0);
@@ -552,7 +563,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
return okRes;
});
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect(env.success.sent).toBe("/s#0042/general#8"); // succeeded, not an error
expect(calls).toBe(2); // retried once
@@ -562,7 +573,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("treats a `deduped` success (same-nonce retry matched the committed message) as sent, not an error", async () => {
const sendSpy = vi.fn(async () => ({ ...okRes, deduped: true }));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect(env.success.sent).toBe("/s#0042/general#8");
expect(env.error).toBeUndefined();
@@ -571,7 +582,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("does NOT retry a blocked/unaligned business outcome (it's a return, not transient)", async () => {
const sendSpy = vi.fn(async () => ({ state: "blocked" as const, reason: "unaligned" as const, unreadCount: 2, latestSeq: 9 }));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("channel not aligned");
expect(sendSpy).toHaveBeenCalledTimes(1); // no retry on a business outcome
@@ -580,7 +591,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("does NOT retry a non-transient thrown error (e.g. 4xx), surfaces it once", async () => {
const sendSpy = vi.fn(async () => { throw new Error("reply target #5 not found in /s#0042/general"); });
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "hi"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("reply target");
expect(sendSpy).toHaveBeenCalledTimes(1); // deterministic business error — not retried
@@ -1703,8 +1714,12 @@ describe("decodeTextEscapes", () => {
});
});
-describe("message send — --text escape decoding wired end-to-end", () => {
- it("sends a real newline body for --text \"a\\n\\nb\"", async () => {
+describe("message send — literal stdin/file body contract", () => {
+ it("forwards stdin byte-for-byte without shell expansion or escape decoding", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const marker = path.join(os.tmpdir(), `alook-stdin-marker-${Date.now()}-${Math.random()}`);
let sentText: string | undefined;
setApiForTesting(
stubApi({
@@ -1714,20 +1729,35 @@ describe("message send — --text escape decoding wired end-to-end", () => {
},
}),
);
- // Two literal chars backslash-n twice, as a shell would pass them.
- await main(["message", "send", "--target", "/s#0042/general", "--text", "a\\n\\nb"]);
- expect(sentText).toBe("a\n\nb");
- expect(sentText!.split("\n")).toHaveLength(3);
+ const literal = ` \`marker\` $(touch ${marker}) \${HOME} ' \\\" \\\\ a\\\\nb\n# markdown\n总部 🎉 \n`;
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], literal);
+ expect(sentText).toBe(literal);
+ expect(fs.existsSync(marker)).toBe(false);
});
- it("does NOT decode --file content (literal backslash-n stays literal)", async () => {
+ it("decodes UTF-8 once after joining split stdin byte chunks", async () => {
+ const literal = "中文 🎉";
+ const bytes = Buffer.from(literal, "utf8");
+ const input = Readable.from([bytes.subarray(0, 1), bytes.subarray(1, 4), bytes.subarray(4)]) as CliInputStream;
+ let sentText: string | undefined;
+ setApiForTesting(stubApi({
+ send: async (request: Parameters<ServerApi["send"]>[0]) => {
+ sentText = request.content.text;
+ return { state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } };
+ },
+ }));
+ await main(["message", "send", "--target", "/s#0042/general", "--stdin"], { stdin: input });
+ expect(sentText).toBe(literal);
+ });
+
+ it("forwards file content byte-for-byte, including surrounding whitespace", async () => {
const fs = await import("fs");
const os = await import("os");
const path = await import("path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cli-esc-"));
const file = path.join(dir, "body.txt");
- // File bytes contain a literal backslash + n (not a newline).
- fs.writeFileSync(file, "a\\nb");
+ const literal = " a\\\\nb\n总部 🎉 \n";
+ fs.writeFileSync(file, literal);
let sentText: string | undefined;
setApiForTesting(
stubApi({
@@ -1739,13 +1769,89 @@ describe("message send — --text escape decoding wired end-to-end", () => {
);
await main(["message", "send", "--target", "/s#0042/general", "--file", file]);
fs.rmSync(dir, { recursive: true, force: true });
- expect(sentText).toBe("a\\nb");
- expect(sentText).not.toContain("\n");
+ expect(sentText).toBe(literal);
+ });
+
+ it("rejects --stdin with --file before sending", async () => {
+ const sendSpy = vi.fn();
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--file", "body.md"]);
+ expect(parseEnvelope(cap.lines()).error).toContain("mutually exclusive");
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
+
+ it("fails fast when --stdin is attached to a TTY", async () => {
+ const sendSpy = vi.fn();
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], "", true);
+ expect(parseEnvelope(cap.lines()).error).toContain("requires piped input");
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
+
+ it("allows whitespace-only stdin only when an attachment is present", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], " \n");
+ expect(parseEnvelope(cap.lines()).error).toContain("--stdin");
+ expect(sendSpy).not.toHaveBeenCalled();
+
+ cap.lines().length = 0;
+ await mainWithStdin(
+ ["message", "send", "--target", "/s#0042/general", "--stdin", "--attachment", "att_1"],
+ " \n",
+ );
+ expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ content: { text: " \n" } }));
+ });
+
+ it("keeps attachment-only sends valid without reading stdin", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s#0042/general", "--attachment", "att_1"]);
+ expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({
+ content: { text: "" },
+ attachments: ["att_1"],
+ }));
+ });
+
+ it("rejects empty EOF and an unreadable body file before sending", async () => {
+ const os = await import("os");
+ const path = await import("path");
+ const sendSpy = vi.fn();
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], "");
+ expect(parseEnvelope(cap.lines()).error).toContain("--stdin");
+
+ cap.lines().length = 0;
+ const missing = path.join(os.tmpdir(), `alook-missing-${Date.now()}-${Math.random()}.md`);
+ await main(["message", "send", "--target", "/s#0042/general", "--file", missing]);
+ expect(parseEnvelope(cap.lines()).error).toContain("cannot read file");
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
+
+ it("documents --stdin and removes --text from send help", async () => {
+ await main(["message", "send", "-h"]);
+ const help = cap.lines().join("");
+ expect(help).toContain("--stdin");
+ expect(help).not.toContain("--text");
+ });
+
+ it("removes --text from the public parser", async () => {
+ const sendSpy = vi.fn();
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s#0042/general", "--text", "legacy"]);
+ expect(parseEnvelope(cap.lines()).error).toContain("unknown option '--text'");
+ expect(sendSpy).not.toHaveBeenCalled();
});
});
describe("nap", () => {
- it("errors when neither --handoff nor --text is given, and never calls api.nap", async () => {
+ it("errors when --handoff is missing, and never calls api.nap", async () => {
const napSpy = vi.fn(async () => ({ napped: true }));
setApiForTesting(stubApi({ nap: napSpy }));
await main(["nap"]);
@@ -1754,38 +1860,30 @@ describe("nap", () => {
expect(napSpy).not.toHaveBeenCalled();
});
- it("errors on a whitespace-only --text handoff (mandatory, real handoff)", async () => {
+ it("errors on a whitespace-only handoff file", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nap-empty-"));
+ const file = path.join(dir, "handoff.md");
+ fs.writeFileSync(file, " \n");
const napSpy = vi.fn(async () => ({ napped: true }));
setApiForTesting(stubApi({ nap: napSpy }));
- await main(["nap", "--text", " "]);
+ await main(["nap", "--handoff", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
const env = parseEnvelope(cap.lines());
expect(typeof env.error).toBe("string");
expect(napSpy).not.toHaveBeenCalled();
});
- it("calls api.nap with the --text handoff (escapes decoded)", async () => {
- let handoff: string | undefined;
- setApiForTesting(
- stubApi({
- nap: async (r: Parameters<ServerApi["nap"]>[0]) => {
- handoff = r.handoff;
- return { napped: true };
- },
- }),
- );
- await main(["nap", "--text", "line1\\nline2"]);
- const env = parseEnvelope(cap.lines());
- expect(env).toEqual({ success: { napped: true } });
- expect(handoff).toBe("line1\nline2");
- });
-
- it("reads the handoff from --handoff <file>", async () => {
+ it("reads the handoff from --handoff <file> without trimming", async () => {
const fs = await import("fs");
const os = await import("os");
const path = await import("path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nap-"));
const file = path.join(dir, "handoff.md");
- fs.writeFileSync(file, "Was mid-review of PR #42; next: run QA.\n");
+ const literal = " Was mid-review of PR #42; next: run QA.\\\\n\n中文 🎉 \n";
+ fs.writeFileSync(file, literal);
let handoff: string | undefined;
setApiForTesting(
stubApi({
@@ -1797,6 +1895,38 @@ describe("nap", () => {
);
await main(["nap", "--handoff", file]);
fs.rmSync(dir, { recursive: true, force: true });
- expect(handoff).toBe("Was mid-review of PR #42; next: run QA.");
+ expect(handoff).toBe(literal);
+ });
+
+ it("rejects --stdin and an unreadable handoff file", async () => {
+ const os = await import("os");
+ const path = await import("path");
+ const napSpy = vi.fn();
+ setApiForTesting(stubApi({ nap: napSpy }));
+ await main(["nap", "--stdin"]);
+ expect(parseEnvelope(cap.lines()).error).toContain("unknown option '--stdin'");
+ expect(napSpy).not.toHaveBeenCalled();
+
+ cap.lines().length = 0;
+ const missing = path.join(os.tmpdir(), `alook-missing-handoff-${Date.now()}-${Math.random()}.md`);
+ await main(["nap", "--handoff", missing]);
+ expect(parseEnvelope(cap.lines()).error).toContain("cannot read file");
+ expect(napSpy).not.toHaveBeenCalled();
+ });
+
+ it("removes --text from the public parser", async () => {
+ const napSpy = vi.fn();
+ setApiForTesting(stubApi({ nap: napSpy }));
+ await main(["nap", "--text", "legacy"]);
+ expect(parseEnvelope(cap.lines()).error).toContain("unknown option '--text'");
+ expect(napSpy).not.toHaveBeenCalled();
+ });
+
+ it("documents only --handoff and removes --stdin/--text from nap help", async () => {
+ await main(["nap", "-h"]);
+ const help = cap.lines().join("");
+ expect(help).toContain("--handoff <file>");
+ expect(help).not.toContain("--stdin");
+ expect(help).not.toContain("--text");
});
});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 035469974..1a3a5ce20 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -140,6 +140,62 @@ export function decodeTextEscapes(s: string): string {
return s.replace(/\\(.)/g, (m, c: string) => TEXT_ESCAPE_MAP[c] ?? m);
}
+export interface CliInputStream extends AsyncIterable<string | Uint8Array> {
+ isTTY?: boolean;
+}
+
+export interface CliIo {
+ stdin?: CliInputStream;
+}
+
+/**
+ * Read a free-form UTF-8 value without putting it in argv. `--stdin` is always
+ * explicit so an omitted body can never hang waiting for an interactive
+ * terminal. Both sources are byte-literal: validation may inspect `trim()`,
+ * but the value returned to the caller is never decoded, trimmed, or rewritten.
+ */
+async function readLiteralInput(args: {
+ command: string;
+ stdinSelected: boolean;
+ stdin?: CliInputStream;
+ filePath?: string;
+ fileOption: string;
+}): Promise<string | undefined> {
+ const { command, stdinSelected, stdin, filePath, fileOption } = args;
+ if (stdinSelected && filePath !== undefined) {
+ throw new CliError(`${command}: --stdin and ${fileOption} are mutually exclusive`);
+ }
+
+ if (stdinSelected) {
+ if (!stdin) throw new CliError(`${command}: stdin is unavailable`);
+ if (stdin.isTTY === true) {
+ throw new CliError(
+ `${command}: --stdin requires piped input; use ${fileOption} in an interactive terminal`,
+ );
+ }
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stdin) {
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks).toString("utf8");
+ } catch (err) {
+ throw new CliError(`${command}: cannot read stdin: ${(err as Error).message}`);
+ }
+ }
+
+ if (filePath !== undefined) {
+ const fs = await import("fs/promises");
+ try {
+ return await fs.readFile(filePath, "utf8");
+ } catch (err) {
+ throw new CliError(`${command}: cannot read file: ${(err as Error).message}`);
+ }
+ }
+
+ return undefined;
+}
+
/* ------------------------------------------------------------------ */
/* Commands */
/* ------------------------------------------------------------------ */
@@ -235,7 +291,7 @@ async function sendWithRetry(
return withTransientMutationRetry(() => api.send(req));
}
-async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
+async function cmdMessageSend(opts: Record<string, unknown>, stdin: CliInputStream): Promise<unknown> {
const remindAfterFlag = opts.remindAfter as string | undefined;
// Validate the full duration before any server mutation. A bad opt-in flag
// must never send a message and then report a local validation failure.
@@ -245,20 +301,14 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
const channel = opts.target as string;
if (!channel) throw new CliError("message send: --target <ref> is required (e.g. /demo-workspace#1234/general)");
- 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 send: file not found: ${fileFlag}`);
- // `--file` content is already-real bytes — never escape-decode it, or a
- // literal `\n` in a pasted code snippet / log would get corrupted.
- text = fs.readFileSync(fileFlag, "utf8").trim();
- } else if (typeof textFlag === "string") {
- // `--text` is a shell arg where agents naturally type `\n` for a newline;
- // decode the standard escapes so it doesn't land as a literal backslash-n.
- text = decodeTextEscapes(textFlag);
- }
+ const text = await readLiteralInput({
+ command: "message send",
+ stdinSelected: opts.stdin === true,
+ stdin,
+ filePath: fileFlag,
+ fileOption: "--file <path>",
+ });
// `--attachment` may repeat. Commander wires this via `.option(..., collect, [])`
// below; treat a missing flag as an empty list.
@@ -266,7 +316,7 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
const hasText = typeof text === "string" && text.trim().length > 0;
if (!hasText && attachmentIds.length === 0) {
- throw new CliError("message send: --text <text>, --file <path>, or --attachment <id> is required");
+ throw new CliError("message send: --stdin, --file <path>, or --attachment <id> is required");
}
// `--reply` accepts the hash form the agent already sees in payloads (`"#37"`)
@@ -355,8 +405,7 @@ async function cmdMessagePost(opts: Record<string, unknown>): Promise<unknown> {
const title = opts.title as string | undefined;
if (!title || title.trim().length === 0) throw new CliError("message post: --title <name> is required");
- // Body: same --text/--file handling as `message send` (file = literal bytes,
- // never escape-decode; --text decodes shell escapes).
+ // `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;
@@ -734,17 +783,14 @@ async function cmdFriendList(opts: Record<string, unknown>): Promise<unknown> {
async function cmdNap(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const fileFlag = opts.handoff as string | undefined;
- const textFlag = opts.text as string | undefined;
- let handoff: string | undefined;
- if (fileFlag) {
- const fs = await import("fs");
- if (!fs.existsSync(fileFlag)) throw new CliError(`nap: handoff file not found: ${fileFlag}`);
- handoff = fs.readFileSync(fileFlag, "utf8").trim();
- } else if (typeof textFlag === "string") {
- handoff = decodeTextEscapes(textFlag).trim();
- }
- if (!handoff) {
- throw new CliError("nap: a handoff is required — pass --handoff <file> or --text <note>");
+ const handoff = await readLiteralInput({
+ command: "nap",
+ stdinSelected: false,
+ filePath: fileFlag,
+ fileOption: "--handoff <file>",
+ });
+ if (handoff === undefined || handoff.trim().length === 0) {
+ throw new CliError("nap: a handoff is required — pass --handoff <file>");
}
return await api.nap({ handoff });
}
@@ -753,7 +799,7 @@ async function cmdNap(opts: Record<string, unknown>): Promise<unknown> {
/* Program definition */
/* ------------------------------------------------------------------ */
-function buildProgram(): Command {
+function buildProgram(stdin: CliInputStream): Command {
const program = new Command("alook")
.description("agent CLI")
.exitOverride()
@@ -770,8 +816,8 @@ function buildProgram(): Command {
.command("send")
.description("send a message to a channel, DM, or thread")
.option("--target <ref>", "destination (path-style ref, e.g. /demo-workspace#1234/general)")
- .option("--text <text>", "inline message body (short messages)")
- .option("--file <path>", "read message body from a file (long messages)")
+ .option("--stdin", "read the literal UTF-8 message body from non-TTY stdin")
+ .option("--file <path>", "read the literal UTF-8 message body from a file")
.option(
"-a, --attachment <id>",
"attach an uploaded file by id (repeatable — order = message order)",
@@ -788,7 +834,7 @@ function buildProgram(): Command {
.action(async function (this: Command) {
const localOpts = this.opts();
const globalOpts = program.opts();
- const result = await cmdMessageSend({ ...globalOpts, ...localOpts });
+ const result = await cmdMessageSend({ ...globalOpts, ...localOpts }, stdin);
printEnvelope({ success: result });
});
@@ -1047,7 +1093,6 @@ function buildProgram(): Command {
.command("nap")
.description("end your session and start fresh, carrying a handoff to your reborn self (read the nap rule first)")
.option("--handoff <file>", "path to your handoff note (your note to your reborn self)")
- .option("--text <note>", "inline handoff note (alternative to --handoff)")
.exitOverride()
.configureOutput({ writeOut: () => {}, writeErr: () => {} })
.action(async function (this: Command) {
@@ -1202,8 +1247,9 @@ function buildProgram(): Command {
/* Main entry */
/* ------------------------------------------------------------------ */
-export async function main(argv = process.argv.slice(2)): Promise<number> {
- const program = buildProgram();
+export async function main(argv = process.argv.slice(2), io: CliIo = {}): Promise<number> {
+ const stdin = io.stdin ?? (process.stdin as CliInputStream);
+ const program = buildProgram(stdin);
let internalExitCode = 0;
try {
await program.parseAsync(argv, { from: "user" });
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 17b71cd72..ec06627c4 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -107,8 +107,9 @@ function cliCommandsSection(): string {
"",
`1. \`${CLI} inbox pull\` — fetch unread messages (advances your read waterline by default, ` +
`so they won't re-pull; \`--no-ack\` to peek without advancing).`,
- `2. \`${CLI} message send\` — send to a channel, DM, or thread. Attach with ` +
- `\`--attachment <id>\` (repeatable, order matters). Optionally add ` +
+ `2. \`${CLI} message send\` — send to a channel, DM, or thread. ` +
+ `For a short body, use explicit \`--stdin\` with a quoted heredoc; for a long or complicated body, ` +
+ `use \`--file <path>\`. Attach with \`--attachment <id>\` (repeatable, order matters). Optionally add ` +
`\`--remind-after <duration>\` to be reminded if the same channel, thread, or DM receives no ` +
`newer message after your send. Use a whole number of minutes or hours from \`1m\` to \`24h\`, ` +
`such as \`15m\` or \`2h\`.`,
@@ -156,7 +157,7 @@ function cliCommandsSection(): string {
"",
"### Context Lifecycle",
"",
- `1. \`${CLI} nap --handoff <file>\` (or \`--text <note>\`) — reset your current session and ` +
+ `1. \`${CLI} nap --handoff <file>\` — reset your current session and ` +
`start fresh. The required handoff is injected into the new session so your future self can ` +
`quickly pick up unfinished work. Never nap on your own; only do it when someone explicitly asks.`,
"",
@@ -188,10 +189,14 @@ function messagingSection(): string {
"",
"- Reply where the message came from. Post results in the channel that owns the topic. " +
"When uncertain, read history (below) or DM the relevant people.",
- `- Short reply: \`${CLI} message send --target <ref> --text "brief reply"\`.`,
- `- Long or complicated: write body to a tmp file, then \`${CLI} message send --target <ref> --file ./temp_msg.md\`.`,
- `- Cite a specific message: \`${CLI} message send --target <ref> --reply "#37" --text "on it"\` — ` +
- "`--reply` takes the `#N` seq (within `--target`) of the message you're answering.",
+ "Free-form message bodies never go in command arguments.",
+ "",
+ `- Short reply: use \`${CLI} message send --target <ref> --stdin\` with the quoted-heredoc form shown ` +
+ "under *Message formatting*. Choose a fresh quoted delimiter that does not occur as a standalone line in the body.",
+ `- Long or complicated: write the body to a temporary file with a filesystem tool, then ` +
+ `\`${CLI} message send --target <ref> --file ./temp_msg.md\`.`,
+ `- Cite a specific message: add \`--reply "#37"\` to either form — \`--reply\` takes the \`#N\` seq ` +
+ "(within `--target`) of the message you're answering.",
"",
"### Context refs",
"",
@@ -243,8 +248,10 @@ function messagingSection(): string {
`are a member with \`${CLI} channel member --channel <ref>\` before mentioning them.`,
"",
"```bash",
- "# Notify Alice and point her to a message for context.",
- `${CLI} message send --target \"/demo#1234/general\" --text \"@alice#0001 Please review /demo#1234/general#42\"`,
+ "# Choose a fresh quoted delimiter that does not occur as a standalone line in the body.",
+ `${CLI} message send --target \"/demo#1234/general\" --stdin <<'ALOOK_MESSAGE_7F3C'`,
+ "@alice#0001 Please review /demo#1234/general#42",
+ "ALOOK_MESSAGE_7F3C",
"```",
"",
"### Pulled messages",
@@ -333,8 +340,7 @@ function utilsSection(): string {
"the duration, you'll receive a reminder to return and decide what to do next. Don't add it to " +
"ordinary messages that need no follow-up.",
"",
- `Example: \`${CLI} message send --target /demo#1234/team --text "Please review the rollout plan" ` +
- `--remind-after 1m\`.`,
+ `Example: ${CLI} message send --target "/demo#1234/team" --remind-after 1m --file ./message.md`,
].join("\n");
}
diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.ts
index 0ea2b5b40..851f091db 100644
--- a/src/daemon/src/manager/agentRouter.test.ts
+++ b/src/daemon/src/manager/agentRouter.test.ts
@@ -390,7 +390,7 @@ describe("AgentRouter — agent:nap", () => {
});
await router.start();
- const handoff = "Was mid-review of PR #42; next: run the QA suite.";
+ const handoff = " Was mid-review of PR #42; next: run the QA suite. \n";
await fire({ type: "agent:nap", agentId: "a1", config: CFG, launchId: "l1", handoff });
expect(beforeCalls).toEqual(["a1"]);
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 394b79e65..523705e49 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -155,7 +155,7 @@ function buildNapRewakePrompt(handoff: string): string {
return (
"You took a nap: you reset your own session, so prior conversation context " +
"is gone. Before sleeping you left yourself this handoff —\n\n" +
- handoff.trim() +
+ handoff +
"\n\nThen read @memory.md and your .context_timeline for durable context, and pull " +
"your inbox before doing anything else. If it reports marked messages, run `$ALOOK_CLI " +
"message mark list` and resume that outstanding work."
diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.ts
index fb1f44871..7b100215e 100644
--- a/src/shared/src/schemas.test.ts
+++ b/src/shared/src/schemas.test.ts
@@ -8,6 +8,7 @@ import {
UpdateWorkspaceRequestSchema,
BotAuditEventSchema,
BotAuditEventKindSchema,
+ CommunityAgentNapRequestSchema,
} from "./schemas"
function validCreatePayload(image?: string) {
@@ -19,6 +20,14 @@ function validCreatePayload(image?: string) {
}
}
+describe("CommunityAgentNapRequestSchema", () => {
+ it("rejects whitespace-only handoffs without trimming valid literal content", () => {
+ expect(CommunityAgentNapRequestSchema.safeParse({ handoff: " \n\t" }).success).toBe(false)
+ const handoff = " literal \\\\n text\n中文 🎉 \n"
+ expect(CommunityAgentNapRequestSchema.parse({ handoff }).handoff).toBe(handoff)
+ })
+})
+
describe("BotImageUrlSchema (via CommunityBotCreateRequestSchema)", () => {
it("accepts an https URL", () => {
const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("https://cdn.example.com/a.png"))
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 645cb11aa..f49785053 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1312,11 +1312,13 @@ export type CommunityAgentJoinServerRequest = z.infer<
>;
// `alook nap` — the agent resets its own session with a mandatory handoff (its
-// note to its reborn self, spliced into the rewake prompt). `.trim().min(1)`
-// enforces the handoff is real, not whitespace — the mechanical half of the
-// nap gate.
+// note to its reborn self, spliced into the rewake prompt). Inspect `trim()` to
+// reject whitespace-only handoffs, but preserve the original string byte-for-
+// byte for the rewake prompt.
export const CommunityAgentNapRequestSchema = z.object({
- handoff: z.string().trim().min(1),
+ handoff: z.string().refine((value) => value.trim().length > 0, {
+ message: "handoff is required",
+ }),
});
export type CommunityAgentNapRequest = z.infer<
typeof CommunityAgentNapRequestSchema
diff --git a/src/web/src/app/api/community/bots/me/nap/route.test.ts b/src/web/src/app/api/community/bots/me/nap/route.test.ts
index 1699f03f3..0dc2fcf2c 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.test.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.test.ts
@@ -109,8 +109,9 @@ describe("POST /api/community/bots/me/nap", () => {
it("daemon online (sent:1) → 200 dispatch-only; nap audit + awake stamp re-homed to daemon completion, NOT written here", async () => {
mockGetBotWakeContext.mockResolvedValue(READY_CTX)
mockPushAgentNapToMachine.mockResolvedValue({ sent: 1 })
+ const handoff = " note \\\\n to future self\n中文 🎉 \n"
- const res = await POST(req())
+ const res = await POST(req({ handoff }))
expect(res.status).toBe(200)
const body = (await res.json()) as { napped: boolean }
expect(body.napped).toBe(true)
@@ -118,7 +119,7 @@ describe("POST /api/community/bots/me/nap", () => {
expect(mockPushAgentNapToMachine).toHaveBeenCalledTimes(1)
const [, machineId, args] = mockPushAgentNapToMachine.mock.calls[0]!
expect(machineId).toBe("mac_1")
- expect(args).toMatchObject({ agentId: "b1", handoff: "note to future self" })
+ expect(args).toMatchObject({ agentId: "b1", handoff })
expect(typeof args.launchId).toBe("string")
expect(args.launchId.length).toBeGreaterThan(0)
diff --git a/src/web/src/app/api/community/bots/me/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.ts
index 19f8a2e9d..e86c75da8 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.ts
@@ -12,7 +12,7 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor
import { pushAgentNapToMachine } from "@/lib/community/bot-push"
/**
- * POST /api/community/bots/me/nap — `alook nap --handoff <file>|--text <s>`.
+ * POST /api/community/bots/me/nap — `alook nap --handoff <file>`.
*
* Relocated from the flat /api/community/nap (route/disc 接口树统一, Gener #215
* 乙; Blondie #527 placement). nap is a BOT-QUA-BOT self lifecycle action — the