resources
This commit is contained in:
@@ -0,0 +1,51 @@
|
|||||||
|
# Resource Configuration Guide
|
||||||
|
|
||||||
|
You are an AI assistant helping users configure **resources** — external services and APIs that Officer connects to.
|
||||||
|
|
||||||
|
## What is a Resource?
|
||||||
|
|
||||||
|
A resource represents an external service (e.g., a TTS server, an STT API, an OCR endpoint). Each resource has:
|
||||||
|
- A `RESOURCE.md` file with frontmatter metadata (name, description) and a markdown body
|
||||||
|
- A `config.json` file with flat key-value connection settings (all strings)
|
||||||
|
|
||||||
|
## config.json Format
|
||||||
|
|
||||||
|
The config is a flat JSON object where every value is a string. Empty string means "not set".
|
||||||
|
|
||||||
|
Base fields (always present):
|
||||||
|
- `url` — the service endpoint URL
|
||||||
|
- `api_key` — API key or token for authentication
|
||||||
|
- `username` — username for basic auth
|
||||||
|
- `password` — password for basic auth
|
||||||
|
|
||||||
|
Additional fields vary per resource (e.g., `provider`, `model`, `voice`).
|
||||||
|
|
||||||
|
Example:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"url": "http://localhost:8000",
|
||||||
|
"api_key": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"provider": "openai",
|
||||||
|
"model": "tts-1",
|
||||||
|
"voice": "alloy"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to Help the User
|
||||||
|
|
||||||
|
1. **Ask what service they're connecting to** — provider name, URL, auth method
|
||||||
|
2. **Fill in the config.json** — write the file with the values they provide
|
||||||
|
3. **Explain each field** — tell them what each key does and what format it expects
|
||||||
|
4. **For new resources**, also write the `RESOURCE.md` with an appropriate name and description in the frontmatter
|
||||||
|
|
||||||
|
## RESOURCE.md Format
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
name: Human Readable Name
|
||||||
|
description: One-line description of what this resource does
|
||||||
|
---
|
||||||
|
Optional longer markdown body with usage notes, compatible providers, etc.
|
||||||
|
```
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Optical Character Recognition — OCR API
|
||||||
|
|
||||||
|
- **Type:** OCR
|
||||||
|
- **Port:** 8082
|
||||||
|
- **Description:** HTTP server for optical character recognition. Compatible with OpenAI-style vision APIs. Configure the URL and model in the connection settings below.
|
||||||
|
- **Verify:** `curl -sf {url}/v1/models`
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Speech to Text — Transcription API
|
||||||
|
|
||||||
|
- **Type:** STT
|
||||||
|
- **Port:** 8080
|
||||||
|
- **Description:** HTTP server for speech-to-text transcription. Compatible with the whisper.cpp server API. Configure the URL in the connection settings below.
|
||||||
|
- **Verify:** `curl -sf {url}/health`
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Text to Speech — Synthesis API
|
||||||
|
|
||||||
|
- **Type:** TTS
|
||||||
|
- **Port:** 8000
|
||||||
|
- **Description:** HTTP server for text-to-speech synthesis. Compatible with the OpenAI audio/speech API (mlx-audio, Kokoro, etc.) and ElevenLabs. Configure the URL and credentials in the connection settings below.
|
||||||
|
- **Verify:** `curl -sf {url}/v1/models`
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
name: Optical Character Recognition
|
||||||
|
description: HTTP server for optical character recognition
|
||||||
|
---
|
||||||
|
Compatible with OpenAI-style vision APIs for extracting text from images.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"url": "",
|
||||||
|
"api_key": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"model": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
name: Speech to Text
|
||||||
|
description: HTTP server for speech-to-text transcription
|
||||||
|
---
|
||||||
|
Compatible with the whisper.cpp server API and OpenAI-compatible transcription endpoints.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"url": "",
|
||||||
|
"api_key": "",
|
||||||
|
"username": "",
|
||||||
|
"password": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
name: Text to Speech
|
||||||
|
description: HTTP server for text-to-speech synthesis
|
||||||
|
---
|
||||||
|
Compatible with OpenAI audio/speech API (mlx-audio, Kokoro, etc.) and ElevenLabs.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"url": "",
|
||||||
|
"api_key": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"provider": "",
|
||||||
|
"model": "",
|
||||||
|
"voice": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
---
|
||||||
|
name: ocr
|
||||||
|
label: OCR
|
||||||
|
description: Extract text from an image file using the configured OCR service. Sends the image to the OCR API (OpenAI-compatible vision endpoint) and returns the extracted text. Use this tool whenever you need to read text from images, screenshots, documents, receipts, etc. Requires OCR to be configured in Settings → Resources.
|
||||||
|
language: typescript
|
||||||
|
inputs:
|
||||||
|
file_path:
|
||||||
|
type: string
|
||||||
|
description: Absolute path to the image file to extract text from
|
||||||
|
prompt:
|
||||||
|
type: string
|
||||||
|
description: Optional instructions for the OCR model (e.g. "extract only the table" or "return as markdown")
|
||||||
|
optional: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# OCR Tool
|
||||||
|
|
||||||
|
Extracts text from images using the configured OCR resource (OpenAI-compatible vision API).
|
||||||
|
|
||||||
|
## Supported formats
|
||||||
|
|
||||||
|
PNG, JPEG, WebP, GIF, and other common image formats.
|
||||||
|
|
||||||
|
## Output
|
||||||
|
|
||||||
|
Returns the extracted text content. For documents, preserves structure as markdown.
|
||||||
|
For tables, uses markdown table format. For code screenshots, uses fenced code blocks.
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { extname } from 'node:path';
|
||||||
|
|
||||||
|
type OcrConfig = {
|
||||||
|
url: string;
|
||||||
|
model: string;
|
||||||
|
api_key?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getOcrConfig(): OcrConfig | null {
|
||||||
|
try {
|
||||||
|
const raw = process.env.OFFICER_RESOURCES;
|
||||||
|
if (!raw) return null;
|
||||||
|
const resources = JSON.parse(raw) as Record<string, Record<string, string>>;
|
||||||
|
const ocr = resources['optical-character-recognition'];
|
||||||
|
if (!ocr?.url) return null;
|
||||||
|
return { url: ocr.url, model: ocr.model ?? '', api_key: ocr.api_key };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_PROMPT = [
|
||||||
|
'You are an OCR assistant. Extract meaningful text content from images.',
|
||||||
|
'Rules:',
|
||||||
|
'- Output ONLY the extracted text, no commentary or explanations.',
|
||||||
|
'- For documents, articles, books: preserve the original text, paragraphs, and structure as markdown.',
|
||||||
|
'- For tables: use markdown table format.',
|
||||||
|
'- For code/terminal screenshots: use fenced code blocks.',
|
||||||
|
'- For handwritten text: do your best to transcribe accurately.',
|
||||||
|
'- For mixed content: use appropriate formatting for each section.',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
export async function execute(
|
||||||
|
_toolCallId: string,
|
||||||
|
params: { file_path: string; prompt?: string },
|
||||||
|
) {
|
||||||
|
const config = getOcrConfig();
|
||||||
|
if (!config) {
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: 'OCR is not configured. Set it up in Settings → Resources → Optical Character Recognition.' }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const { file_path, prompt } = params;
|
||||||
|
|
||||||
|
if (!existsSync(file_path)) {
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: `File not found: ${file_path}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageBytes = readFileSync(file_path);
|
||||||
|
const base64 = imageBytes.toString('base64');
|
||||||
|
const ext = extname(file_path).replace('.', '').toLowerCase();
|
||||||
|
const mime = ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : ext === 'webp' ? 'image/webp' : ext === 'gif' ? 'image/gif' : `image/${ext || 'png'}`;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
|
if (config.api_key) headers['Authorization'] = `Bearer ${config.api_key}`;
|
||||||
|
|
||||||
|
const systemPrompt = prompt ? `${DEFAULT_PROMPT}\n\nAdditional instructions: ${prompt}` : DEFAULT_PROMPT;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${config.url.replace(/\/+$/, '')}/v1/chat/completions`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: config.model,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: systemPrompt },
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content: [
|
||||||
|
{ type: 'image_url', image_url: { url: `data:${mime};base64,${base64}` } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
max_tokens: 4096,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errorText = await res.text().catch(() => '');
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: `OCR API error (${res.status}): ${errorText}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = await res.json() as { choices?: Array<{ message?: { content?: string } }> };
|
||||||
|
const text = json.choices?.[0]?.message?.content ?? '';
|
||||||
|
|
||||||
|
if (!text) {
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: 'OCR returned empty result — the image may not contain readable text.' }],
|
||||||
|
isError: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text }],
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
return {
|
||||||
|
content: [{ type: 'text', text: `OCR request failed: ${message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-1
@@ -6,13 +6,14 @@ import { useClient } from 'hooks/useClient';
|
|||||||
type GoogleStatus = {
|
type GoogleStatus = {
|
||||||
connected: boolean;
|
connected: boolean;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
|
picture: string | null;
|
||||||
configured: boolean;
|
configured: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const GoogleAccount = () => {
|
export const GoogleAccount = () => {
|
||||||
const client = useClient();
|
const client = useClient();
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [status, setStatus] = useState<GoogleStatus>({ connected: false, email: null, configured: false });
|
const [status, setStatus] = useState<GoogleStatus>({ connected: false, email: null, picture: null, configured: false });
|
||||||
|
|
||||||
const fetchStatus = () => {
|
const fetchStatus = () => {
|
||||||
client
|
client
|
||||||
@@ -76,6 +77,9 @@ export const GoogleAccount = () => {
|
|||||||
<p className="text-sm font-medium text-duck-dark dark:text-foreground">Connected</p>
|
<p className="text-sm font-medium text-duck-dark dark:text-foreground">Connected</p>
|
||||||
<p className="text-xs text-duck-dark/50 dark:text-foreground/50 truncate">{status.email}</p>
|
<p className="text-xs text-duck-dark/50 dark:text-foreground/50 truncate">{status.email}</p>
|
||||||
</div>
|
</div>
|
||||||
|
{status.picture && (
|
||||||
|
<img src={status.picture} alt="" className="h-9 w-9 rounded-full shrink-0" referrerPolicy="no-referrer" />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-duck-dark/40 dark:text-foreground/40">
|
<p className="text-xs text-duck-dark/40 dark:text-foreground/40">
|
||||||
Officer has access to your Google Calendar, Gmail, and other enabled services.
|
Officer has access to your Google Calendar, Gmail, and other enabled services.
|
||||||
|
|||||||
+100
-91
@@ -1,116 +1,125 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Circle, Server, Wrench } from 'lucide-react';
|
import { Server, Plus, Check, X, Search } from 'lucide-react';
|
||||||
import { useGlobal } from 'hooks/useGlobal';
|
import { useGlobal } from 'hooks/useGlobal';
|
||||||
import { Input } from '@/components/ui/input';
|
import { useResources, type ResourceSummary } from 'state/useResources';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { useResources, getResourceCategory, type Resource } from 'state/useResources';
|
|
||||||
|
|
||||||
type ResourceItemProps = {
|
|
||||||
resource: Resource;
|
|
||||||
isActive: boolean;
|
|
||||||
onSelect: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ResourceItem = ({ resource: r, isActive, onSelect }: ResourceItemProps) => (
|
|
||||||
<button
|
|
||||||
onClick={onSelect}
|
|
||||||
className={`flex items-start gap-2.5 py-2 px-3 rounded-lg text-left cursor-pointer transition-colors ${isActive ? 'bg-duck-teal/10 text-duck-dark' : 'text-duck-dark/70 hover:bg-duck-dark/5 hover:text-duck-dark'}`}
|
|
||||||
>
|
|
||||||
{r.port ? (
|
|
||||||
<Server className="h-3.5 w-3.5 text-duck-teal shrink-0 mt-0.5" />
|
|
||||||
) : (
|
|
||||||
<Wrench className="h-3.5 w-3.5 text-duck-dark/40 shrink-0 mt-0.5" />
|
|
||||||
)}
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<div className="text-sm font-medium truncate">{r.name}</div>
|
|
||||||
<div className="text-xs text-duck-dark/40 truncate">{r.subtitle}</div>
|
|
||||||
</div>
|
|
||||||
<Circle className="h-2 w-2 shrink-0 mt-1.5 fill-green-500 text-green-500" />
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
|
|
||||||
export const ResourceSidebar = () => {
|
export const ResourceSidebar = () => {
|
||||||
const { resources, isLoading } = useResources();
|
const { resources, isLoading, createResource } = useResources();
|
||||||
const [selectedId, setSelectedId] = useGlobal<string | null>('RESOURCE_SELECTED', null);
|
const [selectedName, setSelectedName] = useGlobal<string | null>('RESOURCE_SELECTED', null);
|
||||||
const [showCatalog, setShowCatalog] = useGlobal<boolean>('RESOURCE_CATALOG', false);
|
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
const installed = resources?.filter((r: Resource) => r.installed) ?? [];
|
const [newName, setNewName] = useState('');
|
||||||
|
|
||||||
const query = search.toLowerCase();
|
const query = search.toLowerCase();
|
||||||
const filtered = query
|
const filtered = resources?.filter(
|
||||||
? installed.filter(
|
(r: ResourceSummary) =>
|
||||||
(r: Resource) => r.name.toLowerCase().includes(query) || r.subtitle.toLowerCase().includes(query),
|
!query || r.name.toLowerCase().includes(query) || r.description?.toLowerCase().includes(query),
|
||||||
)
|
) ?? [];
|
||||||
: installed;
|
|
||||||
|
|
||||||
const apiBased = filtered.filter((r: Resource) => getResourceCategory(r) === 'api-based');
|
const handleSelect = (dirName: string) => {
|
||||||
const localCli = filtered.filter((r: Resource) => getResourceCategory(r) === 'local-cli');
|
setSelectedName(dirName);
|
||||||
|
|
||||||
const handleCatalog = () => {
|
|
||||||
setSelectedId(null);
|
|
||||||
setShowCatalog(true);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSelect = (id: string) => {
|
const handleCreate = async () => {
|
||||||
setShowCatalog(false);
|
const name = newName.trim();
|
||||||
setSelectedId(id);
|
if (!name) return;
|
||||||
|
try {
|
||||||
|
const result = await createResource(name);
|
||||||
|
setCreating(false);
|
||||||
|
setNewName('');
|
||||||
|
setSelectedName(result.dirName);
|
||||||
|
} catch {
|
||||||
|
// error handled by client
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full">
|
<div className="flex flex-col h-full">
|
||||||
<div className="shrink-0 px-3 pt-3 pb-2 flex flex-col gap-2">
|
<div className="shrink-0 px-4 py-2 border-b border-duck-dark/10 bg-background/60 flex items-center justify-between">
|
||||||
<h2 className="text-sm font-semibold text-duck-dark px-1">Resources</h2>
|
<span className="text-sm font-medium text-duck-dark/70">Resources</span>
|
||||||
<Button
|
{!creating && (
|
||||||
size="sm"
|
<button
|
||||||
onClick={handleCatalog}
|
onClick={() => setCreating(true)}
|
||||||
className="w-full text-xs cursor-pointer bg-duck-teal text-white hover:bg-duck-teal/90"
|
className="p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors"
|
||||||
>
|
>
|
||||||
Catalog
|
<Plus className="h-4 w-4 text-duck-dark/50" />
|
||||||
</Button>
|
</button>
|
||||||
<Input
|
)}
|
||||||
placeholder="Search..."
|
</div>
|
||||||
|
{creating && (
|
||||||
|
<div className="shrink-0 px-3 py-2 border-b border-duck-dark/10 bg-duck-teal/5 flex items-center gap-1.5">
|
||||||
|
<input
|
||||||
|
value={newName}
|
||||||
|
onChange={(ev) => setNewName(ev.target.value)}
|
||||||
|
onKeyDown={(ev) => {
|
||||||
|
if (ev.key === 'Enter') {
|
||||||
|
ev.preventDefault();
|
||||||
|
handleCreate();
|
||||||
|
}
|
||||||
|
if (ev.key === 'Escape') {
|
||||||
|
setCreating(false);
|
||||||
|
setNewName('');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="Resource name..."
|
||||||
|
className="flex-1 min-w-0 rounded border border-duck-dark/20 bg-background px-2 py-1 text-base md:text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/30"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleCreate}
|
||||||
|
disabled={!newName.trim()}
|
||||||
|
className="p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors disabled:opacity-30"
|
||||||
|
>
|
||||||
|
<Check className="h-3.5 w-3.5 text-duck-teal" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setCreating(false); setNewName(''); }}
|
||||||
|
className="p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5 text-duck-dark/50" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="shrink-0 px-3 py-2 border-b border-duck-dark/10">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-duck-dark/30" />
|
||||||
|
<input
|
||||||
value={search}
|
value={search}
|
||||||
onChange={(ev) => setSearch(ev.target.value)}
|
onChange={(ev) => setSearch(ev.target.value)}
|
||||||
className="h-7 text-xs"
|
placeholder="Search resources..."
|
||||||
|
className="w-full rounded border border-duck-dark/15 bg-background/80 pl-7 pr-2 py-1 text-base md:text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/30"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-0.5 px-3 overflow-y-auto flex-1">
|
|
||||||
{isLoading && <p className="text-xs text-duck-dark/50 px-3 py-2">Loading...</p>}
|
|
||||||
{!isLoading && filtered.length === 0 && (
|
|
||||||
<p className="text-xs text-duck-dark/40 px-3 py-2">{search ? 'No matches' : 'No active resources'}</p>
|
|
||||||
)}
|
|
||||||
{apiBased.length > 0 && (
|
|
||||||
<>
|
|
||||||
<div className="flex items-center gap-2 px-3 pt-3 pb-1">
|
|
||||||
<Server className="h-3 w-3 text-duck-teal" />
|
|
||||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-duck-dark/40">API Based</span>
|
|
||||||
</div>
|
</div>
|
||||||
{apiBased.map((r: Resource) => (
|
<div className="overflow-y-auto flex-1">
|
||||||
<ResourceItem
|
{isLoading && <p className="text-xs text-duck-dark/50 px-4 py-2">Loading...</p>}
|
||||||
key={r.id}
|
{filtered.map((r: ResourceSummary) => (
|
||||||
resource={r}
|
<button
|
||||||
isActive={!showCatalog && selectedId === r.id}
|
key={r.dirName}
|
||||||
onSelect={() => handleSelect(r.id)}
|
onClick={() => handleSelect(r.dirName)}
|
||||||
/>
|
className={`w-full text-left px-4 py-3 border-b border-duck-dark/5 cursor-pointer transition-colors ${
|
||||||
|
selectedName === r.dirName ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Server className="h-3.5 w-3.5 text-duck-teal shrink-0" />
|
||||||
|
<span className="text-sm font-medium text-duck-dark truncate">{r.name}</span>
|
||||||
|
<span
|
||||||
|
className={`shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium ${
|
||||||
|
r.scope === 'global' ? 'bg-duck-teal/20 text-duck-teal' : 'bg-duck-dark/10 text-duck-dark/60'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{r.scope}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{r.description && <p className="text-xs text-duck-dark/50 mt-1 line-clamp-2">{r.description}</p>}
|
||||||
|
</button>
|
||||||
))}
|
))}
|
||||||
</>
|
{!isLoading && resources && resources.length === 0 && (
|
||||||
|
<p className="text-sm text-duck-dark/40 px-4 py-6 text-center">No resources found</p>
|
||||||
)}
|
)}
|
||||||
{localCli.length > 0 && (
|
{!isLoading && resources && resources.length > 0 && filtered.length === 0 && (
|
||||||
<>
|
<p className="text-sm text-duck-dark/40 px-4 py-6 text-center">No matches</p>
|
||||||
<div className="flex items-center gap-2 px-3 pt-3 pb-1">
|
|
||||||
<Wrench className="h-3 w-3 text-duck-dark/40" />
|
|
||||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-duck-dark/40">Local CLI</span>
|
|
||||||
</div>
|
|
||||||
{localCli.map((r: Resource) => (
|
|
||||||
<ResourceItem
|
|
||||||
key={r.id}
|
|
||||||
resource={r}
|
|
||||||
isActive={!showCatalog && selectedId === r.id}
|
|
||||||
onSelect={() => handleSelect(r.id)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,42 +1,66 @@
|
|||||||
import { useState } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { Server, Wrench, Loader2, RefreshCw, Trash2 } from 'lucide-react';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import ReactMarkdown from 'react-markdown';
|
||||||
|
import remarkGfm from 'remark-gfm';
|
||||||
|
import rehypeRaw from 'rehype-raw';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { useGlobal } from 'hooks/useGlobal';
|
import { Pencil, Trash2, Plus, X, Loader2, ArrowLeft } from 'lucide-react';
|
||||||
import { usePanelChannel } from 'hooks/usePanelChannel';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import {
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||||
AlertDialog,
|
import { useGlobal } from 'hooks/useGlobal';
|
||||||
AlertDialogAction,
|
import { useClient } from 'hooks/useClient';
|
||||||
AlertDialogCancel,
|
import { usePiChat, EmbeddableChat } from 'officerdev';
|
||||||
AlertDialogContent,
|
import { useResources, type ResourceDetail, type PingResult } from 'state/useResources';
|
||||||
AlertDialogDescription,
|
import { FrontmatterBlock } from '../../CapabilityPage';
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from '@/components/ui/alert-dialog';
|
|
||||||
import { useResources, getResourceCategory, type Resource, type PingResult } from 'state/useResources';
|
|
||||||
import { RUN_COMMAND_CHANNEL, type RunCommandState } from './run-command-channel';
|
|
||||||
|
|
||||||
type ConnectionSectionProps = {
|
const isSensitiveKey = (key: string) => /key|secret|password|token/i.test(key);
|
||||||
resource: Resource;
|
|
||||||
|
type ConfigEditorProps = {
|
||||||
|
resourceName: string;
|
||||||
|
config: Record<string, string>;
|
||||||
|
onSaved: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const ConnectionSection = ({ resource }: ConnectionSectionProps) => {
|
const ConfigEditor = ({ resourceName, config, onSaved }: ConfigEditorProps) => {
|
||||||
const { saveConnectionConfig, pingResource } = useResources();
|
const { saveConfig, pingResource } = useResources();
|
||||||
const [url, setUrl] = useState(resource.connectionConfig?.url ?? '');
|
const configEntries = Object.entries(config);
|
||||||
const [apiKey, setApiKey] = useState(resource.connectionConfig?.credentials?.apiKey ?? '');
|
const [fields, setFields] = useState<[string, string][]>(configEntries);
|
||||||
const [username, setUsername] = useState(resource.connectionConfig?.credentials?.username ?? '');
|
const [newKey, setNewKey] = useState('');
|
||||||
const [password, setPassword] = useState(resource.connectionConfig?.credentials?.password ?? '');
|
const [newValue, setNewValue] = useState('');
|
||||||
const [pinging, setPinging] = useState(false);
|
const [pinging, setPinging] = useState(false);
|
||||||
const [pingResult, setPingResult] = useState<PingResult | null>(null);
|
const [pingResult, setPingResult] = useState<PingResult | null>(null);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setFields(Object.entries(config));
|
||||||
|
}, [config]);
|
||||||
|
|
||||||
|
const hasUrl = fields.some(([k, v]) => k === 'url' && v);
|
||||||
|
|
||||||
|
const handleAddField = () => {
|
||||||
|
const key = newKey.trim();
|
||||||
|
if (!key || fields.some(([k]) => k === key)) return;
|
||||||
|
setFields([...fields, [key, newValue]]);
|
||||||
|
setNewKey('');
|
||||||
|
setNewValue('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveField = (index: number) => {
|
||||||
|
setFields(fields.filter((_, i) => i !== index));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFieldValue = (index: number, value: string) => {
|
||||||
|
setFields(fields.map((f, i) => (i === index ? [f[0]!, value] : f)));
|
||||||
|
};
|
||||||
|
|
||||||
const handlePing = async () => {
|
const handlePing = async () => {
|
||||||
|
const url = fields.find(([k]) => k === 'url')?.[1];
|
||||||
|
if (!url) return;
|
||||||
setPinging(true);
|
setPinging(true);
|
||||||
setPingResult(null);
|
setPingResult(null);
|
||||||
try {
|
try {
|
||||||
const result = await pingResource(resource.id, url);
|
const result = await pingResource(resourceName, url);
|
||||||
setPingResult(result);
|
setPingResult(result);
|
||||||
} catch {
|
} catch {
|
||||||
setPingResult({ reachable: false, latencyMs: null });
|
setPingResult({ reachable: false, latencyMs: null });
|
||||||
@@ -48,74 +72,83 @@ const ConnectionSection = ({ resource }: ConnectionSectionProps) => {
|
|||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const credentials =
|
const oldKeys = Object.keys(config);
|
||||||
apiKey || username || password
|
const newKeys = new Set(fields.map(([k]) => k));
|
||||||
? { apiKey: apiKey || undefined, username: username || undefined, password: password || undefined }
|
const patch: Record<string, string | null> = {};
|
||||||
: undefined;
|
for (const [key, value] of fields) {
|
||||||
await saveConnectionConfig(resource.id, { url, credentials });
|
patch[key] = value;
|
||||||
|
}
|
||||||
|
for (const key of oldKeys) {
|
||||||
|
if (!newKeys.has(key)) patch[key] = null;
|
||||||
|
}
|
||||||
|
await saveConfig(resourceName, patch);
|
||||||
|
onSaved();
|
||||||
|
toast.success('Configuration saved');
|
||||||
|
} catch {
|
||||||
|
toast.error('Failed to save configuration');
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasCredentials = !!(
|
|
||||||
resource.connectionConfig?.credentials?.apiKey || resource.connectionConfig?.credentials?.username
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<h3 className="text-sm font-semibold text-duck-dark mb-3">Connection</h3>
|
<h3 className="text-sm font-semibold text-duck-dark mb-3">Configuration</h3>
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-2">
|
||||||
<div>
|
{fields.map(([key, value], index) => (
|
||||||
<label className="text-xs text-duck-dark/50 mb-1 block">Base URL</label>
|
<div key={key} className="flex items-center gap-2">
|
||||||
|
<label className="text-xs text-duck-dark/50 w-28 shrink-0 truncate" title={key}>
|
||||||
|
{key}
|
||||||
|
</label>
|
||||||
<Input
|
<Input
|
||||||
value={url}
|
value={value}
|
||||||
onChange={(ev) => setUrl(ev.target.value)}
|
onChange={(ev) => handleFieldValue(index, ev.target.value)}
|
||||||
placeholder="http://127.0.0.1:64202"
|
type={isSensitiveKey(key) ? 'password' : 'text'}
|
||||||
className="h-8 text-xs"
|
className="h-8 text-xs flex-1"
|
||||||
/>
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 w-8 p-0 shrink-0 text-duck-dark/30 hover:text-red-500 cursor-pointer"
|
||||||
|
onClick={() => handleRemoveField(index)}
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{(hasCredentials || apiKey) && (
|
))}
|
||||||
<div>
|
|
||||||
<label className="text-xs text-duck-dark/50 mb-1 block">API Key</label>
|
|
||||||
<Input
|
|
||||||
value={apiKey}
|
|
||||||
onChange={(ev) => setApiKey(ev.target.value)}
|
|
||||||
placeholder="Optional"
|
|
||||||
type="password"
|
|
||||||
className="h-8 text-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{(hasCredentials || username || password) && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="text-xs text-duck-dark/50 mb-1 block">Username</label>
|
|
||||||
<Input
|
|
||||||
value={username}
|
|
||||||
onChange={(ev) => setUsername(ev.target.value)}
|
|
||||||
placeholder="Optional"
|
|
||||||
className="h-8 text-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="text-xs text-duck-dark/50 mb-1 block">Password</label>
|
|
||||||
<Input
|
|
||||||
value={password}
|
|
||||||
onChange={(ev) => setPassword(ev.target.value)}
|
|
||||||
placeholder="Optional"
|
|
||||||
type="password"
|
|
||||||
className="h-8 text-xs"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button variant="outline" size="sm" onClick={handlePing} disabled={pinging || !url} className="text-xs">
|
<Input
|
||||||
|
value={newKey}
|
||||||
|
onChange={(ev) => setNewKey(ev.target.value)}
|
||||||
|
placeholder="key"
|
||||||
|
className="h-8 text-xs w-28 shrink-0"
|
||||||
|
onKeyDown={(ev) => ev.key === 'Enter' && handleAddField()}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
value={newValue}
|
||||||
|
onChange={(ev) => setNewValue(ev.target.value)}
|
||||||
|
placeholder="value"
|
||||||
|
className="h-8 text-xs flex-1"
|
||||||
|
onKeyDown={(ev) => ev.key === 'Enter' && handleAddField()}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 w-8 p-0 shrink-0 text-duck-dark/30 hover:text-duck-teal cursor-pointer"
|
||||||
|
onClick={handleAddField}
|
||||||
|
disabled={!newKey.trim()}
|
||||||
|
>
|
||||||
|
<Plus className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 mt-1">
|
||||||
|
{hasUrl && (
|
||||||
|
<Button variant="outline" size="sm" onClick={handlePing} disabled={pinging} className="text-xs cursor-pointer">
|
||||||
{pinging && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
{pinging && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
||||||
Test Connection
|
Test Connection
|
||||||
</Button>
|
</Button>
|
||||||
<Button size="sm" onClick={handleSave} disabled={saving || !url} className="text-xs">
|
)}
|
||||||
|
<Button size="sm" onClick={handleSave} disabled={saving} className="text-xs cursor-pointer">
|
||||||
{saving && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
{saving && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
||||||
Save
|
Save
|
||||||
</Button>
|
</Button>
|
||||||
@@ -130,318 +163,187 @@ const ConnectionSection = ({ resource }: ConnectionSectionProps) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
type LocalAvailabilitySectionProps = {
|
type ResourceChatProps = {
|
||||||
resource: Resource;
|
detail: ResourceDetail;
|
||||||
onRun: (command: string) => void;
|
isNew?: boolean;
|
||||||
|
onResponseEnd: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ResourceAction = 'install' | 'uninstall' | 'verify' | 'update' | 'manage';
|
const ResourceChat = ({ detail, isNew, onResponseEnd }: ResourceChatProps) => {
|
||||||
|
const promptFrontmatter = `<frontmatter>\nconfig file: ${detail.configPath}\nresource file: ${detail.filePath}\nguide: ${detail.guidePath}\n\nYou are helping configure a resource. Read the GUIDE.md for instructions on how to help. Read the RESOURCE.md for context about what this resource is. Write config values to the config.json file.\n</frontmatter>`;
|
||||||
|
const defaultInput = isNew
|
||||||
|
? 'Help me set up this new resource'
|
||||||
|
: 'Help me configure this resource';
|
||||||
|
|
||||||
const LocalAvailabilitySection = ({ resource, onRun }: LocalAvailabilitySectionProps) => {
|
const pi = usePiChat(undefined, undefined, { replaceUrl: false });
|
||||||
const { runCommand } = useResources();
|
|
||||||
const [runningAction, setRunningAction] = useState<ResourceAction | null>(null);
|
|
||||||
|
|
||||||
const isSudo = (cmd: string) => cmd.trimStart().startsWith('sudo');
|
const onResponseEndRef = useRef(onResponseEnd);
|
||||||
|
onResponseEndRef.current = onResponseEnd;
|
||||||
|
|
||||||
const handleAction = async (action: ResourceAction, command: string) => {
|
const wasGenerating = useRef(false);
|
||||||
if (isSudo(command)) {
|
useEffect(() => {
|
||||||
onRun(command);
|
if (wasGenerating.current && !pi.isGenerating) {
|
||||||
return;
|
onResponseEndRef.current();
|
||||||
}
|
}
|
||||||
setRunningAction(action);
|
wasGenerating.current = pi.isGenerating;
|
||||||
try {
|
}, [pi.isGenerating]);
|
||||||
const result = await runCommand(resource.id, action);
|
|
||||||
if (result.exitCode === 0) {
|
|
||||||
toast.success('Command completed successfully');
|
|
||||||
} else {
|
|
||||||
toast.error(result.output || `Command failed (exit code ${result.exitCode})`, { duration: 8000 });
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
toast.error('Failed to run command');
|
|
||||||
} finally {
|
|
||||||
setRunningAction(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-2">
|
<EmbeddableChat
|
||||||
{resource.installed ? (
|
chat={pi}
|
||||||
<>
|
defaultInput={defaultInput}
|
||||||
<div>
|
promptPrefix={promptFrontmatter}
|
||||||
<span className="text-xs bg-green-100 text-green-700 rounded-full px-2 py-0.5">Installed</span>
|
className="h-full"
|
||||||
</div>
|
|
||||||
{resource.version && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{resource.updateCommand && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs cursor-pointer"
|
|
||||||
onClick={() => handleAction('update', resource.updateCommand!)}
|
|
||||||
disabled={!!runningAction}
|
|
||||||
>
|
|
||||||
<RefreshCw className={`h-3 w-3 mr-1 ${runningAction === 'update' ? 'animate-spin' : ''}`} />
|
|
||||||
Update
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<span className="text-xs text-duck-dark/50 dark:text-foreground/50">{resource.version}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
{!resource.version && resource.updateCommand && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs cursor-pointer"
|
|
||||||
onClick={() => handleAction('update', resource.updateCommand!)}
|
|
||||||
disabled={!!runningAction}
|
|
||||||
>
|
|
||||||
<RefreshCw className={`h-3 w-3 mr-1 ${runningAction === 'update' ? 'animate-spin' : ''}`} />
|
|
||||||
Update
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{resource.verifyCommand && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs cursor-pointer"
|
|
||||||
onClick={() => handleAction('verify', resource.verifyCommand!)}
|
|
||||||
disabled={!!runningAction}
|
|
||||||
>
|
|
||||||
{runningAction === 'verify' && <Loader2 className="h-3 w-3 mr-1 animate-spin" />}
|
|
||||||
Verify
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{resource.manageCommand && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs cursor-pointer"
|
|
||||||
onClick={() => handleAction('manage', resource.manageCommand!)}
|
|
||||||
disabled={!!runningAction}
|
|
||||||
>
|
|
||||||
{runningAction === 'manage' && <Loader2 className="h-3 w-3 mr-1 animate-spin" />}
|
|
||||||
Manage
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{resource.uninstallCommand && (
|
|
||||||
<div className="flex items-center mt-1.5">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs cursor-pointer text-red-500 hover:text-red-600 border-red-500/30 hover:border-red-500/50 hover:bg-red-500/5"
|
|
||||||
onClick={() => handleAction('uninstall', resource.uninstallCommand!)}
|
|
||||||
disabled={!!runningAction}
|
|
||||||
>
|
|
||||||
{runningAction === 'uninstall' ? (
|
|
||||||
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Trash2 className="h-3 w-3 mr-1" />
|
|
||||||
)}
|
|
||||||
Uninstall
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<span className="text-xs bg-duck-dark/5 text-duck-dark/40 rounded-full px-2 py-0.5">Not installed</span>
|
|
||||||
{resource.installCommand && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
className="h-6 text-xs bg-duck-teal text-duck-yellow hover:bg-duck-teal/90 cursor-pointer"
|
|
||||||
onClick={() => handleAction('install', resource.installCommand!)}
|
|
||||||
disabled={runningAction === 'install'}
|
|
||||||
>
|
|
||||||
{runningAction === 'install' ? 'Installing...' : 'Install'}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
type CatalogCardProps = {
|
|
||||||
resource: Resource;
|
|
||||||
onSelect: (id: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const CatalogCard = ({ resource: r, onSelect }: CatalogCardProps) => {
|
|
||||||
const category = getResourceCategory(r);
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={() => onSelect(r.id)}
|
|
||||||
className="flex flex-col gap-2 p-4 rounded-lg border border-duck-dark/10 text-left cursor-pointer transition-colors hover:border-duck-teal/30 hover:bg-duck-teal/5"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{r.port ? (
|
|
||||||
<Server className="h-3.5 w-3.5 text-duck-teal shrink-0" />
|
|
||||||
) : (
|
|
||||||
<Wrench className="h-3.5 w-3.5 text-duck-dark/40 shrink-0" />
|
|
||||||
)}
|
|
||||||
<span className="text-sm font-medium text-duck-dark truncate">{r.name}</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-duck-dark/40 line-clamp-1">{r.subtitle}</p>
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<span className="text-[10px] bg-duck-dark/5 text-duck-dark/40 rounded-full px-1.5 py-0.5">{r.type}</span>
|
|
||||||
<span
|
|
||||||
className={`text-[10px] rounded-full px-1.5 py-0.5 ${category === 'api-based' ? 'bg-duck-teal/10 text-duck-teal' : 'bg-duck-dark/5 text-duck-dark/40'}`}
|
|
||||||
>
|
|
||||||
{category === 'api-based' ? 'API' : 'CLI'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ResourceCatalog = () => {
|
|
||||||
const { resources, isLoading } = useResources();
|
|
||||||
const [, setSelectedId] = useGlobal<string | null>('RESOURCE_SELECTED', null);
|
|
||||||
const [, setShowCatalog] = useGlobal<boolean>('RESOURCE_CATALOG', false);
|
|
||||||
const [search, setSearch] = useState('');
|
|
||||||
|
|
||||||
const query = search.toLowerCase();
|
|
||||||
const filtered =
|
|
||||||
resources?.filter(
|
|
||||||
(r: Resource) =>
|
|
||||||
!r.installed &&
|
|
||||||
(r.name.toLowerCase().includes(query) ||
|
|
||||||
r.subtitle.toLowerCase().includes(query) ||
|
|
||||||
r.description.toLowerCase().includes(query)),
|
|
||||||
) ?? [];
|
|
||||||
|
|
||||||
const apiBased = filtered.filter((r: Resource) => getResourceCategory(r) === 'api-based');
|
|
||||||
const localCli = filtered.filter((r: Resource) => getResourceCategory(r) === 'local-cli');
|
|
||||||
|
|
||||||
const handleSelect = (id: string) => {
|
|
||||||
setShowCatalog(false);
|
|
||||||
setSelectedId(id);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-full overflow-y-auto p-6">
|
|
||||||
<h2 className="text-lg font-bold text-duck-dark mb-1">Resource Catalog</h2>
|
|
||||||
<p className="text-sm text-duck-dark/40 mb-4">All available resources. Select one to configure.</p>
|
|
||||||
<Input
|
|
||||||
placeholder="Search resources..."
|
|
||||||
value={search}
|
|
||||||
onChange={(ev) => setSearch(ev.target.value)}
|
|
||||||
className="h-8 text-xs mb-4 max-w-xs"
|
|
||||||
/>
|
/>
|
||||||
{isLoading && <p className="text-xs text-duck-dark/50">Loading...</p>}
|
|
||||||
{apiBased.length > 0 && (
|
|
||||||
<div className="mb-6">
|
|
||||||
<div className="flex items-center gap-2 mb-3">
|
|
||||||
<Server className="h-3.5 w-3.5 text-duck-teal" />
|
|
||||||
<span className="text-xs font-semibold uppercase tracking-wider text-duck-dark/40">API Based</span>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 xl:grid-cols-3 gap-3">
|
|
||||||
{apiBased.map((r: Resource) => (
|
|
||||||
<CatalogCard key={r.id} resource={r} onSelect={handleSelect} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{localCli.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center gap-2 mb-3">
|
|
||||||
<Wrench className="h-3.5 w-3.5 text-duck-dark/40" />
|
|
||||||
<span className="text-xs font-semibold uppercase tracking-wider text-duck-dark/40">Local CLI</span>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 xl:grid-cols-3 gap-3">
|
|
||||||
{localCli.map((r: Resource) => (
|
|
||||||
<CatalogCard key={r.id} resource={r} onSelect={handleSelect} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ResourceDetail = ({ resource }: { resource: Resource }) => {
|
|
||||||
const category = getResourceCategory(resource);
|
|
||||||
const [, setRunCommand] = usePanelChannel<RunCommandState>(RUN_COMMAND_CHANNEL, null);
|
|
||||||
const [confirmCommand, setConfirmCommand] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const handleRun = (command: string) => {
|
|
||||||
const isSudo = command.trimStart().startsWith('sudo');
|
|
||||||
if (isSudo) {
|
|
||||||
setConfirmCommand(command);
|
|
||||||
} else {
|
|
||||||
setRunCommand({ command });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className="h-full overflow-y-auto p-6">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
{resource.port ? (
|
|
||||||
<Server className="h-4 w-4 text-duck-teal shrink-0" />
|
|
||||||
) : (
|
|
||||||
<Wrench className="h-4 w-4 text-duck-dark/40 shrink-0" />
|
|
||||||
)}
|
|
||||||
<h2 className="text-lg font-bold text-duck-dark">{resource.name}</h2>
|
|
||||||
<span className="text-sm text-duck-dark/40">{resource.subtitle}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2 mb-4">
|
|
||||||
<span className="text-xs bg-duck-dark/5 text-duck-dark/50 rounded-full px-2 py-0.5">{resource.type}</span>
|
|
||||||
<span
|
|
||||||
className={`text-xs rounded-full px-2 py-0.5 ${category === 'api-based' ? 'bg-duck-teal/10 text-duck-teal' : 'bg-duck-dark/5 text-duck-dark/50'}`}
|
|
||||||
>
|
|
||||||
{category === 'api-based' ? 'API Based' : 'Local CLI'}
|
|
||||||
</span>
|
|
||||||
{resource.port && (
|
|
||||||
<span className="text-xs bg-duck-teal/10 text-duck-teal rounded-full px-2 py-0.5">:{resource.port}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="text-sm text-duck-dark/70 mb-6">{resource.description}</p>
|
|
||||||
|
|
||||||
{category === 'api-based' && <ConnectionSection key={resource.id} resource={resource} />}
|
|
||||||
<LocalAvailabilitySection resource={resource} onRun={handleRun} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<AlertDialog open={!!confirmCommand} onOpenChange={(open) => !open && setConfirmCommand(null)}>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle>Run with elevated privileges</AlertDialogTitle>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<p className="text-sm text-duck-dark/70 dark:text-foreground/70">
|
|
||||||
For this operation the script must be run with elevated privileges (sudo) on the host machine.
|
|
||||||
<br />
|
|
||||||
Not to worry, though, we wrote it and battle tested it ourselves.
|
|
||||||
</p>
|
|
||||||
<code className="text-sm font-mono bg-[#1a1a2e] text-[#e0e0e0] rounded-lg px-3 py-2 break-all">{confirmCommand}</code>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel className="cursor-pointer">Cancel</AlertDialogCancel>
|
|
||||||
<AlertDialogAction
|
|
||||||
className="cursor-pointer bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold"
|
|
||||||
onClick={() => {
|
|
||||||
if (confirmCommand) setRunCommand({ command: confirmCommand });
|
|
||||||
setConfirmCommand(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Run
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Resources = () => {
|
export const Resources = () => {
|
||||||
const { resources } = useResources();
|
const client = useClient();
|
||||||
const [selectedId] = useGlobal<string | null>('RESOURCE_SELECTED', null);
|
const qc = useQueryClient();
|
||||||
const [showCatalog] = useGlobal<boolean>('RESOURCE_CATALOG', false);
|
const [selectedName] = useGlobal<string | null>('RESOURCE_SELECTED', null);
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [isNew, setIsNew] = useState(false);
|
||||||
|
const [deleteConfirm, setDeleteConfirm] = useState(false);
|
||||||
|
const [showDetail, setShowDetail] = useState(false);
|
||||||
|
|
||||||
const resource = selectedId ? resources?.find((r: Resource) => r.id === selectedId) : null;
|
const { data: detail, refetch } = useQuery<ResourceDetail>({
|
||||||
|
queryKey: ['RESOURCES', selectedName],
|
||||||
|
queryFn: () => client.get<ResourceDetail>(`/server-settings/resources/${selectedName}`),
|
||||||
|
enabled: !!selectedName,
|
||||||
|
});
|
||||||
|
|
||||||
if (showCatalog || !resource) return <ResourceCatalog />;
|
useEffect(() => {
|
||||||
return <ResourceDetail resource={resource} />;
|
if (selectedName) {
|
||||||
|
setShowDetail(true);
|
||||||
|
setEditing(false);
|
||||||
|
}
|
||||||
|
}, [selectedName]);
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!selectedName) return;
|
||||||
|
try {
|
||||||
|
await client.delete(`/server-settings/resources/${selectedName}`);
|
||||||
|
setDeleteConfirm(false);
|
||||||
|
setEditing(false);
|
||||||
|
await qc.invalidateQueries({ queryKey: ['RESOURCES'] });
|
||||||
|
} catch {
|
||||||
|
toast.error('Failed to delete resource');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const canDelete = detail && detail.scope === 'global' && !detail.filePath.includes('/seed/');
|
||||||
|
|
||||||
|
if (!selectedName || !detail) {
|
||||||
|
return (
|
||||||
|
<div className="h-full flex items-center justify-center">
|
||||||
|
<p className="text-sm text-duck-dark/40">Select a resource to view its configuration</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Detail panel */}
|
||||||
|
<div className={`flex-1 overflow-hidden flex flex-col min-h-0 ${editing ? 'hidden md:flex' : ''}`}>
|
||||||
|
<div className="shrink-0 px-4 py-2 border-b border-duck-dark/10 bg-background/60 flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setShowDetail(false)}
|
||||||
|
className="md:hidden p-1 -ml-1 rounded hover:bg-duck-dark/10 cursor-pointer"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4 text-duck-dark/60" />
|
||||||
|
</button>
|
||||||
|
<span className="text-sm font-medium text-duck-dark/70 flex-1">{detail.name}</span>
|
||||||
|
<span
|
||||||
|
className={`shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium ${
|
||||||
|
detail.scope === 'global' ? 'bg-duck-teal/20 text-duck-teal' : 'bg-duck-dark/10 text-duck-dark/60'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{detail.scope}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing((e) => !e)}
|
||||||
|
className={`p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors ${editing ? 'bg-duck-teal/10' : ''}`}
|
||||||
|
>
|
||||||
|
<Pencil className={`h-3.5 w-3.5 ${editing ? 'text-duck-teal' : 'text-duck-dark/50'}`} />
|
||||||
|
</button>
|
||||||
|
{canDelete && (
|
||||||
|
<button
|
||||||
|
onClick={() => setDeleteConfirm(true)}
|
||||||
|
className="p-1 rounded hover:bg-red-50 cursor-pointer transition-colors"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5 text-duck-dark/50 hover:text-red-500" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="overflow-y-auto flex-1 p-6">
|
||||||
|
{detail.rawFrontmatter && <FrontmatterBlock yaml={detail.rawFrontmatter} />}
|
||||||
|
{detail.body && (
|
||||||
|
<article className="skill-md mb-6">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
|
||||||
|
{detail.body}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</article>
|
||||||
|
)}
|
||||||
|
<ConfigEditor
|
||||||
|
key={selectedName}
|
||||||
|
resourceName={selectedName}
|
||||||
|
config={detail.config}
|
||||||
|
onSaved={() => refetch()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chat panel */}
|
||||||
|
{editing && (
|
||||||
|
<div className="flex-1 overflow-hidden flex flex-col min-h-0">
|
||||||
|
<div className="shrink-0 px-4 py-1.5 border-b border-duck-dark/10 bg-background/60 flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing(false)}
|
||||||
|
className="md:hidden p-1 -ml-1 rounded hover:bg-duck-dark/10 cursor-pointer"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4 text-duck-dark/60" />
|
||||||
|
</button>
|
||||||
|
<span className="text-xs font-medium text-duck-dark/50 flex-1">{detail.name} — Chat</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditing(false)}
|
||||||
|
className="p-1 rounded hover:bg-duck-dark/10 cursor-pointer transition-colors"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5 text-duck-dark/50" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<ResourceChat
|
||||||
|
key={detail.filePath}
|
||||||
|
detail={detail}
|
||||||
|
isNew={isNew}
|
||||||
|
onResponseEnd={() => {
|
||||||
|
refetch();
|
||||||
|
qc.invalidateQueries({ queryKey: ['RESOURCES'] });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog open={deleteConfirm} onOpenChange={setDeleteConfirm}>
|
||||||
|
<DialogContent className="sm:max-w-md z-[700]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Delete Resource</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Are you sure you want to delete "{detail.name}"? This action cannot be undone.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="flex justify-end gap-2 mt-2">
|
||||||
|
<Button variant="outline" onClick={() => setDeleteConfirm(false)} className="cursor-pointer">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={handleDelete} className="cursor-pointer">
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,22 +1,11 @@
|
|||||||
import { useState, useEffect, useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { X } from 'lucide-react';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
|
||||||
import type { LayoutNode, PanelComponents } from 'officerdev';
|
import type { LayoutNode, PanelComponents } from 'officerdev';
|
||||||
import { WorkspaceLayout, TerminalView, FileViewerView } from 'officerdev';
|
import { WorkspaceLayout } from 'officerdev';
|
||||||
import { usePanelChannel } from 'hooks/usePanelChannel';
|
|
||||||
import { useClient } from 'hooks/useClient';
|
|
||||||
|
|
||||||
import { Resources } from './Resources';
|
import { Resources } from './Resources';
|
||||||
import { ResourceSidebar } from './ResourceSidebar';
|
import { ResourceSidebar } from './ResourceSidebar';
|
||||||
import {
|
|
||||||
RUN_COMMAND_CHANNEL,
|
|
||||||
ERROR_LOG_CHANNEL,
|
|
||||||
type RunCommandState,
|
|
||||||
type ErrorLogState,
|
|
||||||
} from './run-command-channel';
|
|
||||||
|
|
||||||
const baseLayout: LayoutNode = {
|
const layout: LayoutNode = {
|
||||||
type: 'group',
|
type: 'group',
|
||||||
id: 'resources-root',
|
id: 'resources-root',
|
||||||
direction: 'horizontal',
|
direction: 'horizontal',
|
||||||
@@ -26,147 +15,11 @@ const baseLayout: LayoutNode = {
|
|||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const splitLayout: LayoutNode = {
|
|
||||||
type: 'group',
|
|
||||||
id: 'resources-root',
|
|
||||||
direction: 'horizontal',
|
|
||||||
children: [
|
|
||||||
{ node: { type: 'panel', id: 'resources-left', appType: null }, size: 20 },
|
|
||||||
{
|
|
||||||
node: {
|
|
||||||
type: 'group',
|
|
||||||
id: 'resources-right-group',
|
|
||||||
direction: 'vertical',
|
|
||||||
children: [
|
|
||||||
{ node: { type: 'panel', id: 'resources-right', appType: null }, size: 50 },
|
|
||||||
{ node: { type: 'panel', id: 'resources-terminal', appType: null }, size: 50 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
size: 80,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const errorLayout: LayoutNode = {
|
|
||||||
type: 'group',
|
|
||||||
id: 'resources-root',
|
|
||||||
direction: 'horizontal',
|
|
||||||
children: [
|
|
||||||
{ node: { type: 'panel', id: 'resources-left', appType: null }, size: 20 },
|
|
||||||
{
|
|
||||||
node: {
|
|
||||||
type: 'group',
|
|
||||||
id: 'resources-right-group',
|
|
||||||
direction: 'vertical',
|
|
||||||
children: [
|
|
||||||
{ node: { type: 'panel', id: 'resources-right', appType: null }, size: 50 },
|
|
||||||
{ node: { type: 'panel', id: 'resources-error-log', appType: null }, size: 50 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
size: 80,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const ResourceTerminalPanel = () => {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const client = useClient();
|
|
||||||
const [state, setState] = usePanelChannel<RunCommandState>(RUN_COMMAND_CHANNEL, null);
|
|
||||||
const [, setErrorLog] = usePanelChannel<ErrorLogState>(ERROR_LOG_CHANNEL, null);
|
|
||||||
const [session, setSession] = useState<{ id: string; command: string } | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (state && (!session || session.command !== state.command)) {
|
|
||||||
setSession({ id: `res-cmd-${Date.now()}`, command: state.command });
|
|
||||||
} else if (!state) {
|
|
||||||
setSession(null);
|
|
||||||
}
|
|
||||||
}, [state]);
|
|
||||||
|
|
||||||
const close = () => setState(null);
|
|
||||||
|
|
||||||
const onCommandDone = (exitCode: number, output: string) => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['RESOURCES'] });
|
|
||||||
if (exitCode === 0) {
|
|
||||||
toast.success('Command completed successfully');
|
|
||||||
setTimeout(() => setState(null), 2000);
|
|
||||||
} else {
|
|
||||||
const command = session?.command ?? 'unknown';
|
|
||||||
const md = [
|
|
||||||
`# Command Failed (exit code ${exitCode})`,
|
|
||||||
'',
|
|
||||||
'```',
|
|
||||||
command,
|
|
||||||
'```',
|
|
||||||
'',
|
|
||||||
'## Output',
|
|
||||||
'',
|
|
||||||
'```',
|
|
||||||
output,
|
|
||||||
'```',
|
|
||||||
].join('\n');
|
|
||||||
|
|
||||||
client.post('/server-settings/resources/error-log', { command, output, exitCode }).catch(() => {});
|
|
||||||
|
|
||||||
setState(null);
|
|
||||||
setErrorLog({ content: md, fileName: 'error.md' });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!state || !session) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-full flex flex-col">
|
|
||||||
<div className="shrink-0 px-4 py-1.5 border-b border-duck-dark/10 dark:border-foreground/10 bg-background/60 flex items-center gap-2">
|
|
||||||
<span className="text-xs font-medium text-duck-dark/50 dark:text-foreground/50 flex-1">Run Command</span>
|
|
||||||
<button
|
|
||||||
onClick={close}
|
|
||||||
className="p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 cursor-pointer transition-colors"
|
|
||||||
>
|
|
||||||
<X className="h-3.5 w-3.5 text-duck-dark/50 dark:text-foreground/50" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<TerminalView
|
|
||||||
className="flex-1"
|
|
||||||
sandboxed={false}
|
|
||||||
command={session.command}
|
|
||||||
sessionId={session.id}
|
|
||||||
onCommandDone={onCommandDone}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ErrorLogPanel = () => {
|
|
||||||
const [errorLog, setErrorLog] = usePanelChannel<ErrorLogState>(ERROR_LOG_CHANNEL, null);
|
|
||||||
|
|
||||||
if (!errorLog) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<FileViewerView
|
|
||||||
filePath=""
|
|
||||||
fileName={errorLog.fileName}
|
|
||||||
content={errorLog.content}
|
|
||||||
onClose={() => setErrorLog(null)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ResourceSettings = () => {
|
export const ResourceSettings = () => {
|
||||||
const [runCommand] = usePanelChannel<RunCommandState>(RUN_COMMAND_CHANNEL, null);
|
|
||||||
const [errorLog] = usePanelChannel<ErrorLogState>(ERROR_LOG_CHANNEL, null);
|
|
||||||
|
|
||||||
const layout = useMemo(
|
|
||||||
() => (errorLog ? errorLayout : runCommand ? splitLayout : baseLayout),
|
|
||||||
[errorLog, runCommand],
|
|
||||||
);
|
|
||||||
|
|
||||||
const panelComponents: PanelComponents = useMemo(
|
const panelComponents: PanelComponents = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
'resources-left': ResourceSidebar,
|
'resources-left': ResourceSidebar,
|
||||||
'resources-right': Resources,
|
'resources-right': Resources,
|
||||||
'resources-terminal': ResourceTerminalPanel,
|
|
||||||
'resources-error-log': ErrorLogPanel,
|
|
||||||
}),
|
}),
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
export type RunCommandState = {
|
|
||||||
command: string;
|
|
||||||
} | null;
|
|
||||||
|
|
||||||
export const RUN_COMMAND_CHANNEL = 'resource-settings:run-command';
|
|
||||||
|
|
||||||
export type ErrorLogState = {
|
|
||||||
content: string;
|
|
||||||
fileName: string;
|
|
||||||
} | null;
|
|
||||||
|
|
||||||
export const ERROR_LOG_CHANNEL = 'resource-settings:error-log';
|
|
||||||
@@ -106,6 +106,7 @@ integrationsRouter.get('/google/status', async (ctx) => {
|
|||||||
configured: !!(config?.clientId && config?.clientSecret),
|
configured: !!(config?.clientId && config?.clientSecret),
|
||||||
connected: !!connection?.accessToken,
|
connected: !!connection?.accessToken,
|
||||||
email: connection?.email ?? null,
|
email: connection?.email ?? null,
|
||||||
|
picture: connection?.picture ?? null,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -201,9 +202,11 @@ export const googleCallbackHandler = async (ctx: any) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let googleEmail = email;
|
let googleEmail = email;
|
||||||
|
let picture: string | null = null;
|
||||||
if (userinfoResponse.ok) {
|
if (userinfoResponse.ok) {
|
||||||
const userinfo = await userinfoResponse.json();
|
const userinfo = await userinfoResponse.json();
|
||||||
googleEmail = userinfo.email ?? email;
|
googleEmail = userinfo.email ?? email;
|
||||||
|
picture = userinfo.picture ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
await writeUserGoogle(email, {
|
await writeUserGoogle(email, {
|
||||||
@@ -211,6 +214,7 @@ export const googleCallbackHandler = async (ctx: any) => {
|
|||||||
refreshToken: tokens.refresh_token,
|
refreshToken: tokens.refresh_token,
|
||||||
expiresAt: Date.now() + tokens.expires_in * 1000,
|
expiresAt: Date.now() + tokens.expires_in * 1000,
|
||||||
email: googleEmail,
|
email: googleEmail,
|
||||||
|
picture,
|
||||||
scope: tokens.scope,
|
scope: tokens.scope,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { join, relative } from "path";
|
import { join, relative } from "path";
|
||||||
import { readdirSync, existsSync, mkdirSync } from "node:fs";
|
import { readdirSync, existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
||||||
import type { Subprocess } from "bun";
|
import type { Subprocess } from "bun";
|
||||||
import type { PiEvent, MessageCost } from "./types";
|
import type { PiEvent, MessageCost } from "./types";
|
||||||
import { readApiKeys } from "../server-settings/pi-mono";
|
import { readApiKeys } from "../server-settings/pi-mono";
|
||||||
import { readSearxngConfig } from "../server-settings/searxng";
|
import { readSearxngConfig } from "../server-settings/searxng";
|
||||||
import { PI_CONFIG_DIR, getGlobalSkillsDir, getUserSkillsDir, getGlobalExtensionsDir, getUserExtensionsDir, getGlobalToolsDir, getUserToolsDir } from "../../data-path";
|
import { PI_CONFIG_DIR, DATA_PATH, getGlobalSkillsDir, getUserSkillsDir, getGlobalExtensionsDir, getUserExtensionsDir, getGlobalToolsDir, getUserToolsDir, getNativeResourcesDir, getGlobalResourcesDir } from "../../data-path";
|
||||||
import { ensureDockerContainer } from "../terminal/websocket";
|
import { ensureDockerContainer } from "../terminal/websocket";
|
||||||
import { logger } from "./logger";
|
import { logger } from "./logger";
|
||||||
|
import { parseFrontmatter } from "../skills/skills";
|
||||||
|
|
||||||
export type PiEventHandler = (event: PiEvent) => void;
|
export type PiEventHandler = (event: PiEvent) => void;
|
||||||
|
|
||||||
@@ -52,6 +53,106 @@ function collectExtensionFlags(email: string, containerPaths?: PathOverrides): s
|
|||||||
return flags;
|
return flags;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function generateResourceSkill(outputDir: string): string | null {
|
||||||
|
const nativeDir = getNativeResourcesDir();
|
||||||
|
const globalDir = getGlobalResourcesDir();
|
||||||
|
|
||||||
|
// Collect all resource dirs (global overrides native)
|
||||||
|
const resourceDirs = new Map<string, string>();
|
||||||
|
for (const dir of [nativeDir, globalDir]) {
|
||||||
|
if (!existsSync(dir)) continue;
|
||||||
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
if (existsSync(join(dir, entry.name, 'RESOURCE.md'))) {
|
||||||
|
resourceDirs.set(entry.name, dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resourceDirs.size === 0) return null;
|
||||||
|
|
||||||
|
const sections: string[] = [];
|
||||||
|
for (const [name, baseDir] of resourceDirs) {
|
||||||
|
const resourceMd = join(baseDir, name, 'RESOURCE.md');
|
||||||
|
let mdContent = '';
|
||||||
|
try { mdContent = readFileSync(resourceMd, 'utf-8'); } catch { continue; }
|
||||||
|
const { frontmatter } = parseFrontmatter(mdContent);
|
||||||
|
|
||||||
|
// Merge native + global config
|
||||||
|
let nativeConfig: Record<string, string> = {};
|
||||||
|
let globalConfig: Record<string, string> = {};
|
||||||
|
try { nativeConfig = JSON.parse(readFileSync(join(nativeDir, name, 'config.json'), 'utf-8')); } catch {}
|
||||||
|
try { globalConfig = JSON.parse(readFileSync(join(globalDir, name, 'config.json'), 'utf-8')); } catch {}
|
||||||
|
|
||||||
|
const config: Record<string, string> = {};
|
||||||
|
for (const key of Object.keys(nativeConfig)) config[key] = globalConfig[key] ?? nativeConfig[key]!;
|
||||||
|
for (const key of Object.keys(globalConfig)) if (!(key in config)) config[key] = globalConfig[key]!;
|
||||||
|
|
||||||
|
const hasValues = Object.values(config).some((v) => v !== '');
|
||||||
|
const configLines = Object.entries(config)
|
||||||
|
.filter(([, v]) => v)
|
||||||
|
.map(([k, v]) => /key|secret|password|token/i.test(k) ? `- **${k}**: (configured)` : `- **${k}**: ${v}`);
|
||||||
|
|
||||||
|
sections.push([
|
||||||
|
`### ${frontmatter.name || name}`,
|
||||||
|
hasValues ? 'Status: **configured**' : 'Status: not configured',
|
||||||
|
...configLines,
|
||||||
|
].join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const skillContent = [
|
||||||
|
'---',
|
||||||
|
'name: Available Resources',
|
||||||
|
'description: External services and APIs configured on this Officer instance',
|
||||||
|
'---',
|
||||||
|
'',
|
||||||
|
'These are external services available to you. Use their configured URLs directly via HTTP requests.',
|
||||||
|
'Do NOT try to install local alternatives (like tesseract, whisper, etc.) — use the configured HTTP APIs instead.',
|
||||||
|
'',
|
||||||
|
...sections,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const skillDir = join(outputDir, '.generated', 'available-resources');
|
||||||
|
mkdirSync(skillDir, { recursive: true });
|
||||||
|
writeFileSync(join(skillDir, 'SKILL.md'), skillContent, 'utf-8');
|
||||||
|
return skillDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildResourcesEnv(): string {
|
||||||
|
const nativeDir = getNativeResourcesDir();
|
||||||
|
const globalDir = getGlobalResourcesDir();
|
||||||
|
|
||||||
|
const resourceDirs = new Map<string, string>();
|
||||||
|
for (const dir of [nativeDir, globalDir]) {
|
||||||
|
if (!existsSync(dir)) continue;
|
||||||
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
if (existsSync(join(dir, entry.name, 'RESOURCE.md')) || existsSync(join(dir, entry.name, 'config.json'))) {
|
||||||
|
resourceDirs.set(entry.name, dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: Record<string, Record<string, string>> = {};
|
||||||
|
for (const [name] of resourceDirs) {
|
||||||
|
let nativeConfig: Record<string, string> = {};
|
||||||
|
let globalConfig: Record<string, string> = {};
|
||||||
|
try { nativeConfig = JSON.parse(readFileSync(join(nativeDir, name, 'config.json'), 'utf-8')); } catch {}
|
||||||
|
try { globalConfig = JSON.parse(readFileSync(join(globalDir, name, 'config.json'), 'utf-8')); } catch {}
|
||||||
|
|
||||||
|
const config: Record<string, string> = {};
|
||||||
|
for (const key of Object.keys(nativeConfig)) config[key] = globalConfig[key] ?? nativeConfig[key]!;
|
||||||
|
for (const key of Object.keys(globalConfig)) if (!(key in config)) config[key] = globalConfig[key]!;
|
||||||
|
|
||||||
|
// Only include resources that have at least one non-empty value
|
||||||
|
if (Object.values(config).some((v) => v !== '')) {
|
||||||
|
result[name] = config;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.stringify(result);
|
||||||
|
}
|
||||||
|
|
||||||
type SandboxOptions = {
|
type SandboxOptions = {
|
||||||
userId: number;
|
userId: number;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -87,19 +188,27 @@ export async function spawnPi(
|
|||||||
user: '/officer/user/extensions',
|
user: '/officer/user/extensions',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Generate resource context skill (host-side, mounted into container)
|
||||||
|
const resourceSkillHost = generateResourceSkill(DATA_PATH);
|
||||||
|
const resourceSkillFlags = resourceSkillHost ? ['--skill', '/officer/generated/available-resources'] : [];
|
||||||
|
|
||||||
const piArgs = [
|
const piArgs = [
|
||||||
'pi', '--mode', 'rpc',
|
'pi', '--mode', 'rpc',
|
||||||
'--no-skills', '--no-prompt-templates', '--no-themes',
|
'--no-skills', '--no-prompt-templates', '--no-themes',
|
||||||
...skillFlags,
|
...skillFlags,
|
||||||
...extensionFlags,
|
...extensionFlags,
|
||||||
|
...resourceSkillFlags,
|
||||||
];
|
];
|
||||||
if (model) piArgs.push('--model', model);
|
if (model) piArgs.push('--model', model);
|
||||||
|
|
||||||
|
const resourcesEnv = buildResourcesEnv();
|
||||||
|
|
||||||
const envFlags = [
|
const envFlags = [
|
||||||
'-e', `PI_CODING_AGENT_DIR=${containerPiConfig}`,
|
'-e', `PI_CODING_AGENT_DIR=${containerPiConfig}`,
|
||||||
'-e', `HOME=${containerHome}`,
|
'-e', `HOME=${containerHome}`,
|
||||||
'-e', `PI_TOOLS_DIRS=/officer/tools:/officer/user/tools`,
|
'-e', `PI_TOOLS_DIRS=/officer/tools:/officer/user/tools`,
|
||||||
'-e', `PI_SEARXNG_URL=${searxng.url}`,
|
'-e', `PI_SEARXNG_URL=${searxng.url}`,
|
||||||
|
'-e', `OFFICER_RESOURCES=${resourcesEnv}`,
|
||||||
];
|
];
|
||||||
for (const [key, value] of Object.entries(storedKeys)) {
|
for (const [key, value] of Object.entries(storedKeys)) {
|
||||||
if (value?.trim()) envFlags.push('-e', `${key}=${value.trim()}`);
|
if (value?.trim()) envFlags.push('-e', `${key}=${value.trim()}`);
|
||||||
@@ -130,7 +239,12 @@ export async function spawnPi(
|
|||||||
const searxng = await readSearxngConfig();
|
const searxng = await readSearxngConfig();
|
||||||
const skillFlags = collectSkillFlags(email);
|
const skillFlags = collectSkillFlags(email);
|
||||||
const extensionFlags = collectExtensionFlags(email);
|
const extensionFlags = collectExtensionFlags(email);
|
||||||
const args = ['pi', '--mode', 'rpc', '--no-skills', '--no-prompt-templates', '--no-themes', ...skillFlags, ...extensionFlags];
|
|
||||||
|
// Generate resource context skill
|
||||||
|
const resourceSkillDir = generateResourceSkill(DATA_PATH);
|
||||||
|
const resourceSkillFlags = resourceSkillDir ? ['--skill', resourceSkillDir] : [];
|
||||||
|
|
||||||
|
const args = ['pi', '--mode', 'rpc', '--no-skills', '--no-prompt-templates', '--no-themes', ...skillFlags, ...extensionFlags, ...resourceSkillFlags];
|
||||||
if (model) args.push('--model', model);
|
if (model) args.push('--model', model);
|
||||||
|
|
||||||
if (!existsSync(cwd)) {
|
if (!existsSync(cwd)) {
|
||||||
@@ -144,7 +258,7 @@ export async function spawnPi(
|
|||||||
stdin: 'pipe',
|
stdin: 'pipe',
|
||||||
stdout: 'pipe',
|
stdout: 'pipe',
|
||||||
stderr: 'pipe',
|
stderr: 'pipe',
|
||||||
env: { ...process.env, ...storedKeys, PI_CODING_AGENT_DIR: PI_CONFIG_DIR, PI_TOOLS_DIRS: toolsDirs, PI_SEARXNG_URL: searxng.url },
|
env: { ...process.env, ...storedKeys, PI_CODING_AGENT_DIR: PI_CONFIG_DIR, PI_TOOLS_DIRS: toolsDirs, PI_SEARXNG_URL: searxng.url, OFFICER_RESOURCES: buildResourcesEnv() },
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.info('Spawned Pi locally', {
|
logger.info('Spawned Pi locally', {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createRouter } from '../../create-router';
|
import { createRouter } from '../../create-router';
|
||||||
import { settingsPath } from './server-settings';
|
import { settingsPath } from './server-settings';
|
||||||
|
import { readResourceConfig } from './resources';
|
||||||
|
|
||||||
type OcrConfig = {
|
type OcrConfig = {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -7,6 +8,9 @@ type OcrConfig = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export async function readOcrConfig(): Promise<OcrConfig | undefined> {
|
export async function readOcrConfig(): Promise<OcrConfig | undefined> {
|
||||||
|
const config = await readResourceConfig('optical-character-recognition');
|
||||||
|
if (config.url) return { url: config.url, model: config.model ?? '' };
|
||||||
|
// Fallback to legacy settings.json
|
||||||
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
return settings.ocr as OcrConfig | undefined;
|
return settings.ocr as OcrConfig | undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,259 +1,224 @@
|
|||||||
import { readdir, mkdir } from 'node:fs/promises';
|
import { readdir, mkdir, rm } from 'node:fs/promises';
|
||||||
import { existsSync } from 'node:fs';
|
import { join, dirname } from 'node:path';
|
||||||
import { join } from 'node:path';
|
|
||||||
import { createRouter } from '../../create-router';
|
import { createRouter } from '../../create-router';
|
||||||
import { DATA_PATH, getResourcesDir } from '../../data-path';
|
import { getNativeResourcesDir, getGlobalResourcesDir } from '../../data-path';
|
||||||
|
import { parseFrontmatter } from '../skills/skills';
|
||||||
|
|
||||||
type ResourceCredentials = {
|
async function readResourceDirs(dir: string): Promise<Map<string, string>> {
|
||||||
apiKey?: string;
|
const result = new Map<string, string>();
|
||||||
username?: string;
|
try {
|
||||||
password?: string;
|
const entries = await readdir(dir, { withFileTypes: true });
|
||||||
};
|
for (const entry of entries) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
export type ResourceConnectionConfig = {
|
const resourceFile = join(dir, entry.name, 'RESOURCE.md');
|
||||||
url: string;
|
if (await Bun.file(resourceFile).exists()) {
|
||||||
credentials?: ResourceCredentials;
|
result.set(entry.name, resourceFile);
|
||||||
};
|
}
|
||||||
|
}
|
||||||
type ResourcesConfig = Record<string, ResourceConnectionConfig>;
|
} catch {
|
||||||
|
// directory doesn't exist yet
|
||||||
type Resource = {
|
}
|
||||||
id: string;
|
return result;
|
||||||
name: string;
|
|
||||||
subtitle: string;
|
|
||||||
type: string;
|
|
||||||
port: string | null;
|
|
||||||
path: string | null;
|
|
||||||
description: string;
|
|
||||||
installCommand: string | null;
|
|
||||||
uninstallCommand: string | null;
|
|
||||||
manageCommand: string | null;
|
|
||||||
verifyCommand: string | null;
|
|
||||||
updateCommand: string | null;
|
|
||||||
installed: boolean;
|
|
||||||
version: string | null;
|
|
||||||
connectionConfig: ResourceConnectionConfig | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const stripBackticks = (value: string) => value.replace(/^`(.+)`$/, '$1');
|
|
||||||
|
|
||||||
const resolveCommand = (command: string): string => {
|
|
||||||
return command.replace(/\$DATA_PATH/g, DATA_PATH);
|
|
||||||
};
|
|
||||||
|
|
||||||
function parseResourceFile(
|
|
||||||
filename: string,
|
|
||||||
content: string,
|
|
||||||
): Omit<Resource, 'installed' | 'version' | 'connectionConfig'> {
|
|
||||||
const id = filename
|
|
||||||
.replace(/^SERVICE_/, '')
|
|
||||||
.replace(/\.md$/, '')
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/_/g, '-');
|
|
||||||
|
|
||||||
const headingMatch = content.match(/^#\s+(.+?)\s+—\s+(.+)$/m);
|
|
||||||
const name = headingMatch?.[1] ?? id;
|
|
||||||
const subtitle = headingMatch?.[2] ?? '';
|
|
||||||
|
|
||||||
const field = (key: string): string | null => {
|
|
||||||
const match = content.match(new RegExp(`^-\\s+\\*\\*${key}:\\*\\*\\s+(.+)$`, 'm'));
|
|
||||||
return match?.[1]?.trim() ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const rawType = field('Type') ?? 'native';
|
|
||||||
const rawPort = field('Port');
|
|
||||||
const port = rawPort && !rawPort.startsWith('none') ? rawPort : null;
|
|
||||||
|
|
||||||
const rawPath = field('Path');
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
subtitle,
|
|
||||||
type: rawType,
|
|
||||||
port,
|
|
||||||
path: rawPath ? stripBackticks(rawPath) : null,
|
|
||||||
description: field('Description') ?? '',
|
|
||||||
installCommand: field('Install') ? resolveCommand(stripBackticks(field('Install')!)) : null,
|
|
||||||
uninstallCommand: field('Uninstall') ? resolveCommand(stripBackticks(field('Uninstall')!)) : null,
|
|
||||||
manageCommand: field('Manage') ? resolveCommand(stripBackticks(field('Manage')!)) : null,
|
|
||||||
verifyCommand: field('Verify') ? resolveCommand(stripBackticks(field('Verify')!)) : null,
|
|
||||||
updateCommand: field('Update') ? resolveCommand(stripBackticks(field('Update')!)) : null,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const CONFIG_FILENAME = 'resources-config.json';
|
async function readConfigFile(dir: string): Promise<Record<string, string>> {
|
||||||
|
try {
|
||||||
const getConfigPath = () => join(getResourcesDir(), CONFIG_FILENAME);
|
return await Bun.file(join(dir, 'config.json')).json();
|
||||||
|
} catch {
|
||||||
export async function readConfig(): Promise<ResourcesConfig> {
|
return {};
|
||||||
const path = getConfigPath();
|
}
|
||||||
if (!existsSync(path)) return {};
|
|
||||||
const text = await Bun.file(path).text();
|
|
||||||
return JSON.parse(text) as ResourcesConfig;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function writeConfig(config: ResourcesConfig): Promise<void> {
|
function mergeConfig(native: Record<string, string>, global: Record<string, string>): Record<string, string> {
|
||||||
const dir = getResourcesDir();
|
const merged: Record<string, string> = {};
|
||||||
if (!existsSync(dir)) await mkdir(dir, { recursive: true });
|
for (const key of Object.keys(native)) {
|
||||||
await Bun.write(getConfigPath(), JSON.stringify(config, null, 2));
|
merged[key] = global[key] ?? native[key]!;
|
||||||
|
}
|
||||||
|
for (const key of Object.keys(global)) {
|
||||||
|
if (!(key in merged)) merged[key] = global[key]!;
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPrivileged(role: string) {
|
||||||
|
return role === 'Admin' || role === 'Owner' || role === 'Super Admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readResourceConfig(name: string): Promise<Record<string, string>> {
|
||||||
|
const nativeConfig = await readConfigFile(join(getNativeResourcesDir(), name));
|
||||||
|
const globalConfig = await readConfigFile(join(getGlobalResourcesDir(), name));
|
||||||
|
return mergeConfig(nativeConfig, globalConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
const CHECK_TIMEOUT_MS = 3_000;
|
const CHECK_TIMEOUT_MS = 3_000;
|
||||||
|
|
||||||
async function checkPort(port: number): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const socket = await Bun.connect({
|
|
||||||
hostname: '127.0.0.1',
|
|
||||||
port,
|
|
||||||
socket: {
|
|
||||||
data() {},
|
|
||||||
open(s) {
|
|
||||||
s.end();
|
|
||||||
},
|
|
||||||
error() {},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
socket.end();
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkVerifyCommand(command: string): Promise<{ installed: boolean; version: string | null }> {
|
|
||||||
try {
|
|
||||||
const proc = Bun.spawn(['sh', '-c', command], { stdout: 'pipe', stderr: 'pipe' });
|
|
||||||
const timeout = new Promise<never>((_, reject) =>
|
|
||||||
setTimeout(() => {
|
|
||||||
proc.kill();
|
|
||||||
reject(new Error('timeout'));
|
|
||||||
}, CHECK_TIMEOUT_MS),
|
|
||||||
);
|
|
||||||
const result = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
|
|
||||||
const [stdout, stderr] = await Promise.race([result, timeout]);
|
|
||||||
if (proc.exitCode !== 0) return { installed: false, version: null };
|
|
||||||
const output = (stdout + stderr).trim();
|
|
||||||
const versionMatch = output.match(/(\d+\.\d+[\w.-]*)/);
|
|
||||||
return { installed: true, version: versionMatch?.[1] ?? null };
|
|
||||||
} catch {
|
|
||||||
return { installed: false, version: null };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractFirstPort(portStr: string): number | null {
|
|
||||||
const match = portStr.match(/(\d+)/);
|
|
||||||
return match ? parseInt(match[1]!, 10) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkUrl(url: string): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const controller = new AbortController();
|
|
||||||
const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);
|
|
||||||
await fetch(url, { signal: controller.signal });
|
|
||||||
clearTimeout(timeout);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type CheckResourceStatusParams = {
|
|
||||||
resource: Omit<Resource, 'installed' | 'version' | 'connectionConfig'>;
|
|
||||||
configUrl?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
async function checkResourceStatus({
|
|
||||||
resource,
|
|
||||||
configUrl,
|
|
||||||
}: CheckResourceStatusParams): Promise<{ installed: boolean; version: string | null }> {
|
|
||||||
if (resource.path) {
|
|
||||||
const fullPath = `${getResourcesDir()}/${resource.path}`;
|
|
||||||
return { installed: existsSync(fullPath), version: null };
|
|
||||||
}
|
|
||||||
if (resource.port) {
|
|
||||||
if (configUrl) {
|
|
||||||
const reachable = await checkUrl(configUrl);
|
|
||||||
if (reachable) return { installed: true, version: null };
|
|
||||||
}
|
|
||||||
const port = extractFirstPort(resource.port);
|
|
||||||
if (port) {
|
|
||||||
const reachable = await checkPort(port);
|
|
||||||
return { installed: reachable, version: null };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (resource.verifyCommand) {
|
|
||||||
return checkVerifyCommand(resource.verifyCommand);
|
|
||||||
}
|
|
||||||
return { installed: false, version: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildConnectionConfig(
|
|
||||||
resource: Omit<Resource, 'installed' | 'version' | 'connectionConfig'>,
|
|
||||||
config: ResourcesConfig,
|
|
||||||
): ResourceConnectionConfig | null {
|
|
||||||
if (!resource.port) return null;
|
|
||||||
if (config[resource.id]) return config[resource.id]!;
|
|
||||||
const port = extractFirstPort(resource.port);
|
|
||||||
return { url: `http://127.0.0.1:${port ?? resource.port}` };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function parseResources() {
|
|
||||||
const dir = getResourcesDir();
|
|
||||||
if (!existsSync(dir)) return [];
|
|
||||||
const files = await readdir(dir);
|
|
||||||
const serviceFiles = files.filter((f) => f.startsWith('SERVICE_') && f.endsWith('.md'));
|
|
||||||
return Promise.all(
|
|
||||||
serviceFiles.map(async (filename) => {
|
|
||||||
const content = await Bun.file(`${dir}/${filename}`).text();
|
|
||||||
return parseResourceFile(filename, content);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadResources(): Promise<Resource[]> {
|
|
||||||
const [parsed, config] = await Promise.all([parseResources(), readConfig()]);
|
|
||||||
return Promise.all(
|
|
||||||
parsed.map(async (r) => {
|
|
||||||
const configUrl = config[r.id]?.url;
|
|
||||||
const status = await checkResourceStatus({ resource: r, configUrl });
|
|
||||||
const connectionConfig = buildConnectionConfig(r, config);
|
|
||||||
return { ...r, ...status, connectionConfig };
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const resourcesRouter = createRouter();
|
export const resourcesRouter = createRouter();
|
||||||
|
|
||||||
resourcesRouter.get('/', async (ctx) => {
|
resourcesRouter.get('/', async (ctx) => {
|
||||||
const resources = await loadResources();
|
const nativeResources = await readResourceDirs(getNativeResourcesDir());
|
||||||
|
const globalResources = await readResourceDirs(getGlobalResourcesDir());
|
||||||
|
|
||||||
|
const merged = new Map(nativeResources);
|
||||||
|
for (const [name, path] of globalResources) merged.set(name, path);
|
||||||
|
|
||||||
|
const resources = await Promise.all(
|
||||||
|
Array.from(merged.entries()).map(async ([dirName, filePath]) => {
|
||||||
|
const raw = await Bun.file(filePath).text();
|
||||||
|
const { frontmatter } = parseFrontmatter(raw);
|
||||||
|
const scope = globalResources.has(dirName) && !nativeResources.has(dirName) ? 'global' as const : nativeResources.has(dirName) ? 'native' as const : 'global' as const;
|
||||||
|
const config = await readResourceConfig(dirName);
|
||||||
|
return { dirName, name: frontmatter.name || dirName, description: frontmatter.description, scope, config };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
return ctx.json(resources);
|
return ctx.json(resources);
|
||||||
});
|
});
|
||||||
|
|
||||||
resourcesRouter.get('/config', async (ctx) => {
|
resourcesRouter.get('/:name', async (ctx) => {
|
||||||
const config = await readConfig();
|
const name = ctx.req.param('name');
|
||||||
return ctx.json(config);
|
|
||||||
|
const nativeResources = await readResourceDirs(getNativeResourcesDir());
|
||||||
|
const globalResources = await readResourceDirs(getGlobalResourcesDir());
|
||||||
|
|
||||||
|
const filePath = globalResources.get(name) ?? nativeResources.get(name);
|
||||||
|
if (!filePath) return ctx.text('Not found', 404);
|
||||||
|
|
||||||
|
const scope = globalResources.has(name) && !nativeResources.has(name) ? 'global' as const : 'native' as const;
|
||||||
|
const raw = await Bun.file(filePath).text();
|
||||||
|
const { frontmatter, body, rawYaml } = parseFrontmatter(raw);
|
||||||
|
const config = await readResourceConfig(name);
|
||||||
|
|
||||||
|
const globalConfigPath = join(getGlobalResourcesDir(), name, 'config.json');
|
||||||
|
const chatMeta = join(dirname(filePath), 'chat', 'meta.json');
|
||||||
|
const chatSessionId = await Bun.file(chatMeta).json().then((m: { id: string }) => m.id).catch(() => null);
|
||||||
|
const guidePath = join(getNativeResourcesDir(), 'GUIDE.md');
|
||||||
|
|
||||||
|
return ctx.json({
|
||||||
|
dirName: name,
|
||||||
|
name: frontmatter.name || name,
|
||||||
|
description: frontmatter.description,
|
||||||
|
scope,
|
||||||
|
body,
|
||||||
|
rawFrontmatter: rawYaml,
|
||||||
|
filePath,
|
||||||
|
config,
|
||||||
|
configPath: globalConfigPath,
|
||||||
|
chatSessionId,
|
||||||
|
guidePath,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
resourcesRouter.patch('/config/:id', async (ctx) => {
|
resourcesRouter.patch('/:name/config', async (ctx) => {
|
||||||
const id = ctx.req.param('id');
|
const user = ctx.get('user');
|
||||||
const body = await ctx.req.json<Partial<ResourceConnectionConfig>>();
|
if (!isPrivileged(user.role)) return ctx.text('Forbidden', 403);
|
||||||
const config = await readConfig();
|
|
||||||
const existing = config[id] ?? { url: '' };
|
const name = ctx.req.param('name');
|
||||||
config[id] = { ...existing, ...body };
|
const body = await ctx.req.json<Record<string, string | null>>();
|
||||||
await writeConfig(config);
|
|
||||||
return ctx.json(config[id]);
|
const globalDir = join(getGlobalResourcesDir(), name);
|
||||||
|
await mkdir(globalDir, { recursive: true });
|
||||||
|
|
||||||
|
const existing = await readConfigFile(globalDir);
|
||||||
|
for (const [key, value] of Object.entries(body)) {
|
||||||
|
if (value === null) delete existing[key];
|
||||||
|
else existing[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
await Bun.write(join(globalDir, 'config.json'), JSON.stringify(existing, null, 2));
|
||||||
|
|
||||||
|
const merged = await readResourceConfig(name);
|
||||||
|
return ctx.json(merged);
|
||||||
});
|
});
|
||||||
|
|
||||||
resourcesRouter.post('/:id/ping', async (ctx) => {
|
resourcesRouter.post('/', async (ctx) => {
|
||||||
const id = ctx.req.param('id');
|
const user = ctx.get('user');
|
||||||
|
if (!isPrivileged(user.role)) return ctx.text('Forbidden', 403);
|
||||||
|
|
||||||
|
const { name } = await ctx.req.json<{ name: string }>();
|
||||||
|
if (!name?.trim()) return ctx.text('Name is required', 400);
|
||||||
|
|
||||||
|
const dirName = name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
|
||||||
|
if (!dirName) return ctx.text('Invalid name', 400);
|
||||||
|
|
||||||
|
const dir = join(getGlobalResourcesDir(), dirName);
|
||||||
|
const filePath = join(dir, 'RESOURCE.md');
|
||||||
|
|
||||||
|
if (await Bun.file(filePath).exists()) {
|
||||||
|
return ctx.text('Resource already exists', 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(dir, { recursive: true });
|
||||||
|
await Bun.write(filePath, `---\nname: ${name.trim()}\ndescription: \n---\n`);
|
||||||
|
await Bun.write(join(dir, 'config.json'), JSON.stringify({ url: '', api_key: '', username: '', password: '' }, null, 2));
|
||||||
|
|
||||||
|
return ctx.json({ name: name.trim(), dirName, filePath, scope: 'global' });
|
||||||
|
});
|
||||||
|
|
||||||
|
resourcesRouter.delete('/:name', async (ctx) => {
|
||||||
|
const user = ctx.get('user');
|
||||||
|
if (!isPrivileged(user.role)) return ctx.text('Forbidden', 403);
|
||||||
|
|
||||||
|
const name = ctx.req.param('name');
|
||||||
|
const nativeResources = await readResourceDirs(getNativeResourcesDir());
|
||||||
|
|
||||||
|
if (nativeResources.has(name)) return ctx.text('Cannot delete native resource', 400);
|
||||||
|
|
||||||
|
const dir = join(getGlobalResourcesDir(), name);
|
||||||
|
const filePath = join(dir, 'RESOURCE.md');
|
||||||
|
if (!(await Bun.file(filePath).exists())) return ctx.text('Not found', 404);
|
||||||
|
|
||||||
|
await rm(dir, { recursive: true });
|
||||||
|
return ctx.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
resourcesRouter.get('/:name/chat', async (ctx) => {
|
||||||
|
const name = ctx.req.param('name');
|
||||||
|
|
||||||
|
const nativeResources = await readResourceDirs(getNativeResourcesDir());
|
||||||
|
const globalResources = await readResourceDirs(getGlobalResourcesDir());
|
||||||
|
|
||||||
|
const filePath = globalResources.get(name) ?? nativeResources.get(name);
|
||||||
|
if (!filePath) return ctx.text('Not found', 404);
|
||||||
|
|
||||||
|
const chatDir = join(getGlobalResourcesDir(), name, '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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
resourcesRouter.put('/:name/chat', async (ctx) => {
|
||||||
|
const user = ctx.get('user');
|
||||||
|
if (!isPrivileged(user.role)) return ctx.text('Forbidden', 403);
|
||||||
|
|
||||||
|
const name = ctx.req.param('name');
|
||||||
|
const { sessionId, messages } = await ctx.req.json<{ sessionId: string; messages: unknown[] }>();
|
||||||
|
|
||||||
|
const chatDir = join(getGlobalResourcesDir(), name, 'chat');
|
||||||
|
await mkdir(chatDir, { recursive: true });
|
||||||
|
await Bun.write(join(chatDir, 'messages.json'), JSON.stringify(messages));
|
||||||
|
if (sessionId) await Bun.write(join(chatDir, 'meta.json'), JSON.stringify({ id: sessionId }));
|
||||||
|
|
||||||
|
return ctx.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
resourcesRouter.delete('/:name/chat', async (ctx) => {
|
||||||
|
const user = ctx.get('user');
|
||||||
|
if (!isPrivileged(user.role)) return ctx.text('Forbidden', 403);
|
||||||
|
|
||||||
|
const name = ctx.req.param('name');
|
||||||
|
const chatDir = join(getGlobalResourcesDir(), name, 'chat');
|
||||||
|
await rm(chatDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
return ctx.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
resourcesRouter.post('/:name/ping', async (ctx) => {
|
||||||
|
const name = ctx.req.param('name');
|
||||||
const body = await ctx.req.json<{ url?: string }>().catch((): { url?: string } => ({}));
|
const body = await ctx.req.json<{ url?: string }>().catch((): { url?: string } => ({}));
|
||||||
const config = await readConfig();
|
const config = await readResourceConfig(name);
|
||||||
const resources = await loadResources();
|
|
||||||
const resource = resources.find((r) => r.id === id);
|
|
||||||
if (!resource) return ctx.json({ error: 'Resource not found' }, 404);
|
|
||||||
|
|
||||||
const url = body.url ?? config[id]?.url ?? resource.connectionConfig?.url;
|
const url = body.url ?? config.url;
|
||||||
if (!url) return ctx.json({ error: 'No URL configured' }, 400);
|
if (!url) return ctx.json({ error: 'No URL configured' }, 400);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -268,67 +233,3 @@ resourcesRouter.post('/:id/ping', async (ctx) => {
|
|||||||
return ctx.json({ reachable: false, latencyMs: null });
|
return ctx.json({ reachable: false, latencyMs: null });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
resourcesRouter.post('/error-log', async (ctx) => {
|
|
||||||
const body = await ctx.req.json<{ command: string; output: string; exitCode: number }>();
|
|
||||||
const timestamp = Date.now();
|
|
||||||
const filePath = `/tmp/officer-error-${timestamp}.md`;
|
|
||||||
const md = [
|
|
||||||
`# Command Failed (exit code ${body.exitCode})`,
|
|
||||||
'',
|
|
||||||
'```',
|
|
||||||
body.command,
|
|
||||||
'```',
|
|
||||||
'',
|
|
||||||
'## Output',
|
|
||||||
'',
|
|
||||||
'```',
|
|
||||||
body.output,
|
|
||||||
'```',
|
|
||||||
].join('\n');
|
|
||||||
await Bun.write(filePath, md);
|
|
||||||
return ctx.json({ filePath });
|
|
||||||
});
|
|
||||||
|
|
||||||
resourcesRouter.post('/:id/run', async (ctx) => {
|
|
||||||
const id = ctx.req.param('id');
|
|
||||||
const { action } = await ctx.req.json<{ action: string }>();
|
|
||||||
|
|
||||||
const parsed = await parseResources();
|
|
||||||
const resource = parsed.find((r) => r.id === id);
|
|
||||||
if (!resource) return ctx.json({ error: 'Resource not found' }, 404);
|
|
||||||
|
|
||||||
const commands: Record<string, string | null> = {
|
|
||||||
install: resource.installCommand,
|
|
||||||
uninstall: resource.uninstallCommand,
|
|
||||||
verify: resource.verifyCommand,
|
|
||||||
update: resource.updateCommand,
|
|
||||||
manage: resource.manageCommand,
|
|
||||||
};
|
|
||||||
|
|
||||||
const command = commands[action];
|
|
||||||
if (!command) return ctx.json({ error: `No ${action} command for this resource` }, 400);
|
|
||||||
|
|
||||||
if (command.trimStart().startsWith('sudo')) {
|
|
||||||
return ctx.json({ error: 'Sudo commands must run in terminal' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const proc = Bun.spawn(['sh', '-c', command], { stdout: 'pipe', stderr: 'pipe' });
|
|
||||||
const [stdout, stderr] = await Promise.all([
|
|
||||||
new Response(proc.stdout).text(),
|
|
||||||
new Response(proc.stderr).text(),
|
|
||||||
]);
|
|
||||||
await proc.exited;
|
|
||||||
return ctx.json({ exitCode: proc.exitCode, output: (stdout + stderr).trim() });
|
|
||||||
} catch {
|
|
||||||
return ctx.json({ exitCode: 1, output: 'Failed to execute command' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
resourcesRouter.get('/:id', async (ctx) => {
|
|
||||||
const resources = await loadResources();
|
|
||||||
const resource = resources.find((r) => r.id === ctx.req.param('id'));
|
|
||||||
if (!resource) return ctx.json({ error: 'Resource not found' }, 404);
|
|
||||||
return ctx.json(resource);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import { createRouter } from '../../create-router';
|
import { createRouter } from '../../create-router';
|
||||||
import { settingsPath } from './server-settings';
|
import { settingsPath } from './server-settings';
|
||||||
|
import { readResourceConfig } from './resources';
|
||||||
|
|
||||||
type SttConfig = {
|
type SttConfig = {
|
||||||
url: string;
|
url: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function readSttConfig(): Promise<SttConfig | undefined> {
|
export async function readSttConfig(): Promise<SttConfig | undefined> {
|
||||||
|
const config = await readResourceConfig('speech-to-text');
|
||||||
|
if (config.url) return { url: config.url };
|
||||||
|
// Fallback to legacy settings.json
|
||||||
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
return settings.stt as SttConfig | undefined;
|
return settings.stt as SttConfig | undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createRouter } from '../../create-router';
|
import { createRouter } from '../../create-router';
|
||||||
import { settingsPath } from './server-settings';
|
import { settingsPath } from './server-settings';
|
||||||
|
import { readResourceConfig } from './resources';
|
||||||
|
|
||||||
type TtsConfig = {
|
type TtsConfig = {
|
||||||
provider: 'openai' | 'elevenlabs';
|
provider: 'openai' | 'elevenlabs';
|
||||||
@@ -15,8 +16,19 @@ function maskSecret(value: string | undefined): string | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function readTtsConfig(): Promise<TtsConfig | undefined> {
|
export async function readTtsConfig(): Promise<TtsConfig | undefined> {
|
||||||
|
const config = await readResourceConfig('text-to-speech');
|
||||||
|
if (!config.url && !config.provider) {
|
||||||
|
// Fallback to legacy settings.json
|
||||||
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
return settings.tts as TtsConfig | undefined;
|
return settings.tts as TtsConfig | undefined;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
provider: (config.provider || 'openai') as 'openai' | 'elevenlabs',
|
||||||
|
url: config.url ?? '',
|
||||||
|
apiKey: config.api_key || undefined,
|
||||||
|
model: config.model ?? '',
|
||||||
|
voice: config.voice ?? '',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ttsRouter = createRouter();
|
export const ttsRouter = createRouter();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ FROM imbios/bun-node:22-slim
|
|||||||
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y \
|
&& apt-get install -y \
|
||||||
python3 make gcc g++ zsh git curl wget ca-certificates \
|
python3 python3-pip python3-venv make gcc g++ zsh git curl wget ca-certificates \
|
||||||
sudo gosu locales \
|
sudo gosu locales \
|
||||||
zip unzip tree btop net-tools tmux \
|
zip unzip tree btop net-tools tmux \
|
||||||
procps psmisc lsof less file man-db \
|
procps psmisc lsof less file man-db \
|
||||||
@@ -50,6 +50,19 @@ RUN curl -fsSL "https://github.com/jesseduffield/lazygit/releases/download/v${LA
|
|||||||
&& rm -rf /tmp/lazygit.tar.gz /tmp/LICENSE /tmp/README.md
|
&& rm -rf /tmp/lazygit.tar.gz /tmp/LICENSE /tmp/README.md
|
||||||
|
|
||||||
|
|
||||||
|
ENV GOLANG_VERSION=1.23.6
|
||||||
|
RUN curl -fsSL "https://go.dev/dl/go${GOLANG_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \
|
||||||
|
&& tar -C /usr/local -xzf /tmp/go.tar.gz \
|
||||||
|
&& rm /tmp/go.tar.gz
|
||||||
|
|
||||||
|
ENV PATH="/usr/local/go/bin:${PATH}"
|
||||||
|
|
||||||
|
ENV RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo
|
||||||
|
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal \
|
||||||
|
&& chmod -R a+rw $CARGO_HOME
|
||||||
|
|
||||||
|
ENV PATH="/usr/local/cargo/bin:${PATH}"
|
||||||
|
|
||||||
RUN npm install -g @mariozechner/pi-coding-agent
|
RUN npm install -g @mariozechner/pi-coding-agent
|
||||||
|
|
||||||
WORKDIR /tmp
|
WORKDIR /tmp
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { ServerWebSocket } from 'bun';
|
|||||||
import { mkdirSync, statSync } from 'node:fs';
|
import { mkdirSync, statSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { getHomeDir, getGlobalSkillsDir, getGlobalToolsDir, getGlobalExtensionsDir, getUserSkillsDir, getUserToolsDir } from '@@/data-path';
|
import { getHomeDir, getGlobalSkillsDir, getGlobalToolsDir, getGlobalExtensionsDir, getUserSkillsDir, getUserToolsDir, DATA_PATH } from '@@/data-path';
|
||||||
import { syncUserPiConfig } from '@@/api/server-settings/sync-user-pi-config';
|
import { syncUserPiConfig } from '@@/api/server-settings/sync-user-pi-config';
|
||||||
import { getUsers } from 'officerdb';
|
import { getUsers } from 'officerdb';
|
||||||
|
|
||||||
@@ -163,6 +163,7 @@ const startDockerSidecar = (port: number, homeDir: string, userId: number, usern
|
|||||||
'-v', `${getGlobalExtensionsDir()}:/officer/extensions:ro`,
|
'-v', `${getGlobalExtensionsDir()}:/officer/extensions:ro`,
|
||||||
'-v', `${getUserSkillsDir(email)}:/officer/user/skills:ro`,
|
'-v', `${getUserSkillsDir(email)}:/officer/user/skills:ro`,
|
||||||
'-v', `${getUserToolsDir(email)}:/officer/user/tools:ro`,
|
'-v', `${getUserToolsDir(email)}:/officer/user/tools:ro`,
|
||||||
|
'-v', `${join(DATA_PATH, '.generated')}:/officer/generated:ro`,
|
||||||
'-w', containerHome,
|
'-w', containerHome,
|
||||||
tag,
|
tag,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import { initAuthStore } from 'officerdb';
|
|||||||
import { syncSeedSkills } from './sync-skills';
|
import { syncSeedSkills } from './sync-skills';
|
||||||
import { syncSeedTools } from './sync-tools';
|
import { syncSeedTools } from './sync-tools';
|
||||||
import { syncSeedExtensions } from './sync-extensions';
|
import { syncSeedExtensions } from './sync-extensions';
|
||||||
|
import { syncSeedResources } from './sync-resources';
|
||||||
|
import { migrateSettingsToResources } from './migrate-resources';
|
||||||
|
|
||||||
mkdirSync(DATA_PATH, { recursive: true });
|
mkdirSync(DATA_PATH, { recursive: true });
|
||||||
mkdirSync(PI_CONFIG_DIR, { recursive: true });
|
mkdirSync(PI_CONFIG_DIR, { recursive: true });
|
||||||
@@ -75,6 +77,8 @@ function seedPiConfig(): void {
|
|||||||
syncSeedSkills();
|
syncSeedSkills();
|
||||||
syncSeedTools();
|
syncSeedTools();
|
||||||
syncSeedExtensions();
|
syncSeedExtensions();
|
||||||
|
syncSeedResources();
|
||||||
|
migrateSettingsToResources();
|
||||||
|
|
||||||
await syncLocalProvidersToPiConfig().catch(err => {
|
await syncLocalProvidersToPiConfig().catch(err => {
|
||||||
console.error('[bootstrap] Failed to sync local providers to Pi config:', err);
|
console.error('[bootstrap] Failed to sync local providers to Pi config:', err);
|
||||||
|
|||||||
@@ -74,6 +74,10 @@ export const getGlobalProcessesDir = () => join(DATA_PATH, 'processes');
|
|||||||
|
|
||||||
export const getUserProcessesDir = (email: string) => join(DATA_PATH, email, 'processes');
|
export const getUserProcessesDir = (email: string) => join(DATA_PATH, email, 'processes');
|
||||||
|
|
||||||
|
export const getNativeResourcesDir = () => join(SEED_PATH, 'resources');
|
||||||
|
|
||||||
|
export const getGlobalResourcesDir = () => join(DATA_PATH, 'resources');
|
||||||
|
|
||||||
export const getResourcesDir = () => join(DATA_PATH, 'resources');
|
export const getResourcesDir = () => join(DATA_PATH, 'resources');
|
||||||
|
|
||||||
export const getTaskLogsDir = (email: string) => join(DATA_PATH, email, 'logs', 'tasks');
|
export const getTaskLogsDir = (email: string) => join(DATA_PATH, email, 'logs', 'tasks');
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { DATA_PATH, SEED_PATH } from './data-path';
|
||||||
|
import { settingsPath } from './api/server-settings/server-settings';
|
||||||
|
|
||||||
|
const SETTINGS_TO_RESOURCE: Record<string, string> = {
|
||||||
|
stt: 'speech-to-text',
|
||||||
|
tts: 'text-to-speech',
|
||||||
|
ocr: 'optical-character-recognition',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function migrateSettingsToResources(): void {
|
||||||
|
let settings: Record<string, Record<string, string>> = {};
|
||||||
|
try {
|
||||||
|
settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [settingsKey, resourceName] of Object.entries(SETTINGS_TO_RESOURCE)) {
|
||||||
|
const raw = settings[settingsKey];
|
||||||
|
if (!raw || typeof raw !== 'object') continue;
|
||||||
|
|
||||||
|
const globalDir = join(DATA_PATH, 'resources', resourceName);
|
||||||
|
const globalConfigPath = join(globalDir, 'config.json');
|
||||||
|
|
||||||
|
if (existsSync(globalConfigPath)) continue;
|
||||||
|
|
||||||
|
// Read seed config for schema (all keys)
|
||||||
|
let seedConfig: Record<string, string> = {};
|
||||||
|
try {
|
||||||
|
seedConfig = JSON.parse(readFileSync(join(SEED_PATH, 'resources', resourceName, 'config.json'), 'utf-8'));
|
||||||
|
} catch {
|
||||||
|
// no seed config
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge settings values into seed schema
|
||||||
|
const merged: Record<string, string> = {};
|
||||||
|
for (const key of Object.keys(seedConfig)) {
|
||||||
|
merged[key] = seedConfig[key]!;
|
||||||
|
}
|
||||||
|
for (const [key, value] of Object.entries(raw)) {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const mapped = key === 'apiKey' ? 'api_key' : key;
|
||||||
|
merged[mapped] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mkdirSync(globalDir, { recursive: true });
|
||||||
|
writeFileSync(globalConfigPath, JSON.stringify(merged, null, 2), 'utf-8');
|
||||||
|
console.log(`[resources] Migrated ${settingsKey} settings to ${resourceName}/config.json`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { readdirSync, existsSync, mkdirSync, cpSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { SEED_PATH, DATA_PATH } from './data-path';
|
||||||
|
|
||||||
|
const SEED_PROCESSES_DIR = join(SEED_PATH, 'processes');
|
||||||
|
const GLOBAL_PROCESSES_DIR = join(DATA_PATH, 'processes');
|
||||||
|
|
||||||
|
export function syncSeedProcesses(): void {
|
||||||
|
if (!existsSync(SEED_PROCESSES_DIR)) return;
|
||||||
|
|
||||||
|
mkdirSync(GLOBAL_PROCESSES_DIR, { recursive: true });
|
||||||
|
|
||||||
|
const seedEntries = readdirSync(SEED_PROCESSES_DIR, { withFileTypes: true });
|
||||||
|
|
||||||
|
for (const entry of seedEntries) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
|
||||||
|
const seedProcessDir = join(SEED_PROCESSES_DIR, entry.name);
|
||||||
|
const processFile = join(seedProcessDir, 'PROCESS.md');
|
||||||
|
if (!existsSync(processFile)) continue;
|
||||||
|
|
||||||
|
const targetDir = join(GLOBAL_PROCESSES_DIR, entry.name);
|
||||||
|
|
||||||
|
if (existsSync(targetDir)) {
|
||||||
|
// Process already exists in DATA_PATH — skip to preserve user edits
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
cpSync(seedProcessDir, targetDir, { recursive: true });
|
||||||
|
console.log(`[processes] Synced seed process: ${entry.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { mkdirSync } from 'node:fs';
|
||||||
|
import { DATA_PATH } from './data-path';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export function syncSeedResources(): void {
|
||||||
|
// Native resources are read directly from seed/ at runtime.
|
||||||
|
// Only ensure the global resources directory exists.
|
||||||
|
mkdirSync(join(DATA_PATH, 'resources'), { recursive: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { readdirSync, existsSync, mkdirSync, cpSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { SEED_PATH, DATA_PATH } from './data-path';
|
||||||
|
|
||||||
|
const SEED_TASKS_DIR = join(SEED_PATH, 'tasks');
|
||||||
|
const GLOBAL_TASKS_DIR = join(DATA_PATH, 'tasks');
|
||||||
|
|
||||||
|
export function syncSeedTasks(): void {
|
||||||
|
if (!existsSync(SEED_TASKS_DIR)) return;
|
||||||
|
|
||||||
|
mkdirSync(GLOBAL_TASKS_DIR, { recursive: true });
|
||||||
|
|
||||||
|
const seedEntries = readdirSync(SEED_TASKS_DIR, { withFileTypes: true });
|
||||||
|
|
||||||
|
for (const entry of seedEntries) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
|
||||||
|
const seedTaskDir = join(SEED_TASKS_DIR, entry.name);
|
||||||
|
const taskFile = join(seedTaskDir, 'TASK.md');
|
||||||
|
if (!existsSync(taskFile)) continue;
|
||||||
|
|
||||||
|
const targetDir = join(GLOBAL_TASKS_DIR, entry.name);
|
||||||
|
|
||||||
|
if (existsSync(targetDir)) {
|
||||||
|
// Task already exists in DATA_PATH — skip to preserve user edits
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
cpSync(seedTaskDir, targetDir, { recursive: true });
|
||||||
|
console.log(`[tasks] Synced seed task: ${entry.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -6,7 +6,7 @@ type TaskRunnerDialogProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const TaskRunnerDialog = ({ fileBrowserManager }: TaskRunnerDialogProps) => {
|
export const TaskRunnerDialog = ({ fileBrowserManager }: TaskRunnerDialogProps) => {
|
||||||
const { runningTask, setRunningTask, refresh, homeRoot, currentPath } = fileBrowserManager;
|
const { runningTask, setRunningTask, refresh, homeRoot, currentPath, getEntryAbsPath } = fileBrowserManager;
|
||||||
|
|
||||||
if (!runningTask) return null;
|
if (!runningTask) return null;
|
||||||
|
|
||||||
@@ -21,6 +21,7 @@ export const TaskRunnerDialog = ({ fileBrowserManager }: TaskRunnerDialogProps)
|
|||||||
}}
|
}}
|
||||||
task={runningTask.task}
|
task={runningTask.task}
|
||||||
entryName={runningTask.entry.name}
|
entryName={runningTask.entry.name}
|
||||||
|
entryFullPath={getEntryAbsPath(runningTask.entry.name)}
|
||||||
entryType={runningTask.entry.type}
|
entryType={runningTask.entry.type}
|
||||||
cwd={{ root: homeRoot, path: currentPath.replace(/^\//, '') }}
|
cwd={{ root: homeRoot, path: currentPath.replace(/^\//, '') }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
+138
-21
@@ -1,11 +1,12 @@
|
|||||||
import { useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { X } from 'lucide-react';
|
import { X, Play, Square, CircleCheck } from 'lucide-react';
|
||||||
import { Dialog, DialogOverlay, DialogPortal } from '@/components/ui/dialog';
|
import { Dialog, DialogOverlay, DialogPortal } from '@/components/ui/dialog';
|
||||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||||
import { cardStyle } from '@/components/Card';
|
import { cardStyle } from '@/components/Card';
|
||||||
import type { TaskInfo } from '../../../Chat';
|
import type { TaskInfo, ChatMessage } from '../../../Chat';
|
||||||
import { usePiChat, EmbeddableChat } from '../../../Chat';
|
import { usePiChat, MessageBubble, StreamingBubble, ModelSelector } from '../../../Chat';
|
||||||
import { useSettings } from 'state/useSettings';
|
import { useSettings } from 'state/useSettings';
|
||||||
|
import { useVisiblePiModels } from 'state/useModels';
|
||||||
import type { TaskSummary } from '../../useTasks';
|
import type { TaskSummary } from '../../useTasks';
|
||||||
|
|
||||||
const playDing = () => {
|
const playDing = () => {
|
||||||
@@ -32,6 +33,8 @@ const playDing = () => {
|
|||||||
setTimeout(() => ctx.close(), 1500);
|
setTimeout(() => ctx.close(), 1500);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Phase = 'ready' | 'running' | 'done';
|
||||||
|
|
||||||
type PiMonoInnerProps = {
|
type PiMonoInnerProps = {
|
||||||
defaultInput: string;
|
defaultInput: string;
|
||||||
cwd: { root?: string; path: string };
|
cwd: { root?: string; path: string };
|
||||||
@@ -39,27 +42,139 @@ type PiMonoInnerProps = {
|
|||||||
taskInfo: TaskInfo;
|
taskInfo: TaskInfo;
|
||||||
};
|
};
|
||||||
|
|
||||||
const PiMonoInner = ({
|
const PiMonoInner = ({ defaultInput, cwd, initialModel, taskInfo }: PiMonoInnerProps) => {
|
||||||
defaultInput,
|
const [phase, setPhase] = useState<Phase>('ready');
|
||||||
cwd,
|
|
||||||
initialModel,
|
|
||||||
taskInfo,
|
|
||||||
}: PiMonoInnerProps) => {
|
|
||||||
const chat = usePiChat(undefined, initialModel, { replaceUrl: false, taskInfo });
|
const chat = usePiChat(undefined, initialModel, { replaceUrl: false, taskInfo });
|
||||||
|
const availableModels = useVisiblePiModels();
|
||||||
|
|
||||||
|
// --- Independent message accumulator (never loses messages) ---
|
||||||
|
const accRef = useRef<ChatMessage[]>([]);
|
||||||
|
const seenToolIdsRef = useRef(new Set<string>());
|
||||||
|
const seenResultRef = useRef(false);
|
||||||
|
const [, bump] = useState(0);
|
||||||
|
|
||||||
|
// Track tool/result messages from chat.messages (idempotent during render)
|
||||||
|
for (const m of chat.messages) {
|
||||||
|
if (m.role === 'tool' && 'toolCallId' in m) {
|
||||||
|
if (!seenToolIdsRef.current.has(m.toolCallId)) {
|
||||||
|
seenToolIdsRef.current.add(m.toolCallId);
|
||||||
|
accRef.current.push(m);
|
||||||
|
} else {
|
||||||
|
// Update existing tool message (e.g. output arrived)
|
||||||
|
const idx = accRef.current.findIndex(
|
||||||
|
(a) => a.role === 'tool' && 'toolCallId' in a && a.toolCallId === m.toolCallId,
|
||||||
|
);
|
||||||
|
if (idx >= 0) accRef.current[idx] = m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (m.role === 'result' && !seenResultRef.current) {
|
||||||
|
seenResultRef.current = true;
|
||||||
|
accRef.current.push(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture assistant text when streaming is committed (streamingText goes non-empty → empty)
|
||||||
|
const lastStreamRef = useRef('');
|
||||||
|
useEffect(() => {
|
||||||
|
if (lastStreamRef.current && !chat.streamingText) {
|
||||||
|
const text = lastStreamRef.current;
|
||||||
|
const isDuplicate = accRef.current.some((a) => a.role === 'assistant' && 'text' in a && a.text === text);
|
||||||
|
if (!isDuplicate) {
|
||||||
|
accRef.current.push({ role: 'assistant', text });
|
||||||
|
bump((n) => n + 1);
|
||||||
|
}
|
||||||
|
lastStreamRef.current = '';
|
||||||
|
}
|
||||||
|
if (chat.streamingText) {
|
||||||
|
lastStreamRef.current = chat.streamingText;
|
||||||
|
}
|
||||||
|
}, [chat.streamingText]);
|
||||||
|
|
||||||
|
// Auto-scroll
|
||||||
|
const bottomRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
}, [chat.messages, chat.streamingText]);
|
||||||
|
|
||||||
|
// Ding on completion + transition to done
|
||||||
const wasGenerating = useRef(false);
|
const wasGenerating = useRef(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (wasGenerating.current && !chat.isGenerating) playDing();
|
if (wasGenerating.current && !chat.isGenerating) {
|
||||||
|
playDing();
|
||||||
|
setPhase('done');
|
||||||
|
}
|
||||||
wasGenerating.current = chat.isGenerating;
|
wasGenerating.current = chat.isGenerating;
|
||||||
}, [chat.isGenerating]);
|
}, [chat.isGenerating]);
|
||||||
|
|
||||||
|
const handleRun = () => {
|
||||||
|
setPhase('running');
|
||||||
|
chat.sendPrompt(defaultInput, undefined, undefined, cwd);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (phase === 'ready') {
|
||||||
return (
|
return (
|
||||||
<EmbeddableChat
|
<>
|
||||||
chat={chat}
|
<div className="flex-1 flex items-center justify-center">
|
||||||
defaultInput={defaultInput}
|
<button
|
||||||
cwd={cwd}
|
onClick={handleRun}
|
||||||
className="flex-1 min-h-0"
|
disabled={!chat.isConnected}
|
||||||
|
className="flex items-center gap-2 px-6 py-2.5 rounded-lg bg-duck-teal text-white font-medium text-sm hover:bg-duck-teal/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
|
||||||
|
>
|
||||||
|
<Play className="h-4 w-4" />
|
||||||
|
Run
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 px-4 py-3 border-t border-duck-dark/10">
|
||||||
|
<ModelSelector
|
||||||
|
messages={[]}
|
||||||
|
availableModels={availableModels}
|
||||||
|
selectedModel={chat.selectedModel}
|
||||||
|
onModelChange={chat.setSelectedModel}
|
||||||
|
model={chat.model}
|
||||||
|
isConnected={chat.isConnected}
|
||||||
|
isGenerating={false}
|
||||||
|
hasStarted={false}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show StreamingBubble with fallback: use lastStreamRef while the effect hasn't captured yet
|
||||||
|
const showStream = chat.streamingText || lastStreamRef.current;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 flex flex-col min-h-0">
|
||||||
|
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||||
|
{accRef.current.map((msg, i) => (
|
||||||
|
<div key={i} className="px-4 py-1.5">
|
||||||
|
<MessageBubble message={msg} onAnswer={() => {}} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{showStream && (
|
||||||
|
<div className="px-4 py-1.5">
|
||||||
|
<StreamingBubble text={showStream} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div ref={bottomRef} />
|
||||||
|
</div>
|
||||||
|
<div className="shrink-0 flex justify-center py-3 border-t border-duck-dark/10">
|
||||||
|
{phase === 'running' ? (
|
||||||
|
<button
|
||||||
|
onClick={chat.stopGeneration}
|
||||||
|
className="flex items-center gap-2 px-4 py-1.5 rounded-lg bg-red-500/10 text-red-600 text-sm font-medium hover:bg-red-500/20 transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
<Square className="h-3.5 w-3.5" />
|
||||||
|
Stop
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="flex items-center gap-2 text-sm text-green-500 font-medium">
|
||||||
|
<CircleCheck className="h-4 w-4" />
|
||||||
|
Task complete
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -68,18 +183,20 @@ type TaskRunnerModalProps = {
|
|||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
task: TaskSummary;
|
task: TaskSummary;
|
||||||
entryName?: string;
|
entryName?: string;
|
||||||
|
entryFullPath?: string;
|
||||||
entryType?: 'file' | 'directory';
|
entryType?: 'file' | 'directory';
|
||||||
cwd?: { root?: string; path: string };
|
cwd?: { root?: string; path: string };
|
||||||
promptOverride?: string;
|
promptOverride?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType, cwd = { path: '' }, promptOverride }: TaskRunnerModalProps) => {
|
export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryFullPath, entryType, cwd = { path: '' }, promptOverride }: TaskRunnerModalProps) => {
|
||||||
const { settings } = useSettings();
|
const { settings } = useSettings();
|
||||||
const taskSettings = settings.tasks;
|
const taskSettings = settings.tasks;
|
||||||
|
const entryRef = entryFullPath ?? entryName;
|
||||||
const defaultInput = promptOverride
|
const defaultInput = promptOverride
|
||||||
?? (entryName && entryType
|
?? (entryRef && entryType
|
||||||
? `Read the task instructions at ${task.filePath} and execute them on the ${entryType}: ${entryName}`
|
? `Read the task instructions at ${task.filePath} and execute them on the ${entryType}: ${entryRef}\n\nBe verbose — explain each step you take and what the result was.`
|
||||||
: `Read the task instructions at ${task.filePath} and execute them`);
|
: `Read the task instructions at ${task.filePath} and execute them\n\nBe verbose — explain each step you take and what the result was.`);
|
||||||
const taskInfo: TaskInfo = { taskName: task.name, taskDirName: task.dirName, entryName: entryName ?? '', entryType: entryType ?? 'file' };
|
const taskInfo: TaskInfo = { taskName: task.name, taskDirName: task.dirName, entryName: entryName ?? '', entryType: entryType ?? 'file' };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -102,7 +219,7 @@ export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType
|
|||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Chat */}
|
{/* Task Runner */}
|
||||||
<PiMonoInner
|
<PiMonoInner
|
||||||
key="pi"
|
key="pi"
|
||||||
defaultInput={defaultInput}
|
defaultInput={defaultInput}
|
||||||
|
|||||||
@@ -712,6 +712,7 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
|
|||||||
handleDragOver,
|
handleDragOver,
|
||||||
handleDrop,
|
handleDrop,
|
||||||
handleBackgroundClick,
|
handleBackgroundClick,
|
||||||
|
getEntryAbsPath: (name: string) => absPath(entryPath(name)),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { TextRenderer } from './TextRenderer';
|
import { TextRenderer } from './TextRenderer';
|
||||||
|
import { highlight } from './highlight';
|
||||||
|
|
||||||
type CodeRendererProps = {
|
type CodeRendererProps = {
|
||||||
content: string;
|
content: string;
|
||||||
@@ -11,13 +12,8 @@ export const CodeRenderer = ({ content, lang }: CodeRendererProps) => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
import('shiki')
|
highlight(content, lang).then((result) => {
|
||||||
.then(({ codeToHtml }) => codeToHtml(content, { lang, theme: 'github-dark-default' }))
|
|
||||||
.then((result) => {
|
|
||||||
if (!cancelled) setHtml(result);
|
if (!cancelled) setHtml(result);
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
if (!cancelled) setHtml(null);
|
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
|||||||
@@ -3,12 +3,27 @@ import ReactMarkdown from 'react-markdown';
|
|||||||
import remarkGfm from 'remark-gfm';
|
import remarkGfm from 'remark-gfm';
|
||||||
import rehypeRaw from 'rehype-raw';
|
import rehypeRaw from 'rehype-raw';
|
||||||
import rehypeSlug from 'rehype-slug';
|
import rehypeSlug from 'rehype-slug';
|
||||||
|
import { highlight } from './highlight';
|
||||||
|
|
||||||
|
type HastNode = {
|
||||||
|
type: string;
|
||||||
|
value?: string;
|
||||||
|
tagName?: string;
|
||||||
|
properties?: Record<string, unknown>;
|
||||||
|
children?: HastNode[];
|
||||||
|
};
|
||||||
|
|
||||||
type MarkdownRendererProps = {
|
type MarkdownRendererProps = {
|
||||||
content: string;
|
content: string;
|
||||||
scrollContainer: React.RefObject<HTMLDivElement | null>;
|
scrollContainer: React.RefObject<HTMLDivElement | null>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function getNodeText(node: HastNode): string {
|
||||||
|
if (node.type === 'text') return node.value ?? '';
|
||||||
|
if (node.children) return node.children.map(getNodeText).join('');
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
export const MarkdownRenderer = ({ content, scrollContainer }: MarkdownRendererProps) => {
|
export const MarkdownRenderer = ({ content, scrollContainer }: MarkdownRendererProps) => {
|
||||||
const handleAnchorClick = (ev: React.MouseEvent<HTMLElement>) => {
|
const handleAnchorClick = (ev: React.MouseEvent<HTMLElement>) => {
|
||||||
const target = (ev.target as HTMLElement).closest('a');
|
const target = (ev.target as HTMLElement).closest('a');
|
||||||
@@ -35,23 +50,22 @@ export const MarkdownRenderer = ({ content, scrollContainer }: MarkdownRendererP
|
|||||||
</a>
|
</a>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
pre({ children }) {
|
pre({ node, children }) {
|
||||||
return <div className="relative">{children}</div>;
|
const codeChild = node?.children[0];
|
||||||
|
if (codeChild?.type === 'element' && codeChild.tagName === 'code') {
|
||||||
|
const classes = (codeChild.properties?.className ?? []) as string[];
|
||||||
|
const lang = classes[0]?.replace('language-', '') ?? '';
|
||||||
|
const text = getNodeText(codeChild).replace(/\n$/, '');
|
||||||
|
return <HighlightedCodeBlock code={text} lang={lang} />;
|
||||||
|
}
|
||||||
|
return <pre>{children}</pre>;
|
||||||
},
|
},
|
||||||
code({ className, children, ...props }) {
|
code({ children, ...props }) {
|
||||||
const isBlock = className?.startsWith('language-');
|
|
||||||
const lang = className?.replace('language-', '') ?? '';
|
|
||||||
const text = String(children).replace(/\n$/, '');
|
|
||||||
|
|
||||||
if (!isBlock) {
|
|
||||||
return (
|
return (
|
||||||
<code className="px-1.5 py-0.5 rounded bg-duck-teal/10 text-duck-teal text-[0.85em] font-mono" {...props}>
|
<code className="px-1.5 py-0.5 rounded bg-duck-teal/10 text-duck-teal text-[0.85em] font-mono" {...props}>
|
||||||
{children}
|
{children}
|
||||||
</code>
|
</code>
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
return <HighlightedCodeBlock code={text} lang={lang} />;
|
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -84,39 +98,32 @@ const HighlightedCodeBlock = ({ code, lang }: { code: string; lang: string }) =>
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
import('shiki')
|
highlight(code, lang).then((result) => {
|
||||||
.then(({ codeToHtml }) => codeToHtml(code, { lang, theme: 'github-dark-default' }))
|
|
||||||
.then((result) => {
|
|
||||||
if (!cancelled) setHtml(result);
|
if (!cancelled) setHtml(result);
|
||||||
})
|
});
|
||||||
.catch(() => {});
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [code, lang]);
|
}, [code, lang]);
|
||||||
|
|
||||||
if (html) {
|
|
||||||
return (
|
return (
|
||||||
<div className="relative my-4">
|
<div className="relative my-4">
|
||||||
<CopyButton text={code} />
|
<CopyButton text={code} />
|
||||||
{lang && (
|
{lang && (
|
||||||
<span className="absolute top-2 left-3 text-[10px] font-mono text-white/30 uppercase tracking-wider z-10">{lang}</span>
|
<span className="absolute top-2 left-3 text-[10px] font-mono text-white/30 uppercase tracking-wider z-10">
|
||||||
|
{lang}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{html ? (
|
||||||
<div
|
<div
|
||||||
className="[&_pre]:rounded-lg [&_pre]:p-4 [&_pre]:pt-8 [&_pre]:overflow-x-auto [&_pre]:text-sm [&_pre]:font-mono [&_pre]:leading-relaxed [&_pre]:border [&_pre]:border-white/5 [&_code]:font-mono"
|
className="[&_pre]:rounded-lg [&_pre]:p-4 [&_pre]:pt-8 [&_pre]:overflow-x-auto [&_pre]:text-sm [&_pre]:font-mono [&_pre]:leading-relaxed [&_pre]:border [&_pre]:border-white/5 [&_code]:font-mono"
|
||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{ __html: html }}
|
||||||
/>
|
/>
|
||||||
|
) : (
|
||||||
|
<pre className="rounded-lg bg-[#0d1117] text-[#e6edf3] p-4 pt-8 overflow-x-auto text-sm font-mono leading-relaxed border border-white/5">
|
||||||
|
<code>{code}</code>
|
||||||
|
</pre>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<pre className="relative rounded-lg bg-[#0d1117] text-[#e6edf3] p-4 overflow-x-auto text-sm font-mono leading-relaxed my-4 border border-white/5">
|
|
||||||
<CopyButton text={code} />
|
|
||||||
{lang && (
|
|
||||||
<span className="absolute top-2 left-3 text-[10px] font-mono text-white/30 uppercase tracking-wider">{lang}</span>
|
|
||||||
)}
|
|
||||||
<code className="block pt-4">{code}</code>
|
|
||||||
</pre>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { BundledLanguage, BundledTheme, HighlighterGeneric } from 'shiki';
|
||||||
|
import { createHighlighter } from 'shiki';
|
||||||
|
|
||||||
|
const THEME = 'github-dark-default' as const;
|
||||||
|
|
||||||
|
let instance: Promise<HighlighterGeneric<BundledLanguage, BundledTheme>> | null = null;
|
||||||
|
|
||||||
|
function getHighlighter() {
|
||||||
|
if (!instance) {
|
||||||
|
instance = createHighlighter({ themes: [THEME], langs: [] });
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function highlight(code: string, lang: string): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const highlighter = await getHighlighter();
|
||||||
|
if (lang && !highlighter.getLoadedLanguages().includes(lang)) {
|
||||||
|
await highlighter.loadLanguage(lang as BundledLanguage);
|
||||||
|
}
|
||||||
|
return highlighter.codeToHtml(code, { lang: lang || 'text', theme: THEME });
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,8 +9,8 @@ export { useRecentModels } from './useRecentModels';
|
|||||||
export { usePlans } from './usePlans';
|
export { usePlans } from './usePlans';
|
||||||
export { useLandingPage } from './useLandingPage';
|
export { useLandingPage } from './useLandingPage';
|
||||||
export { useServerSettings } from './useServerSettings';
|
export { useServerSettings } from './useServerSettings';
|
||||||
export { useResources, getResourceCategory } from './useResources';
|
export { useResources } from './useResources';
|
||||||
export type { Resource, ResourceCredentials, ResourceConnectionConfig, PingResult, ResourceCategory } from './useResources';
|
export type { ResourceSummary, ResourceDetail, PingResult } from './useResources';
|
||||||
export { useChatSessions } from './useChatSessions';
|
export { useChatSessions } from './useChatSessions';
|
||||||
export type { UseChatSessionsType } from './useChatSessions';
|
export type { UseChatSessionsType } from './useChatSessions';
|
||||||
export { useChatGroups } from './useChatGroups';
|
export { useChatGroups } from './useChatGroups';
|
||||||
|
|||||||
@@ -1,32 +1,21 @@
|
|||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useClient } from 'hooks/useClient';
|
import { useClient } from 'hooks/useClient';
|
||||||
|
|
||||||
export type ResourceCredentials = {
|
export type ResourceSummary = {
|
||||||
apiKey?: string;
|
dirName: string;
|
||||||
username?: string;
|
|
||||||
password?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ResourceConnectionConfig = {
|
|
||||||
url: string;
|
|
||||||
credentials?: ResourceCredentials;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type Resource = {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
name: string;
|
||||||
subtitle: string;
|
|
||||||
type: string;
|
|
||||||
port: string | null;
|
|
||||||
description: string;
|
description: string;
|
||||||
installCommand: string | null;
|
scope: 'native' | 'global';
|
||||||
uninstallCommand: string | null;
|
config: Record<string, string>;
|
||||||
manageCommand: string | null;
|
};
|
||||||
verifyCommand: string | null;
|
|
||||||
updateCommand: string | null;
|
export type ResourceDetail = ResourceSummary & {
|
||||||
installed: boolean;
|
body: string;
|
||||||
version: string | null;
|
rawFrontmatter: string;
|
||||||
connectionConfig: ResourceConnectionConfig | null;
|
filePath: string;
|
||||||
|
configPath: string;
|
||||||
|
chatSessionId: string | null;
|
||||||
|
guidePath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PingResult = {
|
export type PingResult = {
|
||||||
@@ -34,10 +23,6 @@ export type PingResult = {
|
|||||||
latencyMs: number | null;
|
latencyMs: number | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ResourceCategory = 'api-based' | 'local-cli';
|
|
||||||
|
|
||||||
export const getResourceCategory = (r: Resource): ResourceCategory => (r.port ? 'api-based' : 'local-cli');
|
|
||||||
|
|
||||||
const RESOURCES_KEY = ['RESOURCES'];
|
const RESOURCES_KEY = ['RESOURCES'];
|
||||||
|
|
||||||
export const useResources = () => {
|
export const useResources = () => {
|
||||||
@@ -46,23 +31,31 @@ export const useResources = () => {
|
|||||||
|
|
||||||
const { data: resources, isLoading } = useQuery({
|
const { data: resources, isLoading } = useQuery({
|
||||||
queryKey: RESOURCES_KEY,
|
queryKey: RESOURCES_KEY,
|
||||||
queryFn: () => client.get<Resource[]>('/server-settings/resources'),
|
queryFn: () => client.get<ResourceSummary[]>('/server-settings/resources'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const saveConnectionConfig = async (id: string, config: Partial<ResourceConnectionConfig>) => {
|
const getDetail = (name: string) =>
|
||||||
await client.patch(`/server-settings/resources/config/${id}`, config);
|
client.get<ResourceDetail>(`/server-settings/resources/${name}`);
|
||||||
|
|
||||||
|
const saveConfig = async (name: string, config: Record<string, string | null>) => {
|
||||||
|
await client.patch(`/server-settings/resources/${name}/config`, config);
|
||||||
queryClient.invalidateQueries({ queryKey: RESOURCES_KEY });
|
queryClient.invalidateQueries({ queryKey: RESOURCES_KEY });
|
||||||
};
|
};
|
||||||
|
|
||||||
const pingResource = async (id: string, url?: string) => {
|
const createResource = async (name: string) => {
|
||||||
return client.post<PingResult>(`/server-settings/resources/${id}/ping`, { url });
|
const result = await client.post<{ name: string; dirName: string }>('/server-settings/resources', { name });
|
||||||
};
|
|
||||||
|
|
||||||
const runCommand = async (id: string, action: string) => {
|
|
||||||
const result = await client.post<{ exitCode: number; output: string }>(`/server-settings/resources/${id}/run`, { action });
|
|
||||||
queryClient.invalidateQueries({ queryKey: RESOURCES_KEY });
|
queryClient.invalidateQueries({ queryKey: RESOURCES_KEY });
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
return { resources, isLoading, saveConnectionConfig, pingResource, runCommand };
|
const deleteResource = async (name: string) => {
|
||||||
|
await client.delete(`/server-settings/resources/${name}`);
|
||||||
|
queryClient.invalidateQueries({ queryKey: RESOURCES_KEY });
|
||||||
|
};
|
||||||
|
|
||||||
|
const pingResource = async (name: string, url?: string) => {
|
||||||
|
return client.post<PingResult>(`/server-settings/resources/${name}/ping`, { url });
|
||||||
|
};
|
||||||
|
|
||||||
|
return { resources, isLoading, getDetail, saveConfig, createResource, deleteResource, pingResource };
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user