the .part-then-rename rule was applied at two upload routes yesterday and by this morning the platform had a dozen other writes putting files in the same folders — an OCR result beside its image, a TTS clip, a download landing, a save from the editor — every one straight to the final name. a guarantee that holds for two of fourteen paths is not a guarantee, and the next person adding a fifteenth had nothing to copy. so it is a function now, and every durable write goes through it: the file browser, sendoff, task definitions, skill and tool files, bug reports, scraped attachments, the chat provider config. the failure it prevents is silent rather than loud. a truncated m4a decodes fine, it is simply short — a commander transcribing recordings as they land would produce a clean transcript of the first few seconds of a two-minute memo and report success. two things learned writing it. Bun.write creates the parent chain itself, so the mkdir option i added was dead weight and several callers were doing it twice. and Parameters<typeof Bun.write>[1] resolves to the first overload only — BunFile — which rejects the string and Buffer every caller actually passes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
160 lines
5.6 KiB
TypeScript
160 lines
5.6 KiB
TypeScript
import { createRouter } from '../create-router';
|
|
import { readdir, mkdir, rm } from 'node:fs/promises';
|
|
import { join, dirname } from 'node:path';
|
|
import { itemsDir, type ItemType } from '../data-path';
|
|
import { writeAtomic } from '@@/write-atomic';
|
|
|
|
// Shared router for the flat, file-based item types (skills, tools, processes). Each item is a
|
|
// directory under $OFFICER_ITEMS_DIR/<type>/<dirName>/ holding a single markdown file (SKILL.md /
|
|
// TOOL.md / PROCESS.md) plus an optional chat/ subdir. No scope tiers — every item is editable.
|
|
|
|
type Frontmatter = { name: string; description: string };
|
|
|
|
export function parseFrontmatter(raw: string): { frontmatter: Frontmatter; body: string; rawYaml: string } {
|
|
const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
if (!match) return { frontmatter: { name: '', description: '' }, body: raw, rawYaml: '' };
|
|
|
|
const yaml = match[1]!;
|
|
const body = match[2]!;
|
|
const name = yaml.match(/^name:\s*(.+)$/m)?.[1]?.trim() ?? '';
|
|
const description = yaml.match(/^description:\s*(.+)$/m)?.[1]?.trim() ?? '';
|
|
|
|
return { frontmatter: { name, description }, body, rawYaml: yaml };
|
|
}
|
|
|
|
async function readItemDirs(dir: string, fileName: string): Promise<Map<string, string>> {
|
|
const result = new Map<string, string>();
|
|
try {
|
|
const entries = await readdir(dir, { withFileTypes: true });
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
const file = join(dir, entry.name, fileName);
|
|
if (await Bun.file(file).exists()) result.set(entry.name, file);
|
|
}
|
|
} catch {
|
|
// directory doesn't exist yet
|
|
}
|
|
return result;
|
|
}
|
|
|
|
const slugify = (name: string) =>
|
|
name
|
|
.trim()
|
|
.toLowerCase()
|
|
.replace(/\s+/g, '-')
|
|
.replace(/[^a-z0-9-]/g, '');
|
|
|
|
type ItemRouterConfig = { type: ItemType; fileName: string; label: string };
|
|
|
|
export function createItemRouter({ type, fileName, label }: ItemRouterConfig) {
|
|
const router = createRouter();
|
|
const rootDir = () => itemsDir(type);
|
|
const filePathFor = (name: string) => join(rootDir(), name, fileName);
|
|
const resolve = async (name: string): Promise<string | null> => {
|
|
const filePath = filePathFor(name);
|
|
return (await Bun.file(filePath).exists()) ? filePath : null;
|
|
};
|
|
|
|
router.get('/', async (ctx) => {
|
|
const dirs = await readItemDirs(rootDir(), fileName);
|
|
const items = await Promise.all(
|
|
Array.from(dirs.entries()).map(async ([dirName, filePath]) => {
|
|
const { frontmatter } = parseFrontmatter(await Bun.file(filePath).text());
|
|
return { dirName, name: frontmatter.name || dirName, description: frontmatter.description, filePath };
|
|
}),
|
|
);
|
|
items.sort((a, b) => a.name.localeCompare(b.name));
|
|
return ctx.json(items);
|
|
});
|
|
|
|
router.get('/:name', async (ctx) => {
|
|
const name = ctx.req.param('name');
|
|
const filePath = await resolve(name);
|
|
if (!filePath) return ctx.text('Not found', 404);
|
|
|
|
const { frontmatter, body, rawYaml } = parseFrontmatter(await Bun.file(filePath).text());
|
|
const chatMeta = join(dirname(filePath), 'chat', 'meta.json');
|
|
const chatSessionId = await Bun.file(chatMeta)
|
|
.json()
|
|
.then((m: { id: string }) => m.id)
|
|
.catch(() => null);
|
|
|
|
return ctx.json({
|
|
name: frontmatter.name || name,
|
|
description: frontmatter.description,
|
|
body,
|
|
rawFrontmatter: rawYaml,
|
|
filePath,
|
|
chatSessionId,
|
|
});
|
|
});
|
|
|
|
router.get('/:name/chat', async (ctx) => {
|
|
const name = ctx.req.param('name');
|
|
const filePath = await resolve(name);
|
|
if (!filePath) return ctx.text('Not found', 404);
|
|
|
|
const chatDir = join(dirname(filePath), 'chat');
|
|
const sessionId = await Bun.file(join(chatDir, 'meta.json'))
|
|
.json()
|
|
.then((m: { id: string }) => m.id)
|
|
.catch(() => null);
|
|
const messages = await Bun.file(join(chatDir, 'messages.json'))
|
|
.json()
|
|
.catch(() => []);
|
|
|
|
return ctx.json({ sessionId, messages });
|
|
});
|
|
|
|
router.put('/:name/chat', async (ctx) => {
|
|
const name = ctx.req.param('name');
|
|
const filePath = await resolve(name);
|
|
if (!filePath) return ctx.text('Not found', 404);
|
|
|
|
const chatDir = join(dirname(filePath), 'chat');
|
|
const { sessionId, messages } = await ctx.req.json<{ sessionId: string; messages: unknown[] }>();
|
|
|
|
await mkdir(chatDir, { recursive: true });
|
|
await writeAtomic(join(chatDir, 'messages.json'), JSON.stringify(messages));
|
|
if (sessionId) await writeAtomic(join(chatDir, 'meta.json'), JSON.stringify({ id: sessionId }));
|
|
|
|
return ctx.json({ ok: true });
|
|
});
|
|
|
|
router.delete('/:name/chat', async (ctx) => {
|
|
const name = ctx.req.param('name');
|
|
const filePath = await resolve(name);
|
|
if (!filePath) return ctx.text('Not found', 404);
|
|
|
|
await rm(join(dirname(filePath), 'chat'), { recursive: true, force: true });
|
|
return ctx.json({ ok: true });
|
|
});
|
|
|
|
router.post('/', async (ctx) => {
|
|
const { name } = await ctx.req.json<{ name: string }>();
|
|
if (!name?.trim()) return ctx.text('Name is required', 400);
|
|
|
|
const dirName = slugify(name);
|
|
if (!dirName) return ctx.text('Invalid name', 400);
|
|
|
|
const filePath = filePathFor(dirName);
|
|
if (await Bun.file(filePath).exists()) return ctx.text(`${label} already exists`, 409);
|
|
|
|
await mkdir(dirname(filePath), { recursive: true });
|
|
await writeAtomic(filePath, `---\nname: ${name.trim()}\ndescription: \n---\n`);
|
|
|
|
return ctx.json({ name: name.trim(), dirName, filePath });
|
|
});
|
|
|
|
router.delete('/:name', async (ctx) => {
|
|
const name = ctx.req.param('name');
|
|
const filePath = await resolve(name);
|
|
if (!filePath) return ctx.text('Not found', 404);
|
|
|
|
await rm(dirname(filePath), { recursive: true });
|
|
return ctx.json({ ok: true });
|
|
});
|
|
|
|
return router;
|
|
}
|