@syengup/friday-channel-next 0.1.12 → 0.1.14
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/dist/src/agent-forward-runtime.d.ts +6 -0
- package/dist/src/agent-forward-runtime.js +2 -0
- package/dist/src/channel-actions.js +9 -1
- package/dist/src/channel.js +17 -4
- package/dist/src/friday-session.js +3 -4
- package/dist/src/history/normalize-message.d.ts +67 -0
- package/dist/src/history/normalize-message.js +224 -0
- package/dist/src/history/read-transcript.d.ts +22 -0
- package/dist/src/history/read-transcript.js +136 -0
- package/dist/src/http/handlers/files.d.ts +3 -2
- package/dist/src/http/handlers/files.js +20 -5
- package/dist/src/http/handlers/history-messages.d.ts +13 -0
- package/dist/src/http/handlers/history-messages.js +100 -0
- package/dist/src/http/handlers/history-sessions.d.ts +23 -0
- package/dist/src/http/handlers/history-sessions.js +163 -0
- package/dist/src/http/handlers/history-set-title.d.ts +10 -0
- package/dist/src/http/handlers/history-set-title.js +77 -0
- package/dist/src/http/handlers/messages.js +21 -6
- package/dist/src/http/server.js +15 -0
- package/dist/src/session/session-manager.d.ts +6 -0
- package/dist/src/session/session-manager.js +20 -8
- package/package.json +10 -11
- package/src/agent-forward-runtime.ts +10 -0
- package/src/channel-actions.test.ts +111 -0
- package/src/channel-actions.ts +10 -1
- package/src/channel.outbound.test.ts +137 -0
- package/src/channel.ts +24 -6
- package/src/friday-session.ts +3 -5
- package/src/history/normalize-message.test.ts +154 -0
- package/src/history/normalize-message.ts +292 -0
- package/src/history/read-transcript.ts +136 -0
- package/src/http/handlers/files.ts +21 -5
- package/src/http/handlers/history-messages.test.ts +144 -0
- package/src/http/handlers/history-messages.ts +123 -0
- package/src/http/handlers/history-sessions.test.ts +146 -0
- package/src/http/handlers/history-sessions.ts +184 -0
- package/src/http/handlers/history-set-title.test.ts +115 -0
- package/src/http/handlers/history-set-title.ts +86 -0
- package/src/http/handlers/messages.ts +31 -3
- package/src/http/server.ts +18 -0
- package/src/session/session-manager.test.ts +90 -0
- package/src/session/session-manager.ts +21 -8
- package/src/test-support/mock-runtime.ts +2 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalizes raw OpenClaw session transcript messages (as returned by the
|
|
3
|
+
* gateway `sessions.get` method / `runtime.subagent.getSessionMessages`) into a
|
|
4
|
+
* stable wire DTO the Friday app can parse without guessing at the upstream
|
|
5
|
+
* content-block shape.
|
|
6
|
+
*
|
|
7
|
+
* Each raw message is one persisted LLM message (UserMessage / AssistantMessage
|
|
8
|
+
* / ToolResultMessage) with an `__openclaw` metadata envelope attached by the
|
|
9
|
+
* gateway carrying the stable transcript entry `id`, a positional `seq`, and the
|
|
10
|
+
* record timestamp. That `id` is the durable, channel-agnostic identity the app
|
|
11
|
+
* uses as its sync/dedup key — runId is NOT persisted upstream.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface FridayHistoryImage {
|
|
15
|
+
mimeType?: string;
|
|
16
|
+
/** Base64 payload for inline ImageContent blocks. */
|
|
17
|
+
data?: string;
|
|
18
|
+
/** URL for `[media attached: ...]` markers or resolved `MEDIA:` attachments. */
|
|
19
|
+
url?: string;
|
|
20
|
+
/** Display/download filename (set for resolved `MEDIA:` attachments). */
|
|
21
|
+
filename?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface FridayHistoryToolCall {
|
|
25
|
+
id: string;
|
|
26
|
+
name: string;
|
|
27
|
+
arguments?: Record<string, unknown>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface FridayHistoryToolResult {
|
|
31
|
+
toolCallId?: string;
|
|
32
|
+
toolName?: string;
|
|
33
|
+
isError?: boolean;
|
|
34
|
+
text?: string;
|
|
35
|
+
images?: FridayHistoryImage[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface FridayHistoryUsage {
|
|
39
|
+
totalTokens?: number;
|
|
40
|
+
input?: number;
|
|
41
|
+
output?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type FridayHistoryRole = "user" | "assistant" | "toolResult" | "system";
|
|
45
|
+
|
|
46
|
+
export interface FridayHistoryMessage {
|
|
47
|
+
/** Stable transcript entry id (sync key). Synthetic when upstream omitted it. */
|
|
48
|
+
id: string;
|
|
49
|
+
seq: number;
|
|
50
|
+
ts?: number;
|
|
51
|
+
role: FridayHistoryRole;
|
|
52
|
+
text?: string;
|
|
53
|
+
thinking?: string;
|
|
54
|
+
toolCalls?: FridayHistoryToolCall[];
|
|
55
|
+
toolResult?: FridayHistoryToolResult;
|
|
56
|
+
images?: FridayHistoryImage[];
|
|
57
|
+
/** Raw `MEDIA:<path>` server paths stripped from text; the handler resolves
|
|
58
|
+
* them to downloadable `/friday-next/files/...` attachment URLs. */
|
|
59
|
+
mediaPaths?: string[];
|
|
60
|
+
model?: string;
|
|
61
|
+
usage?: FridayHistoryUsage;
|
|
62
|
+
/** Non-message records surfaced for context (e.g. compaction dividers). */
|
|
63
|
+
kind?: "compaction";
|
|
64
|
+
/** True when `id` was synthesized because upstream had no stable id. */
|
|
65
|
+
synthetic?: boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
type RawRecord = Record<string, unknown>;
|
|
69
|
+
|
|
70
|
+
function asRecord(value: unknown): RawRecord | undefined {
|
|
71
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
72
|
+
? (value as RawRecord)
|
|
73
|
+
: undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readString(value: unknown): string | undefined {
|
|
77
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function readFiniteNumber(value: unknown): number | undefined {
|
|
81
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
82
|
+
if (typeof value === "string" && value.trim()) {
|
|
83
|
+
const n = Number(value);
|
|
84
|
+
if (Number.isFinite(n)) return n;
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `MEDIA:<path>` lines emitted for outbound attachments (e.g. generated images). */
|
|
90
|
+
const MEDIA_LINE_RE = /^[ \t]*MEDIA:[ \t]*(\S.*?)[ \t]*$/gim;
|
|
91
|
+
|
|
92
|
+
/** Strips `MEDIA:<path>` lines from text, returning the cleaned text + the paths. */
|
|
93
|
+
function splitMediaLines(text: string): { text: string; paths: string[] } {
|
|
94
|
+
if (!text.includes("MEDIA:")) return { text, paths: [] };
|
|
95
|
+
const paths: string[] = [];
|
|
96
|
+
const cleaned = text
|
|
97
|
+
.replace(MEDIA_LINE_RE, (_m, p: string) => {
|
|
98
|
+
const v = p.trim();
|
|
99
|
+
if (v) paths.push(v);
|
|
100
|
+
return "";
|
|
101
|
+
})
|
|
102
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
103
|
+
.trim();
|
|
104
|
+
return { text: cleaned, paths };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const MEDIA_MARKER_RE = /\[media attached:\s*([^\]]+)\]/gi;
|
|
108
|
+
|
|
109
|
+
/** Pull `[media attached: <url>]` markers out of free text into image refs. */
|
|
110
|
+
function extractMediaMarkers(text: string): FridayHistoryImage[] {
|
|
111
|
+
const images: FridayHistoryImage[] = [];
|
|
112
|
+
for (const match of text.matchAll(MEDIA_MARKER_RE)) {
|
|
113
|
+
const url = match[1]?.trim();
|
|
114
|
+
if (url) images.push({ url });
|
|
115
|
+
}
|
|
116
|
+
return images;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface ParsedContent {
|
|
120
|
+
text: string;
|
|
121
|
+
thinking: string;
|
|
122
|
+
toolCalls: FridayHistoryToolCall[];
|
|
123
|
+
images: FridayHistoryImage[];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function parseContent(content: unknown): ParsedContent {
|
|
127
|
+
const out: ParsedContent = { text: "", thinking: "", toolCalls: [], images: [] };
|
|
128
|
+
|
|
129
|
+
if (typeof content === "string") {
|
|
130
|
+
out.text = content;
|
|
131
|
+
out.images.push(...extractMediaMarkers(content));
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
if (!Array.isArray(content)) return out;
|
|
135
|
+
|
|
136
|
+
const textParts: string[] = [];
|
|
137
|
+
const thinkingParts: string[] = [];
|
|
138
|
+
for (const rawBlock of content) {
|
|
139
|
+
const block = asRecord(rawBlock);
|
|
140
|
+
if (!block) continue;
|
|
141
|
+
switch (block.type) {
|
|
142
|
+
case "text": {
|
|
143
|
+
const t = readString(block.text);
|
|
144
|
+
if (t) {
|
|
145
|
+
textParts.push(t);
|
|
146
|
+
out.images.push(...extractMediaMarkers(t));
|
|
147
|
+
}
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
case "thinking": {
|
|
151
|
+
const t = readString(block.thinking);
|
|
152
|
+
if (t) thinkingParts.push(t);
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case "image": {
|
|
156
|
+
const data = readString(block.data);
|
|
157
|
+
const url = readString(block.url);
|
|
158
|
+
// Skip empty image blocks (no payload and no URL) — they'd render as
|
|
159
|
+
// broken attachment bubbles in the app.
|
|
160
|
+
if (data || url) {
|
|
161
|
+
out.images.push({
|
|
162
|
+
...(readString(block.mimeType) ? { mimeType: readString(block.mimeType) } : {}),
|
|
163
|
+
...(data ? { data } : {}),
|
|
164
|
+
...(url ? { url } : {}),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case "toolCall": {
|
|
170
|
+
const id = readString(block.id);
|
|
171
|
+
const name = readString(block.name);
|
|
172
|
+
if (id && name) {
|
|
173
|
+
out.toolCalls.push({
|
|
174
|
+
id,
|
|
175
|
+
name,
|
|
176
|
+
...(asRecord(block.arguments) ? { arguments: asRecord(block.arguments) } : {}),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
default:
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
out.text = textParts.join("");
|
|
186
|
+
out.thinking = thinkingParts.join("");
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function parseUsage(raw: unknown): FridayHistoryUsage | undefined {
|
|
191
|
+
const usage = asRecord(raw);
|
|
192
|
+
if (!usage) return undefined;
|
|
193
|
+
const totalTokens = readFiniteNumber(usage.totalTokens) ?? readFiniteNumber(usage.total);
|
|
194
|
+
const input = readFiniteNumber(usage.input);
|
|
195
|
+
const output = readFiniteNumber(usage.output);
|
|
196
|
+
if (totalTokens === undefined && input === undefined && output === undefined) return undefined;
|
|
197
|
+
return {
|
|
198
|
+
...(totalTokens !== undefined ? { totalTokens } : {}),
|
|
199
|
+
...(input !== undefined ? { input } : {}),
|
|
200
|
+
...(output !== undefined ? { output } : {}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function normalizeRole(raw: unknown): FridayHistoryRole {
|
|
205
|
+
const role = readString(raw)?.toLowerCase();
|
|
206
|
+
switch (role) {
|
|
207
|
+
case "user":
|
|
208
|
+
return "user";
|
|
209
|
+
case "toolresult":
|
|
210
|
+
return "toolResult";
|
|
211
|
+
case "system":
|
|
212
|
+
return "system";
|
|
213
|
+
default:
|
|
214
|
+
return "assistant";
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Normalize one raw transcript message. `index` is the position in the returned
|
|
220
|
+
* batch, used only to synthesize a stable-ish id when upstream omits one.
|
|
221
|
+
*/
|
|
222
|
+
export function normalizeHistoryMessage(
|
|
223
|
+
raw: unknown,
|
|
224
|
+
index: number,
|
|
225
|
+
): FridayHistoryMessage | null {
|
|
226
|
+
const record = asRecord(raw);
|
|
227
|
+
if (!record) return null;
|
|
228
|
+
|
|
229
|
+
const meta = asRecord(record.__openclaw);
|
|
230
|
+
const role = normalizeRole(record.role);
|
|
231
|
+
const parsed = parseContent(record.content);
|
|
232
|
+
|
|
233
|
+
const seq = readFiniteNumber(meta?.seq) ?? index + 1;
|
|
234
|
+
const metaId = readString(meta?.id);
|
|
235
|
+
const id = metaId ?? `seq:${seq}`;
|
|
236
|
+
const synthetic = metaId === undefined;
|
|
237
|
+
const ts = readFiniteNumber(meta?.recordTimestampMs) ?? readFiniteNumber(record.timestamp);
|
|
238
|
+
const kind = readString(meta?.kind) === "compaction" ? "compaction" : undefined;
|
|
239
|
+
|
|
240
|
+
const message: FridayHistoryMessage = {
|
|
241
|
+
id,
|
|
242
|
+
seq,
|
|
243
|
+
role,
|
|
244
|
+
...(ts !== undefined ? { ts } : {}),
|
|
245
|
+
...(synthetic ? { synthetic: true } : {}),
|
|
246
|
+
...(kind ? { kind } : {}),
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
if (kind === "compaction") {
|
|
250
|
+
message.text = parsed.text || "Compaction";
|
|
251
|
+
return message;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (role === "toolResult") {
|
|
255
|
+
const split = splitMediaLines(parsed.text);
|
|
256
|
+
const toolResult: FridayHistoryToolResult = {
|
|
257
|
+
...(readString(record.toolCallId) ? { toolCallId: readString(record.toolCallId) } : {}),
|
|
258
|
+
...(readString(record.toolName) ? { toolName: readString(record.toolName) } : {}),
|
|
259
|
+
...(record.isError === true ? { isError: true } : {}),
|
|
260
|
+
...(split.text ? { text: split.text } : {}),
|
|
261
|
+
...(parsed.images.length ? { images: parsed.images } : {}),
|
|
262
|
+
};
|
|
263
|
+
message.toolResult = toolResult;
|
|
264
|
+
if (split.paths.length) message.mediaPaths = split.paths;
|
|
265
|
+
return message;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const split = splitMediaLines(parsed.text);
|
|
269
|
+
if (split.text) message.text = split.text;
|
|
270
|
+
if (split.paths.length) message.mediaPaths = split.paths;
|
|
271
|
+
if (parsed.thinking) message.thinking = parsed.thinking;
|
|
272
|
+
if (parsed.toolCalls.length) message.toolCalls = parsed.toolCalls;
|
|
273
|
+
if (parsed.images.length) message.images = parsed.images;
|
|
274
|
+
|
|
275
|
+
const model = readString(record.model) ?? readString(record.responseModel);
|
|
276
|
+
if (model) message.model = model;
|
|
277
|
+
const usage = parseUsage(record.usage);
|
|
278
|
+
if (usage) message.usage = usage;
|
|
279
|
+
|
|
280
|
+
return message;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Normalize a batch of raw transcript messages, dropping unparseable entries. */
|
|
284
|
+
export function normalizeHistoryMessages(rawMessages: unknown[]): FridayHistoryMessage[] {
|
|
285
|
+
const out: FridayHistoryMessage[] = [];
|
|
286
|
+
for (let i = 0; i < rawMessages.length; i += 1) {
|
|
287
|
+
const normalized = normalizeHistoryMessage(rawMessages[i], i);
|
|
288
|
+
if (normalized) out.push(normalized);
|
|
289
|
+
}
|
|
290
|
+
out.sort((a, b) => a.seq - b.seq);
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a session's transcript directly from disk via the forward runtime's
|
|
3
|
+
* session store (`sessions.json` → entry.sessionFile → the `.jsonl` transcript).
|
|
4
|
+
*
|
|
5
|
+
* We do NOT use `runtime.subagent.getSessionMessages` here: that dispatches the
|
|
6
|
+
* gateway `sessions.get` method which is only valid inside a gateway request
|
|
7
|
+
* scope and returns empty when called from a plugin HTTP route. Reading the
|
|
8
|
+
* transcript file mirrors how `history-sessions.ts` reads `sessions.json`.
|
|
9
|
+
*
|
|
10
|
+
* Each transcript line is `{type, id, parentId, timestamp, message:{role,content,...}}`.
|
|
11
|
+
* We surface message records (in file order) with an `__openclaw` envelope
|
|
12
|
+
* matching the gateway's own `sessions.get` output, so `normalize-message.ts`
|
|
13
|
+
* can consume either source identically.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import { getFridayAgentForwardRuntime } from "../agent-forward-runtime.js";
|
|
19
|
+
import { agentIdFromSessionKey, toSessionStoreKey } from "../session/session-manager.js";
|
|
20
|
+
|
|
21
|
+
function entryString(entry: unknown, key: string): string | undefined {
|
|
22
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
23
|
+
const v = (entry as Record<string, unknown>)[key];
|
|
24
|
+
return typeof v === "string" && v.trim() ? v : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Resolves the store entry for a session key, tolerating case differences
|
|
29
|
+
* (the app's key carries an upper-case deviceId; `sessions.json` stores it
|
|
30
|
+
* lower-cased).
|
|
31
|
+
*/
|
|
32
|
+
function resolveEntry(store: Record<string, unknown>, sessionKey: string): unknown {
|
|
33
|
+
if (store[sessionKey]) return store[sessionKey];
|
|
34
|
+
const canonical = toSessionStoreKey(sessionKey);
|
|
35
|
+
if (store[canonical]) return store[canonical];
|
|
36
|
+
const target = canonical.toLowerCase();
|
|
37
|
+
for (const [k, v] of Object.entries(store)) {
|
|
38
|
+
if (k.toLowerCase() === target) return v;
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function resolveTranscriptPath(
|
|
44
|
+
entry: unknown,
|
|
45
|
+
storePath: string,
|
|
46
|
+
): string | undefined {
|
|
47
|
+
const sessionFile = entryString(entry, "sessionFile");
|
|
48
|
+
if (sessionFile) {
|
|
49
|
+
return path.isAbsolute(sessionFile)
|
|
50
|
+
? sessionFile
|
|
51
|
+
: path.join(path.dirname(storePath), sessionFile);
|
|
52
|
+
}
|
|
53
|
+
const sessionId = entryString(entry, "sessionId");
|
|
54
|
+
if (sessionId) {
|
|
55
|
+
return path.join(path.dirname(storePath), `${sessionId}.jsonl`);
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Resolves the real server-side session id for a session key, or undefined. */
|
|
61
|
+
export function resolveSessionId(sessionKey: string): string | undefined {
|
|
62
|
+
const rt = getFridayAgentForwardRuntime();
|
|
63
|
+
if (!rt) return undefined;
|
|
64
|
+
const agentId = agentIdFromSessionKey(sessionKey);
|
|
65
|
+
try {
|
|
66
|
+
const store = rt.loadSessionStore(rt.resolveStorePath(undefined, { agentId })) ?? {};
|
|
67
|
+
return entryString(resolveEntry(store, sessionKey), "sessionId");
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Returns raw transcript message objects (newest tail up to `limit`), each with
|
|
75
|
+
* an `__openclaw: { id, seq, recordTimestampMs }` envelope. Empty on any failure.
|
|
76
|
+
*/
|
|
77
|
+
export function readSessionTranscriptRawMessages(sessionKey: string, limit: number): unknown[] {
|
|
78
|
+
const rt = getFridayAgentForwardRuntime();
|
|
79
|
+
if (!rt) return [];
|
|
80
|
+
|
|
81
|
+
const agentId = agentIdFromSessionKey(sessionKey);
|
|
82
|
+
let storePath: string;
|
|
83
|
+
let store: Record<string, unknown>;
|
|
84
|
+
try {
|
|
85
|
+
storePath = rt.resolveStorePath(undefined, { agentId });
|
|
86
|
+
store = rt.loadSessionStore(storePath) ?? {};
|
|
87
|
+
} catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const entry = resolveEntry(store, sessionKey);
|
|
92
|
+
if (!entry) return [];
|
|
93
|
+
const filePath = resolveTranscriptPath(entry, storePath);
|
|
94
|
+
if (!filePath) return [];
|
|
95
|
+
|
|
96
|
+
let content: string;
|
|
97
|
+
try {
|
|
98
|
+
content = fs.readFileSync(filePath, "utf-8");
|
|
99
|
+
} catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const raw: unknown[] = [];
|
|
104
|
+
let seq = 0;
|
|
105
|
+
for (const line of content.split("\n")) {
|
|
106
|
+
const trimmed = line.trim();
|
|
107
|
+
if (!trimmed) continue;
|
|
108
|
+
let rec: Record<string, unknown>;
|
|
109
|
+
try {
|
|
110
|
+
const parsed = JSON.parse(trimmed) as unknown;
|
|
111
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
|
|
112
|
+
rec = parsed as Record<string, unknown>;
|
|
113
|
+
} catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (rec.type === "session" || !rec.message || typeof rec.message !== "object") continue;
|
|
117
|
+
seq += 1;
|
|
118
|
+
const tsRaw = rec.timestamp;
|
|
119
|
+
const ts =
|
|
120
|
+
typeof tsRaw === "string"
|
|
121
|
+
? Date.parse(tsRaw)
|
|
122
|
+
: typeof tsRaw === "number"
|
|
123
|
+
? tsRaw
|
|
124
|
+
: Number.NaN;
|
|
125
|
+
raw.push({
|
|
126
|
+
...(rec.message as Record<string, unknown>),
|
|
127
|
+
__openclaw: {
|
|
128
|
+
...(typeof rec.id === "string" ? { id: rec.id } : {}),
|
|
129
|
+
seq,
|
|
130
|
+
...(Number.isFinite(ts) ? { recordTimestampMs: ts } : {}),
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return limit > 0 && raw.length > limit ? raw.slice(raw.length - limit) : raw;
|
|
136
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* File manager for Friday Next channel attachments.
|
|
3
3
|
*
|
|
4
|
-
* Files are copied under
|
|
4
|
+
* Files are copied under `~/.openclaw/friday-next/attachments/` and served at
|
|
5
5
|
* GET /friday-next/files/{token} so the app can use stable gateway URLs after restarts.
|
|
6
6
|
*/
|
|
7
7
|
|
|
@@ -11,14 +11,30 @@ import os from "node:os";
|
|
|
11
11
|
import { createFridayNextLogger } from "../../logging.js";
|
|
12
12
|
import path from "node:path";
|
|
13
13
|
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { resolveFridayNextConfig } from "../../config.js";
|
|
15
|
+
import { getHostOpenClawConfigSnapshot } from "../../host-config.js";
|
|
16
|
+
import { getFridayNextRuntime } from "../../runtime.js";
|
|
14
17
|
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
/** Test-only override for the attachments base directory. */
|
|
19
|
+
let testAttachmentsDir: string | null = null;
|
|
20
|
+
|
|
21
|
+
export function setAttachmentsDirForTest(dir: string | null): void {
|
|
22
|
+
testAttachmentsDir = dir;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Resolve `<historyDir>/../attachments`, mirroring the offline-queue layout. */
|
|
26
|
+
function resolveAttachmentsDir(): string {
|
|
27
|
+
try {
|
|
28
|
+
const cfg = resolveFridayNextConfig(getHostOpenClawConfigSnapshot(getFridayNextRuntime().config));
|
|
29
|
+
return path.join(path.dirname(cfg.historyDir), "attachments");
|
|
30
|
+
} catch {
|
|
31
|
+
return path.join(os.homedir(), ".openclaw", "friday-next", "attachments");
|
|
32
|
+
}
|
|
17
33
|
}
|
|
18
34
|
|
|
19
|
-
/**
|
|
35
|
+
/** `~/.openclaw/friday-next/attachments/` directory; created on first use. */
|
|
20
36
|
export function getAttachmentsDir(): string {
|
|
21
|
-
const dir =
|
|
37
|
+
const dir = testAttachmentsDir ?? resolveAttachmentsDir();
|
|
22
38
|
try {
|
|
23
39
|
fs.mkdirSync(dir, { recursive: true });
|
|
24
40
|
} catch {
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { handleHistoryMessages } from "./history-messages.js";
|
|
7
|
+
import { setFridayNextRuntime } from "../../runtime.js";
|
|
8
|
+
import {
|
|
9
|
+
setFridayAgentForwardRuntime,
|
|
10
|
+
resetFridayAgentForwardRuntimeForTest,
|
|
11
|
+
} from "../../agent-forward-runtime.js";
|
|
12
|
+
|
|
13
|
+
class MockRes extends EventEmitter {
|
|
14
|
+
statusCode = 0;
|
|
15
|
+
headers: Record<string, string> = {};
|
|
16
|
+
body = "";
|
|
17
|
+
setHeader(name: string, value: string): void {
|
|
18
|
+
this.headers[name.toLowerCase()] = value;
|
|
19
|
+
}
|
|
20
|
+
end(body?: string): void {
|
|
21
|
+
if (body) this.body += body;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function makeReq(path: string, headers: Record<string, string> = {}, method = "GET"): any {
|
|
26
|
+
return { method, url: path, headers };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const AUTH = { authorization: "Bearer test-token" };
|
|
30
|
+
const CFG = {
|
|
31
|
+
channels: { "friday-next": { authToken: "test-token", pathPrefix: "/friday-next" } },
|
|
32
|
+
gateway: { auth: { token: "test-token" } },
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
let tmpDir = "";
|
|
36
|
+
|
|
37
|
+
/** Auth config + optional subagent fallback. */
|
|
38
|
+
function setRuntime(getSessionMessages?: (params: { sessionKey: string; limit?: number }) => Promise<{ messages?: unknown[] }>): void {
|
|
39
|
+
setFridayNextRuntime({
|
|
40
|
+
config: { loadConfig: () => CFG },
|
|
41
|
+
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
|
|
42
|
+
...(getSessionMessages ? { subagent: { getSessionMessages } } : {}),
|
|
43
|
+
} as never);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Forward runtime: store keyed by full session key → entry with a sessionFile. */
|
|
47
|
+
function setForward(store: Record<string, unknown>): void {
|
|
48
|
+
setFridayAgentForwardRuntime({
|
|
49
|
+
runtime: {
|
|
50
|
+
agent: {
|
|
51
|
+
session: {
|
|
52
|
+
resolveStorePath: (_s?: string, opts?: { agentId?: string }) =>
|
|
53
|
+
path.join(tmpDir, `${opts?.agentId ?? "main"}-sessions.json`),
|
|
54
|
+
loadSessionStore: () => store,
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
config: { current: () => CFG },
|
|
58
|
+
},
|
|
59
|
+
} as any);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function writeTranscript(name: string, lines: unknown[]): string {
|
|
63
|
+
const file = path.join(tmpDir, name);
|
|
64
|
+
fs.writeFileSync(file, lines.map((l) => JSON.stringify(l)).join("\n") + "\n", "utf-8");
|
|
65
|
+
return file;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
describe("handleHistoryMessages", () => {
|
|
69
|
+
beforeEach(() => {
|
|
70
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "friday-hist-"));
|
|
71
|
+
setRuntime();
|
|
72
|
+
});
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
resetFridayAgentForwardRuntimeForTest();
|
|
75
|
+
try {
|
|
76
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
77
|
+
} catch {
|
|
78
|
+
/* ignore */
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("rejects non-GET with 405", async () => {
|
|
83
|
+
const res = new MockRes();
|
|
84
|
+
await handleHistoryMessages(makeReq("/friday-next/history/messages", AUTH, "POST"), res as any);
|
|
85
|
+
expect(res.statusCode).toBe(405);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("rejects missing token with 401", async () => {
|
|
89
|
+
const res = new MockRes();
|
|
90
|
+
await handleHistoryMessages(makeReq("/friday-next/history/messages"), res as any);
|
|
91
|
+
expect(res.statusCode).toBe(401);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("400s when sessionKey is missing", async () => {
|
|
95
|
+
const res = new MockRes();
|
|
96
|
+
await handleHistoryMessages(makeReq("/friday-next/history/messages", AUTH), res as any);
|
|
97
|
+
expect(res.statusCode).toBe(400);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("reads the transcript file from disk including user + assistant messages", async () => {
|
|
101
|
+
const file = writeTranscript("sess.jsonl", [
|
|
102
|
+
{ type: "session", version: 1, sessionId: "s" },
|
|
103
|
+
{ type: "message", id: "u1", timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hi there" } },
|
|
104
|
+
{ type: "message", id: "a1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: [{ type: "text", text: "hello" }], model: "openai/gpt-4" } },
|
|
105
|
+
]);
|
|
106
|
+
setForward({ "agent:main:main": { sessionId: "s", sessionFile: file } });
|
|
107
|
+
|
|
108
|
+
const res = new MockRes();
|
|
109
|
+
await handleHistoryMessages(makeReq("/friday-next/history/messages?sessionKey=agent:main:main", AUTH), res as any);
|
|
110
|
+
expect(res.statusCode).toBe(200);
|
|
111
|
+
const body = JSON.parse(res.body);
|
|
112
|
+
expect(body.messages.map((m: any) => m.role)).toEqual(["user", "assistant"]);
|
|
113
|
+
expect(body.messages[0].text).toBe("hi there");
|
|
114
|
+
expect(body.messages[1].text).toBe("hello");
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("resolves the entry case-insensitively (app upper-cases deviceId)", async () => {
|
|
118
|
+
const file = writeTranscript("fd.jsonl", [
|
|
119
|
+
{ type: "message", id: "u1", message: { role: "user", content: "from app" } },
|
|
120
|
+
]);
|
|
121
|
+
// Store keyed lower-case (as sessions.json persists it).
|
|
122
|
+
setForward({ "agent:main:friday:direct:abcd-1234:9": { sessionId: "x", sessionFile: file } });
|
|
123
|
+
|
|
124
|
+
const res = new MockRes();
|
|
125
|
+
await handleHistoryMessages(
|
|
126
|
+
makeReq("/friday-next/history/messages?sessionKey=agent:main:friday:direct:ABCD-1234:9", AUTH),
|
|
127
|
+
res as any,
|
|
128
|
+
);
|
|
129
|
+
const body = JSON.parse(res.body);
|
|
130
|
+
expect(body.messages.map((m: any) => m.role)).toEqual(["user"]);
|
|
131
|
+
expect(body.messages[0].text).toBe("from app");
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("falls back to getSessionMessages when the transcript is not on disk", async () => {
|
|
135
|
+
setForward({}); // no entry → disk read yields nothing
|
|
136
|
+
setRuntime(async () => ({
|
|
137
|
+
messages: [{ role: "assistant", content: "fallback", __openclaw: { id: "a1", seq: 1 } }],
|
|
138
|
+
}));
|
|
139
|
+
const res = new MockRes();
|
|
140
|
+
await handleHistoryMessages(makeReq("/friday-next/history/messages?sessionKey=agent:main:main", AUTH), res as any);
|
|
141
|
+
const body = JSON.parse(res.body);
|
|
142
|
+
expect(body.messages.map((m: any) => m.id)).toEqual(["a1"]);
|
|
143
|
+
});
|
|
144
|
+
});
|