Remove AgentBuilder, add file ops UI, unify code editor prompt routing
- Delete agent-builder-integration.ts, workflow-store.ts, prompts.ts (~1400줄) - Add move_file tool + sidebar file ops (right-click menu, inline rename, drag-drop, new folder) - Loop detection: read-only tools block at 2 repeats; planText capped at 12000 chars (fix 413) - Route proj-gen-*/proj-plan-* to handleCodeChat; remove duplicate codeAiSystemPrompt from handleChat Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
508d11615a
commit
ac518bc2a5
10 files changed
+562
-1563
No files matched your search
@@ -34,3 +34,7 @@
|
||||
[20:27:06] **SmallClaw**: HEARTBEAT_OK
|
||||
[20:57:08] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[20:57:17] **SmallClaw**: HEARTBEAT_OK
|
||||
[08:24:14] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[08:24:28] **SmallClaw**: HEARTBEAT_OK
|
||||
[08:54:29] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[08:54:43] **SmallClaw**: HEARTBEAT_OK
|
||||
@@ -0,0 +1,27 @@
|
||||
[09:24:45] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[09:24:51] **SmallClaw**: HEARTBEAT_OK
|
||||
[09:54:52] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[09:55:10] **SmallClaw**: HEARTBEAT_OK
|
||||
[10:25:12] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[10:25:44] **SmallClaw**: ```json
|
||||
{
|
||||
"project-files": []
|
||||
}
|
||||
```
|
||||
[11:51:43] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[11:51:55] **SmallClaw**: HEARTBEAT_OK
|
||||
[12:21:56] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[12:22:12] **SmallClaw**: HEARTBEAT_OK
|
||||
[13:31:39] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[13:31:57] **SmallClaw**: HEARTBEAT_OK
|
||||
[14:10:12] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[14:10:31] **SmallClaw**: HEARTBEAT_OK
|
||||
[14:40:32] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[14:40:44] **SmallClaw**: HEARTBEAT_OK
|
||||
[15:10:45] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[15:10:59] **SmallClaw**: HEARTBEAT_OK
|
||||
[16:09:32] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[16:10:20] **SmallClaw**: HEARTBEAT_OK
|
||||
[16:40:22] **User**: Check for anything important and reply HEARTBEAT_OK if nothing needs attention.
|
||||
[16:41:16] **SmallClaw**: HEARTBEAT_OK
|
||||
[16:41:18] **SmallClaw**: HEARTBEAT_OK
|
||||
@@ -1,11 +0,0 @@
|
||||
/**
|
||||
* prompts.ts — workflow context helpers
|
||||
* BASE_WORKFLOW_PROMPT was removed (dead code — never imported by active code paths).
|
||||
* Workflow context is injected via getWorkflowContextBlock() in server-v2.ts.
|
||||
*/
|
||||
|
||||
import { getWorkflowContextBlock } from '../gateway/agent-builder-integration';
|
||||
|
||||
export function getWorkflowMemoryOnly(): string {
|
||||
return getWorkflowContextBlock();
|
||||
}
|
||||
@@ -1,938 +0,0 @@
|
||||
/**
|
||||
* agent-builder-integration.ts
|
||||
* SmallClaw ↔ Agent Builder bridge — with persistent workflow memory
|
||||
*
|
||||
* Tools exposed to the LLM:
|
||||
* 1. architect_workflow — Design + create a new workflow
|
||||
* 2. verify_workflow_credentials — Check all creds are present
|
||||
* 3. test_workflow — Run a dry-run test
|
||||
* 4. deploy_workflow — Activate + SAVE to WorkflowStore
|
||||
* 5. get_workflow_status — Check current status
|
||||
* 6. search_workflow_templates — Search WorkflowStore (local-first, then Agent Builder)
|
||||
* 7. execute_workflow_template — Execute a registered workflow
|
||||
* 8. create_node_subagent — Create + attach a writing subagent for AI-authoring nodes
|
||||
*
|
||||
* File location: src/gateway/agent-builder-integration.ts
|
||||
*/
|
||||
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { workflowStore, StoredWorkflow } from './workflow-store';
|
||||
|
||||
// ─── Config ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const AGENT_BUILDER_URL = process.env.AGENT_BUILDER_URL || 'http://localhost:3005';
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const MAX_RETRIES = 2;
|
||||
const RETRY_DELAY_MS = 1_000;
|
||||
|
||||
// ─── HTTP helper ──────────────────────────────────────────────────────────────
|
||||
|
||||
function abCall(method: string, path: string, body?: object): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = new URL(path, AGENT_BUILDER_URL);
|
||||
const isHttps = url.protocol === 'https:';
|
||||
const transport = isHttps ? https : http;
|
||||
const payload = body ? JSON.stringify(body) : undefined;
|
||||
|
||||
const options: http.RequestOptions = {
|
||||
hostname: url.hostname,
|
||||
port: url.port || (isHttps ? 443 : 80),
|
||||
path: url.pathname + url.search,
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'SmallClaw-AgentBuilder/1.5',
|
||||
...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {})
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT_MS
|
||||
};
|
||||
|
||||
const req = transport.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', chunk => data += chunk);
|
||||
res.on('end', () => {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch {
|
||||
resolve({ ok: false, error: 'Non-JSON response from Agent Builder', raw: data });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
reject(new Error(`Agent Builder request timed out after ${REQUEST_TIMEOUT_MS}ms`));
|
||||
});
|
||||
|
||||
req.on('error', (err) => {
|
||||
reject(new Error(
|
||||
`Agent Builder unreachable at ${AGENT_BUILDER_URL}. Is it running? (${err.message})`
|
||||
));
|
||||
});
|
||||
|
||||
if (payload) req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** abCall with automatic retry on transient errors */
|
||||
async function abCallWithRetry(method: string, path: string, body?: object, retries = MAX_RETRIES): Promise<any> {
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
try {
|
||||
return await abCall(method, path, body);
|
||||
} catch (err: any) {
|
||||
if (attempt === retries) throw err;
|
||||
console.warn(`[AgentBuilder] Attempt ${attempt + 1} failed, retrying in ${RETRY_DELAY_MS}ms...`);
|
||||
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Tool Implementations ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Tool 1: architect_workflow
|
||||
*
|
||||
* IMPORTANT: The LLM should ALWAYS call search_workflow_templates first.
|
||||
* Only call this if no suitable template exists.
|
||||
*/
|
||||
async function architect_workflow(args: {
|
||||
description: string;
|
||||
constraints?: Record<string, any>;
|
||||
}): Promise<string> {
|
||||
console.log('[AgentBuilder] architect_workflow:', args.description);
|
||||
|
||||
// Pre-flight: check local store first — LLM might have skipped search
|
||||
const localMatches = workflowStore.search(args.description, { limit: 3 });
|
||||
if (localMatches.length > 0) {
|
||||
const suggestions = localMatches.map(wf =>
|
||||
`- "${wf.name}" [${wf.workflow_id}] — ${wf.description}`
|
||||
).join('\n');
|
||||
return JSON.stringify({
|
||||
success: false,
|
||||
hint: 'existing_workflows_found',
|
||||
message: 'Before creating a new workflow, consider these existing ones:',
|
||||
suggestions,
|
||||
action: 'Use execute_workflow_template() with one of these IDs, or call architect_workflow() again with force=true to override.'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await abCallWithRetry('POST', '/api/v1/ai/architect', {
|
||||
description: args.description,
|
||||
constraints: args.constraints || {}
|
||||
});
|
||||
|
||||
if (result.workflow_id) {
|
||||
console.log(`[AgentBuilder] Workflow designed: ${result.workflow_id}`);
|
||||
}
|
||||
|
||||
return JSON.stringify(result);
|
||||
} catch (err: any) {
|
||||
return JSON.stringify({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 2: verify_workflow_credentials
|
||||
*/
|
||||
async function verify_workflow_credentials(args: { workflow_id: string }): Promise<string> {
|
||||
console.log('[AgentBuilder] verify_credentials:', args.workflow_id);
|
||||
|
||||
try {
|
||||
const result = await abCallWithRetry('GET', `/api/v1/workflows/${args.workflow_id}/verify-credentials`);
|
||||
|
||||
if (result.all_credentials_present) {
|
||||
workflowStore.markCredentialsVerified(args.workflow_id);
|
||||
console.log(`[WorkflowStore] Credentials verified for ${args.workflow_id}`);
|
||||
}
|
||||
|
||||
// Build a human-friendly message SmallClaw can relay directly to the user.
|
||||
// If credentials are missing, include the deep-link URLs so the user can
|
||||
// click straight into the right Agent Builder credential form.
|
||||
if (!result.all_credentials_present && result.credential_actions?.length) {
|
||||
const actions: Array<{ provider: string; label: string; add_credential_url: string }> = result.credential_actions;
|
||||
|
||||
const linkLines = actions.map((a: any) =>
|
||||
`• **${a.provider}** (${a.label})\n → [Add credentials here](${a.add_credential_url})`
|
||||
).join('\n');
|
||||
|
||||
result.user_message = [
|
||||
`To continue building this workflow I need ${actions.length === 1 ? 'a credential' : 'some credentials'} from you:\n`,
|
||||
linkLines,
|
||||
`\nEach link opens Agent Builder directly to the right setup form.`,
|
||||
`Once you\'ve added them, just say \'done\' and I\'ll verify and continue.`,
|
||||
].join('\n');
|
||||
} else if (result.all_credentials_present) {
|
||||
result.user_message = `All credentials are configured — ready to test and deploy.`;
|
||||
}
|
||||
|
||||
return JSON.stringify(result);
|
||||
} catch (err: any) {
|
||||
return JSON.stringify({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 3: test_workflow
|
||||
*/
|
||||
async function test_workflow(args: { workflow_id: string }): Promise<string> {
|
||||
console.log('[AgentBuilder] test_workflow:', args.workflow_id);
|
||||
|
||||
try {
|
||||
const result = await abCallWithRetry('POST', `/api/v1/workflows/${args.workflow_id}/test`);
|
||||
return JSON.stringify(result);
|
||||
} catch (err: any) {
|
||||
return JSON.stringify({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 4: deploy_workflow
|
||||
*
|
||||
* This is the critical persistence point. After a successful deploy,
|
||||
* the workflow is saved to WorkflowStore so SmallClaw remembers it forever.
|
||||
*/
|
||||
async function deploy_workflow(args: {
|
||||
workflow_id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
type: StoredWorkflow['type'];
|
||||
action: string;
|
||||
tags?: string[];
|
||||
required_inputs?: string[];
|
||||
optional_inputs?: string[];
|
||||
credentials_required?: string[];
|
||||
cron_expression?: string;
|
||||
}): Promise<string> {
|
||||
console.log('[AgentBuilder] deploy_workflow:', args.workflow_id);
|
||||
|
||||
try {
|
||||
// 1. Activate the workflow in Agent Builder's SQLite (sets status = 'active',
|
||||
// also registers cron job if it has a cron_expression)
|
||||
await abCallWithRetry('POST', `/api/v1/workflows/${args.workflow_id}/activate`);
|
||||
console.log(`[AgentBuilder] Workflow ${args.workflow_id} activated`);
|
||||
|
||||
// 2. Register as a reusable template — returns reg_xxxxxx template_id
|
||||
// This is what registry/execute requires to dispatch the run
|
||||
const registryResult = await abCallWithRetry('POST', `/api/v1/workflows/registry/register`, {
|
||||
workflow_id: args.workflow_id,
|
||||
name: args.name,
|
||||
description: args.description,
|
||||
tags: args.tags || [],
|
||||
parameters: (args.required_inputs || []).map((name: string) => ({
|
||||
name,
|
||||
description: `Input: ${name}`,
|
||||
required: true,
|
||||
})).concat(
|
||||
(args.optional_inputs || []).map((name: string) => ({
|
||||
name,
|
||||
description: `Input: ${name}`,
|
||||
required: false,
|
||||
}))
|
||||
),
|
||||
});
|
||||
|
||||
// Extract the reg_xxxxxx template ID from the registry response
|
||||
const templateId: string | undefined =
|
||||
registryResult?.template?.id ||
|
||||
registryResult?.id ||
|
||||
undefined;
|
||||
|
||||
if (!templateId) {
|
||||
console.warn(`[AgentBuilder] registry/register did not return a template id — execute will fall back to direct execution`);
|
||||
} else {
|
||||
console.log(`[AgentBuilder] Registry template ID: ${templateId}`);
|
||||
}
|
||||
|
||||
// 3. Save to SmallClaw's persistent store — includes template_id for future execute calls
|
||||
const stored = workflowStore.register({
|
||||
workflow_id: args.workflow_id,
|
||||
template_id: templateId,
|
||||
name: args.name,
|
||||
description: args.description,
|
||||
type: args.type,
|
||||
action: args.action,
|
||||
tags: args.tags || [],
|
||||
required_inputs: args.required_inputs || [],
|
||||
optional_inputs: args.optional_inputs || [],
|
||||
status: 'active',
|
||||
cron_expression: args.cron_expression,
|
||||
credentials_required: args.credentials_required || [],
|
||||
credentials_verified: true,
|
||||
});
|
||||
|
||||
console.log(`[WorkflowStore] ✅ Saved to persistent store: ${stored.workflow_id} (template: ${templateId ?? 'none'}) — "${stored.name}"`);
|
||||
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
workflow_id: args.workflow_id,
|
||||
template_id: templateId,
|
||||
persisted_locally: true,
|
||||
message: `Workflow "${args.name}" activated and saved. Future requests will reuse this workflow — no rebuild needed.`,
|
||||
reuse_tip: `To execute this workflow again, call execute_workflow_template("${args.workflow_id}", { ...inputs })`
|
||||
});
|
||||
} catch (err: any) {
|
||||
return JSON.stringify({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 5: get_workflow_status
|
||||
*/
|
||||
async function get_workflow_status(args: { workflow_id: string }): Promise<string> {
|
||||
console.log('[AgentBuilder] get_workflow_status:', args.workflow_id);
|
||||
|
||||
// Check local store first for instant response
|
||||
const local = workflowStore.get(args.workflow_id);
|
||||
|
||||
try {
|
||||
const result = await abCallWithRetry('GET', `/api/v1/workflows/${args.workflow_id}/details`);
|
||||
|
||||
// Sync status back to local store if it changed
|
||||
if (result.status && local) {
|
||||
workflowStore.updateStatus(args.workflow_id, result.status);
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
...result,
|
||||
local_record: local ? {
|
||||
execution_count: local.execution_count,
|
||||
last_executed: local.last_executed,
|
||||
credentials_verified: local.credentials_verified
|
||||
} : null
|
||||
});
|
||||
} catch (err: any) {
|
||||
// Serve from local cache if Agent Builder is unreachable
|
||||
if (local) {
|
||||
console.warn('[AgentBuilder] Serving from local cache — Agent Builder unreachable');
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
source: 'local_cache',
|
||||
workflow_id: local.workflow_id,
|
||||
name: local.name,
|
||||
status: local.status,
|
||||
execution_count: local.execution_count,
|
||||
last_executed: local.last_executed,
|
||||
warning: 'Agent Builder unreachable — showing cached data'
|
||||
});
|
||||
}
|
||||
return JSON.stringify({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 6: search_workflow_templates
|
||||
*
|
||||
* LOCAL-FIRST: Searches SmallClaw's persistent store before hitting Agent Builder.
|
||||
* This is the primary way SmallClaw avoids creating duplicate workflows.
|
||||
*
|
||||
* LLM should ALWAYS call this before architect_workflow().
|
||||
*/
|
||||
async function search_workflow_templates(args: {
|
||||
query: string;
|
||||
type?: 'action' | 'scheduled' | 'background';
|
||||
limit?: number;
|
||||
}): Promise<string> {
|
||||
console.log('[WorkflowStore] search_workflow_templates:', args.query);
|
||||
|
||||
// 1. Search local persistent store first (instant, no network)
|
||||
const localResults = workflowStore.search(args.query, {
|
||||
type: args.type,
|
||||
limit: args.limit || 5
|
||||
});
|
||||
|
||||
if (localResults.length > 0) {
|
||||
console.log(`[WorkflowStore] Found ${localResults.length} local matches for "${args.query}"`);
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
source: 'local_store',
|
||||
query: args.query,
|
||||
templates: localResults.map(wf => ({
|
||||
workflow_id: wf.workflow_id,
|
||||
name: wf.name,
|
||||
description: wf.description,
|
||||
type: wf.type,
|
||||
action: wf.action,
|
||||
tags: wf.tags,
|
||||
required_inputs: wf.required_inputs,
|
||||
optional_inputs: wf.optional_inputs,
|
||||
execution_count: wf.execution_count,
|
||||
last_executed: wf.last_executed,
|
||||
status: wf.status
|
||||
})),
|
||||
count: localResults.length,
|
||||
message: localResults.length === 1
|
||||
? `Found an existing workflow that matches. Use execute_workflow_template("${localResults[0].workflow_id}", {...}) instead of creating a new one.`
|
||||
: `Found ${localResults.length} existing workflows. Choose one and use execute_workflow_template() to run it.`
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Fall back to Agent Builder registry (may have entries not in local store yet)
|
||||
console.log('[WorkflowStore] No local matches — checking Agent Builder registry');
|
||||
try {
|
||||
const params = new URLSearchParams({ search: args.query, limit: String(args.limit || 5) });
|
||||
if (args.type) params.set('type', args.type);
|
||||
|
||||
const result = await abCallWithRetry('GET', `/api/v1/workflows/registry/list?${params}`);
|
||||
|
||||
if (result.templates && result.templates.length > 0) {
|
||||
// Backfill any Agent Builder templates we don't have locally
|
||||
for (const tpl of result.templates) {
|
||||
if (tpl.workflow_id && !workflowStore.has(tpl.workflow_id)) {
|
||||
workflowStore.register({
|
||||
workflow_id: tpl.workflow_id,
|
||||
name: tpl.name,
|
||||
description: tpl.description || '',
|
||||
type: tpl.type || 'action',
|
||||
action: tpl.action || 'custom',
|
||||
tags: tpl.tags || [],
|
||||
required_inputs: tpl.required_inputs || [],
|
||||
optional_inputs: tpl.optional_inputs || [],
|
||||
status: 'active',
|
||||
credentials_required: [],
|
||||
});
|
||||
console.log(`[WorkflowStore] Backfilled workflow from Agent Builder: ${tpl.workflow_id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
source: 'agent_builder_registry',
|
||||
...result,
|
||||
templates: result.templates || [],
|
||||
count: result.templates?.length || 0
|
||||
});
|
||||
} catch (err: any) {
|
||||
return JSON.stringify({
|
||||
success: false,
|
||||
source: 'none',
|
||||
error: err.message,
|
||||
local_count: 0,
|
||||
message: 'No existing templates found. Use architect_workflow() to create a new one.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 7: execute_workflow_template
|
||||
*
|
||||
* Execute a registered workflow with runtime parameters.
|
||||
* Records execution in WorkflowStore for usage tracking.
|
||||
*/
|
||||
async function execute_workflow_template(args: {
|
||||
workflow_id: string;
|
||||
inputs?: Record<string, any>;
|
||||
trigger_phrase?: string;
|
||||
}): Promise<string> {
|
||||
console.log('[AgentBuilder] execute_workflow_template:', args.workflow_id);
|
||||
|
||||
// Look up locally to validate before calling Agent Builder
|
||||
const local = workflowStore.get(args.workflow_id);
|
||||
if (local && local.status !== 'active') {
|
||||
return JSON.stringify({
|
||||
success: false,
|
||||
error: `Workflow "${local.name}" is not active (status: ${local.status}). Check Agent Builder dashboard.`
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
let result: any;
|
||||
|
||||
if (local?.template_id) {
|
||||
// Primary path: registry/execute requires template_id (reg_xxxxxx)
|
||||
// WorkflowRegistry is in Agent Builder RAM, so this works as long as
|
||||
// Agent Builder hasn't restarted since deploy. If it has, fall through.
|
||||
result = await abCallWithRetry('POST', `/api/v1/workflows/registry/execute`, {
|
||||
template_id: local.template_id,
|
||||
parameters: args.inputs || {},
|
||||
});
|
||||
|
||||
// If Agent Builder restarted, WorkflowRegistry is empty — fall back to direct execute
|
||||
if (!result?.ok && (result?.error?.includes('Template not found') || result?.error?.includes('template_id'))) {
|
||||
console.warn(`[AgentBuilder] Template ${local.template_id} not found in registry (restart?) — falling back to direct execute`);
|
||||
result = await abCallWithRetry('POST', `/api/v1/workflows/${args.workflow_id}/execute?sync=true`, {
|
||||
triggerData: args.inputs || {},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Fallback path: no template_id stored (deployed before this fix, or registry/register failed)
|
||||
// Hit the workflow's direct execute endpoint instead
|
||||
console.warn(`[AgentBuilder] No template_id for ${args.workflow_id} — using direct execute`);
|
||||
result = await abCallWithRetry('POST', `/api/v1/workflows/${args.workflow_id}/execute?sync=true`, {
|
||||
triggerData: args.inputs || {},
|
||||
});
|
||||
}
|
||||
|
||||
// Record execution in local store
|
||||
workflowStore.recordExecution(args.workflow_id);
|
||||
|
||||
// If the user used a phrase to trigger this, learn it
|
||||
if (args.trigger_phrase && local) {
|
||||
workflowStore.addTriggerPhrases(args.workflow_id, [args.trigger_phrase]);
|
||||
}
|
||||
|
||||
const name = local?.name || args.workflow_id;
|
||||
const execCount = (local?.execution_count ?? 0) + 1;
|
||||
const wasSuccess = result?.ok === true || result?.success === true;
|
||||
const output = result?.result?.output || result?.output || null;
|
||||
const duration = result?.result?.duration || result?.duration || null;
|
||||
|
||||
// Build a plain-English summary the LLM should relay to the user verbatim.
|
||||
// This is the notification bridge — Agent Builder ran something, SmallClaw tells you.
|
||||
let user_message: string;
|
||||
if (wasSuccess) {
|
||||
const parts = [`✅ **${name}** ran successfully.`];
|
||||
if (duration) parts.push(`Completed in ${duration < 1000 ? duration + 'ms' : (duration / 1000).toFixed(1) + 's'}.`);
|
||||
if (output && typeof output === 'object') {
|
||||
const outputStr = JSON.stringify(output, null, 2);
|
||||
if (outputStr.length < 400) parts.push(`\nOutput:\n\`\`\`\n${outputStr}\n\`\`\``);
|
||||
} else if (output && typeof output === 'string' && output.length < 400) {
|
||||
parts.push(`\nOutput: ${output}`);
|
||||
}
|
||||
parts.push(`\n_(Run #${execCount} for this workflow)_`);
|
||||
user_message = parts.join(' ');
|
||||
} else {
|
||||
const errorMsg = result?.result?.error || result?.error || 'unknown error';
|
||||
user_message = [
|
||||
`❌ **${name}** failed.`,
|
||||
`Error: ${errorMsg}`,
|
||||
`You can check the full execution log in Agent Builder under Executions.`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
...result,
|
||||
workflow_name: name,
|
||||
execution_count: execCount,
|
||||
user_message,
|
||||
});
|
||||
} catch (err: any) {
|
||||
const name = local?.name || args.workflow_id;
|
||||
return JSON.stringify({
|
||||
success: false,
|
||||
error: err.message,
|
||||
user_message: `❌ **${name}** could not be executed. Agent Builder may be offline or the workflow may have an error. Details: ${err.message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Tool Definitions (LLM schema) ────────────────────────────────────────────
|
||||
|
||||
// ───────────────────────────────────────────────────────────────────────────────
|
||||
// Tool 8: create_node_subagent
|
||||
// Called when architect detects an AI-authoring node (tweet, email, Slack, etc.)
|
||||
// Runs an onboarding conversation, builds the subagent workspace + identity files,
|
||||
// then returns the agentId to be stored in node.data.subagent_config.
|
||||
// ───────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function create_node_subagent(args: {
|
||||
node_type: string;
|
||||
node_action: string;
|
||||
workflow_id: string;
|
||||
workflow_name: string;
|
||||
onboarding_answers: {
|
||||
purpose: string; // "What is this account/channel about?"
|
||||
tone: string; // "What tone should content have?"
|
||||
hard_rules: string; // "Any hard rules? Things to never say?"
|
||||
topics: string; // "What topics should it cover?"
|
||||
post_frequency?: string; // "How often will this run?"
|
||||
extra?: string; // Any other instructions
|
||||
};
|
||||
}): Promise<string> {
|
||||
const { node_type, node_action, workflow_id, workflow_name, onboarding_answers: answers } = args;
|
||||
|
||||
// Generate a stable, human-readable agentId
|
||||
const slug = workflow_name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_|_$/g, '')
|
||||
.slice(0, 30);
|
||||
const suffix = Math.random().toString(36).slice(2, 7);
|
||||
const agentId = `${slug}_${suffix}`;
|
||||
|
||||
const nodeLabel = `${node_type} (${node_action})`;
|
||||
const outputField = OUTPUT_FIELD_FOR_NODE[node_type] || 'text';
|
||||
|
||||
// Build SOUL.md — the agent's immutable identity and voice
|
||||
const soulMd = [
|
||||
`# ${workflow_name} — Writing Agent`,
|
||||
``,
|
||||
`## Purpose`,
|
||||
answers.purpose,
|
||||
``,
|
||||
`## Tone`,
|
||||
answers.tone,
|
||||
``,
|
||||
`## Hard Rules (NEVER violate these)`,
|
||||
answers.hard_rules,
|
||||
``,
|
||||
`## Post Frequency`,
|
||||
answers.post_frequency || 'Not specified',
|
||||
``,
|
||||
`## Additional Instructions`,
|
||||
answers.extra || 'None',
|
||||
``,
|
||||
`---`,
|
||||
`This file defines who you are. Read it before every task.`,
|
||||
`Do not deviate from these instructions.`,
|
||||
].join('\n');
|
||||
|
||||
// Build topics.md — the rotation list
|
||||
const topicsMd = [
|
||||
`# Topics Rotation`,
|
||||
``,
|
||||
`Rotate through these topics. Track which you've covered in MEMORY.md.`,
|
||||
``,
|
||||
answers.topics
|
||||
.split(/[,\n]+/)
|
||||
.map((t: string) => t.trim())
|
||||
.filter(Boolean)
|
||||
.map((t: string, i: number) => `${i + 1}. ${t}`)
|
||||
.join('\n'),
|
||||
].join('\n');
|
||||
|
||||
// Build MEMORY.md — seeded with initial context
|
||||
const memoryMd = [
|
||||
`# Memory`,
|
||||
``,
|
||||
`## Last Topics Covered`,
|
||||
`(none yet — this is the first run)`,
|
||||
``,
|
||||
`## Notes`,
|
||||
`Agent created for workflow: ${workflow_name} (${workflow_id})`,
|
||||
`Node: ${nodeLabel}`,
|
||||
`Created: ${new Date().toISOString()}`,
|
||||
].join('\n');
|
||||
|
||||
// Build system_instructions for the config
|
||||
const systemInstructions = [
|
||||
`You are a specialized writing agent for: ${answers.purpose}`,
|
||||
``,
|
||||
`Your job is to generate ${nodeLabel} content that is:`,
|
||||
`- Tone: ${answers.tone}`,
|
||||
`- Relevant to the current topic rotation (see topics.md)`,
|
||||
`- Never repeating what you've already posted (see history.md)`,
|
||||
``,
|
||||
`Before writing, ALWAYS:`,
|
||||
`1. Read SOUL.md for your voice and hard rules`,
|
||||
`2. Read topics.md for the current topic rotation`,
|
||||
`3. Read history.md to avoid repeating yourself`,
|
||||
`4. Read MEMORY.md for any running context`,
|
||||
``,
|
||||
`After writing, update MEMORY.md with what topic you covered.`,
|
||||
`Return your output as JSON: { "${outputField}": "your content here" }`,
|
||||
].join('\n');
|
||||
|
||||
// Write all workspace files via Agent Builder's subagent registry endpoint
|
||||
// (Agent Builder stores them and SmallClaw reads them at runtime)
|
||||
const result = await abCallWithRetry('POST', '/api/v1/subagents/create', {
|
||||
agent_id: agentId,
|
||||
workflow_id,
|
||||
node_type,
|
||||
node_action,
|
||||
output_field: outputField,
|
||||
name: `${workflow_name} Writer`,
|
||||
description: answers.purpose,
|
||||
system_instructions: systemInstructions,
|
||||
constraints: [
|
||||
answers.hard_rules,
|
||||
'Return output as JSON with the correct output_field key',
|
||||
'Read memory files before every task',
|
||||
'Update MEMORY.md after every task',
|
||||
'Never repeat a topic covered in history.md',
|
||||
].filter(Boolean),
|
||||
success_criteria: `A complete, ready-to-publish ${node_action} in the correct JSON format`,
|
||||
max_steps: 10,
|
||||
timeout_ms: 45_000,
|
||||
memory_files: {
|
||||
'SOUL.md': soulMd,
|
||||
'topics.md': topicsMd,
|
||||
'MEMORY.md': memoryMd,
|
||||
},
|
||||
});
|
||||
|
||||
const taskTemplate = [
|
||||
`You are the ${workflow_name} writing agent.`,
|
||||
`Read your SOUL.md, topics.md, and history.md first.`,
|
||||
`Write one ${node_action} following your tone and topic rotation.`,
|
||||
`Return ONLY: { "${outputField}": "your content here" }`,
|
||||
].join(' ');
|
||||
|
||||
// Now patch the workflow node with the subagent_config
|
||||
await abCallWithRetry('POST', `/api/v1/workflows/${workflow_id}/patch-node-subagent`, {
|
||||
agent_id: agentId,
|
||||
node_type,
|
||||
node_action,
|
||||
task_template: taskTemplate,
|
||||
output_field: outputField,
|
||||
});
|
||||
|
||||
const user_message = [
|
||||
`✅ Created **${workflow_name} Writer** agent (\`${agentId}\`).`,
|
||||
``,
|
||||
`This agent will generate ${node_action} content each time the workflow runs.`,
|
||||
`It has its own memory, topic rotation, and voice defined by what you told me.`,
|
||||
``,
|
||||
`**Identity:** ${answers.purpose}`,
|
||||
`**Tone:** ${answers.tone}`,
|
||||
`**Topics:** ${answers.topics.slice(0, 100)}${answers.topics.length > 100 ? '...' : ''}`,
|
||||
``,
|
||||
`The workflow is ready to deploy. Want me to continue?`,
|
||||
].join('\n');
|
||||
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
agent_id: agentId,
|
||||
workflow_id,
|
||||
output_field: outputField,
|
||||
user_message,
|
||||
...(result || {}),
|
||||
});
|
||||
}
|
||||
|
||||
// Map node types to their output field name (mirrors agent-node-registry.js)
|
||||
const OUTPUT_FIELD_FOR_NODE: Record<string, string> = {
|
||||
'social.twitter': 'text',
|
||||
'social.linkedin': 'text',
|
||||
'social.facebook': 'message',
|
||||
'google.gmail': 'body',
|
||||
'email.send': 'body',
|
||||
'notify.slack': 'text',
|
||||
'notify.discord': 'content',
|
||||
'google.docs': 'content',
|
||||
'microsoft.outlook': 'body',
|
||||
'microsoft.teams': 'message',
|
||||
};
|
||||
|
||||
export const AGENT_BUILDER_TOOL_DEFINITIONS = [
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'architect_workflow',
|
||||
description: `Design and create a NEW workflow in Agent Builder. \nIMPORTANT: ALWAYS call search_workflow_templates first. Only call this if no suitable template exists — creating duplicates wastes time and API budget.\nIf search returns results, use execute_workflow_template() instead.`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
description: {
|
||||
type: 'string',
|
||||
description: 'Plain English description of what the workflow should do. Be specific: platform, trigger, action, frequency.'
|
||||
},
|
||||
constraints: {
|
||||
type: 'object',
|
||||
description: 'Optional constraints: { schedule: "9am daily", platforms: ["x"], tone: "professional" }'
|
||||
}
|
||||
},
|
||||
required: ['description']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'verify_workflow_credentials',
|
||||
description: 'Check whether all required API credentials for a workflow are present in Agent Builder. Call this after architect_workflow() returns credentials_needed.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
workflow_id: { type: 'string', description: 'Workflow ID from architect_workflow response, e.g. wf_abc123' }
|
||||
},
|
||||
required: ['workflow_id']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'test_workflow',
|
||||
description: 'Run a dry-run test of a workflow to verify it works before deploying. Call after credentials are verified.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
workflow_id: { type: 'string', description: 'Workflow ID to test' }
|
||||
},
|
||||
required: ['workflow_id']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'deploy_workflow',
|
||||
description: 'Activate a workflow and save it to SmallClaw\'s persistent registry. After this, the workflow is remembered forever and can be reused with execute_workflow_template(). Call only after test_workflow() passes.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
workflow_id: { type: 'string', description: 'Workflow ID to deploy' },
|
||||
name: { type: 'string', description: 'Short display name, e.g. "X Daily Posts"' },
|
||||
description: { type: 'string', description: 'What this workflow does' },
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['action', 'scheduled', 'background'],
|
||||
description: 'action=runs on demand, scheduled=runs on cron, background=always running'
|
||||
},
|
||||
action: { type: 'string', description: 'Primary verb: post, send, fetch, monitor, etc.' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: 'Search tags: ["social", "x", "daily"]' },
|
||||
required_inputs: { type: 'array', items: { type: 'string' }, description: 'Params required to execute, e.g. ["text"]' },
|
||||
optional_inputs: { type: 'array', items: { type: 'string' }, description: 'Optional params, e.g. ["hashtags"]' },
|
||||
credentials_required: { type: 'array', items: { type: 'string' }, description: 'Credential providers needed, e.g. ["X API"]' },
|
||||
cron_expression: { type: 'string', description: 'Cron schedule if type=scheduled, e.g. "0 9 * * *"' }
|
||||
},
|
||||
required: ['workflow_id', 'name', 'description', 'type', 'action']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'get_workflow_status',
|
||||
description: 'Get the current status and execution history of a deployed workflow.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
workflow_id: { type: 'string', description: 'Workflow ID to check' }
|
||||
},
|
||||
required: ['workflow_id']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'search_workflow_templates',
|
||||
description: `Search for existing workflows before creating new ones. \nALWAYS call this FIRST when a user asks to automate something. \nSearches SmallClaw's local registry (instant) then Agent Builder.\nIf results found, use execute_workflow_template() — do NOT call architect_workflow().`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query, e.g. "post to x", "send email", "daily digest"' },
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['action', 'scheduled', 'background'],
|
||||
description: 'Optional: filter by workflow type'
|
||||
},
|
||||
limit: { type: 'number', description: 'Max results to return (default: 5)' }
|
||||
},
|
||||
required: ['query']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'execute_workflow_template',
|
||||
description: 'Execute an existing workflow with runtime inputs. Use this to run any workflow that was previously deployed — no API calls to rebuild, instant execution.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
workflow_id: { type: 'string', description: 'Workflow ID from search_workflow_templates or deploy_workflow' },
|
||||
inputs: {
|
||||
type: 'object',
|
||||
description: 'Runtime inputs the workflow needs, e.g. { "text": "Hello world!", "topic": "AI" }'
|
||||
},
|
||||
trigger_phrase: {
|
||||
type: 'string',
|
||||
description: 'The phrase the user said that triggered this execution (helps SmallClaw learn patterns)'
|
||||
}
|
||||
},
|
||||
required: ['workflow_id']
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'create_node_subagent',
|
||||
description: 'Create a persistent SmallClaw writing subagent for an AI-authoring workflow node (tweet/email/slack/etc), then attach it to the node via subagent_config.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
node_type: { type: 'string', description: 'Workflow node type, e.g. "social.twitter", "google.gmail", "notify.slack"' },
|
||||
node_action: { type: 'string', description: 'Node action/mode, e.g. "tweet", "send_email", "post_message"' },
|
||||
workflow_id: { type: 'string', description: 'Agent Builder workflow ID, e.g. wf_abc123' },
|
||||
workflow_name: { type: 'string', description: 'Human-readable workflow name used to derive subagent id/name' },
|
||||
onboarding_answers: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
purpose: { type: 'string', description: 'What this account/channel is about' },
|
||||
tone: { type: 'string', description: 'Desired writing tone/personality' },
|
||||
hard_rules: { type: 'string', description: 'Hard rules and prohibitions' },
|
||||
topics: { type: 'string', description: 'Comma/newline-separated topic rotation list' },
|
||||
post_frequency: { type: 'string', description: 'How often the node runs/posts' },
|
||||
extra: { type: 'string', description: 'Any extra custom instructions' },
|
||||
},
|
||||
required: ['purpose', 'tone', 'hard_rules', 'topics'],
|
||||
},
|
||||
},
|
||||
required: ['node_type', 'node_action', 'workflow_id', 'workflow_name', 'onboarding_answers'],
|
||||
},
|
||||
},
|
||||
}
|
||||
];
|
||||
|
||||
// ─── Tool Name Set ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const AGENT_BUILDER_TOOL_NAMES = new Set(
|
||||
AGENT_BUILDER_TOOL_DEFINITIONS.map(t => t.function.name)
|
||||
);
|
||||
|
||||
// ─── Dispatch ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function executeAgentBuilderTool(name: string, args: any): Promise<string> {
|
||||
switch (name) {
|
||||
case 'architect_workflow': return architect_workflow(args);
|
||||
case 'verify_workflow_credentials': return verify_workflow_credentials(args);
|
||||
case 'test_workflow': return test_workflow(args);
|
||||
case 'deploy_workflow': return deploy_workflow(args);
|
||||
case 'get_workflow_status': return get_workflow_status(args);
|
||||
case 'search_workflow_templates': return search_workflow_templates(args);
|
||||
case 'execute_workflow_template': return execute_workflow_template(args);
|
||||
case 'create_node_subagent': return create_node_subagent(args);
|
||||
default:
|
||||
return JSON.stringify({ success: false, error: `Unknown tool: ${name}` });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Registration (fixed return type bug) ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register all Agent Builder tools into SmallClaw's tool array.
|
||||
*
|
||||
* FIX: Now returns the definitions array so callers can spread it:
|
||||
* tools.push(...registerAgentBuilderTools(tools)) <- wrong pattern
|
||||
* registerAgentBuilderTools(tools) <- correct (mutates + returns)
|
||||
*
|
||||
* In server-v2.ts buildTools(), use Option B (cleaner):
|
||||
* registerAgentBuilderTools(tools);
|
||||
* return tools;
|
||||
*/
|
||||
export function registerAgentBuilderTools(toolsArray: any[]): any[] {
|
||||
for (const tool of AGENT_BUILDER_TOOL_DEFINITIONS) {
|
||||
if (!toolsArray.find((t: any) => t?.function?.name === tool.function.name)) {
|
||||
toolsArray.push(tool);
|
||||
}
|
||||
}
|
||||
return AGENT_BUILDER_TOOL_DEFINITIONS;
|
||||
}
|
||||
|
||||
// ─── Utility: inject workflow memory into system prompt ───────────────────────
|
||||
|
||||
/**
|
||||
* Returns a block to append to SmallClaw's system prompt.
|
||||
* Tells the LLM what workflows already exist so it doesn't try to recreate them.
|
||||
*
|
||||
* Usage in server-v2.ts:
|
||||
* const systemPrompt = BASE_SYSTEM_PROMPT + '\n\n' + getWorkflowContextBlock();
|
||||
*/
|
||||
export function getWorkflowContextBlock(): string {
|
||||
const stats = workflowStore.getStats();
|
||||
if (stats.total_workflows === 0) return '';
|
||||
|
||||
const summary = workflowStore.toLLMSummary();
|
||||
return [
|
||||
`[WORKFLOWS] ${stats.total_workflows} registered (${stats.active_workflows} active). Do not recreate — search first.`,
|
||||
'',
|
||||
summary,
|
||||
].join('\n');
|
||||
}
|
||||
+46
-95
@@ -151,12 +151,6 @@ import { synthesizeSpeech, isTTSAvailable } from '../tools/tts.js';
|
||||
import { raceWithWatchdog, PreemptState } from './preempt-watchdog';
|
||||
import { detectGpu, logGpuStatus } from './gpu-detector';
|
||||
import { internalAgentTaskRouter } from './internal-agent-task';
|
||||
import {
|
||||
registerAgentBuilderTools,
|
||||
executeAgentBuilderTool,
|
||||
AGENT_BUILDER_TOOL_NAMES,
|
||||
getWorkflowContextBlock,
|
||||
} from './agent-builder-integration';
|
||||
|
||||
|
||||
// ─── Server log ring buffer ────────────────────────────────────────────────────
|
||||
@@ -1209,8 +1203,7 @@ function detectToolCategories(text: string, sessionId?: string): Set<string> {
|
||||
const SCHOLAR = ['openalex', 'semantic scholar', 'openalex_search', 'semantic_search', 'google scholar', 'semanticscholar', 'paper search', '논문 검색', '학술 검색', '학술논문', 'citation', '인용', 'arxiv', 'preprint'];
|
||||
// 'why' removed — matches casual questions; keep specific error/debug terms
|
||||
const DEBUG = ['error', 'failed', 'how does', 'architecture', 'debug', 'caused', 'broke', 'not working', 'explain how', 'whats wrong', "what's wrong"];
|
||||
const WORKFLOW = ['workflow', 'agent builder', 'architect_workflow', 'deploy workflow', 'workflow template', 'build workflow'];
|
||||
const PHOTO = ['사진', '이미지', 'photo', 'image', 'picture', 'search_images', 'find photo', 'find image', 'show photo', 'show image', '이미지 편집', '사진 편집', '이미지 수정', '말풍선', '워터마크', '배경 제거', '크롭', '리사이즈', '애니메이션 스타일', '유화', '수채화', '스케치', '만화체', '그림체', '그림으로', '스타일 변환', 'stylize', 'anime style', 'cartoon style'];
|
||||
const PHOTO =['사진', '이미지', 'photo', 'image', 'picture', 'search_images', 'find photo', 'find image', 'show photo', 'show image', '이미지 편집', '사진 편집', '이미지 수정', '말풍선', '워터마크', '배경 제거', '크롭', '리사이즈', '애니메이션 스타일', '유화', '수채화', '스케치', '만화체', '그림체', '그림으로', '스타일 변환', 'stylize', 'anime style', 'cartoon style'];
|
||||
if (WEB.some(k => lower.includes(k))) cats.add('web');
|
||||
if (BROWSER.some(k => lower.includes(k))) cats.add('browser');
|
||||
if (DESKTOP.some(k => lower.includes(k))) cats.add('desktop');
|
||||
@@ -1237,7 +1230,6 @@ function detectToolCategories(text: string, sessionId?: string): Set<string> {
|
||||
const SPAWN = ['논문 리서치', '논문 분석', '논문 요약', '여러 논문', '다수 논문', 'pubmed_researcher', 'spawn_agent'];
|
||||
if (SPAWN.some(k => lower.includes(k))) cats.add('spawn');
|
||||
if (DEBUG.some(k => lower.includes(k))) cats.add('debug');
|
||||
if (WORKFLOW.some(k => lower.includes(k))) cats.add('workflow');
|
||||
if (PHOTO.some(k => lower.includes(k))) cats.add('photo');
|
||||
const WEATHER = ['weather', 'forecast', 'temperature', 'humidity', '날씨', '기온', '기상', '예보', '날씨 알려', '오늘 날씨', '내일 날씨', '이번 주 날씨', '미세먼지', '대기질', '황사', 'pm2.5', 'pm10', '대기오염', '기상청', '초단기', '단기예보', 'weather_search', 'weather_kma', 'weather_airkorea', 'weather_openmeteo', 'weather_airpollution'];
|
||||
if (WEATHER.some(k => lower.includes(k))) cats.add('weather');
|
||||
@@ -1315,8 +1307,6 @@ PDF→PPTX WORKFLOW — MANDATORY. When source is a PDF, ALL steps below are REQ
|
||||
6. In slide specs, use image_url = EXACT workspace-relative path. Never strip folders, never use image_path.
|
||||
7. ONLY use figure_* and filtered img-* files. Raw unfiltered img-* files are FORBIDDEN.`,
|
||||
|
||||
workflow: `WORKFLOW TOOLS: ALWAYS call search_workflow_templates(intent) FIRST before creating anything — reuse existing workflows. If no match: (1) architect_workflow(desc) → (2) verify_workflow_credentials(wf_id) if creds needed → wait for user → (3) test_workflow(wf_id) → (4) deploy_workflow(wf_id, name, ...). Never call architect_workflow if search returns a match. Always relay tool user_message fields verbatim to the user.`,
|
||||
|
||||
photo: `PHOTO SEARCH: search_images(query, count?) → searches Pexels + Unsplash and returns embeddable image URLs. Display results as markdown images in your response. Use when the user asks to find, show, or search for photos or images.
|
||||
|
||||
IMAGE EDIT TOOL: image_edit(path, operation, ...params) → 이미지 편집 및 변환.
|
||||
@@ -1682,6 +1672,20 @@ function buildTools() {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'move_file',
|
||||
description: 'Move or rename a file. Works in both server workspace and client-local mode.',
|
||||
parameters: {
|
||||
type: 'object', required: ['source', 'destination'],
|
||||
properties: {
|
||||
source: { type: 'string', description: 'Current file path (relative to project root)' },
|
||||
destination: { type: 'string', description: 'New file path (relative to project root). Parent directories are created automatically.' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
@@ -2682,7 +2686,6 @@ function buildTools() {
|
||||
},
|
||||
);
|
||||
|
||||
registerAgentBuilderTools(toolDefs);
|
||||
_toolsCache = toolDefs;
|
||||
}
|
||||
|
||||
@@ -3178,6 +3181,7 @@ async function executeTool(name: string, args: any, workspacePath: string, sessi
|
||||
case 'delete_lines': return { name, args, result: `Updated ${fname} (deleted lines ${args.start_line}-${args.end_line}).`, error: false };
|
||||
case 'find_replace': return { name, args, result: `Updated ${fname}.`, error: false };
|
||||
case 'delete_file': return { name, args, result: `Deleted ${fname}.`, error: false };
|
||||
case 'move_file': return { name, args, result: `${args.source || fname} → ${args.destination || '(destination)'}`, error: false };
|
||||
case 'read_file': return { name, args, result: `"${fname}"의 내용은 이미 대화 컨텍스트에 줄 번호와 함께 포함되어 있습니다. 컨텍스트의 해당 내용을 그대로 사용하세요. 컨텍스트에 없다면 사용자에게 에디터에서 파일을 열어달라고 요청하세요.`, error: false };
|
||||
case 'list_files':
|
||||
case 'search_files': return { name, args, result: `프로젝트 파일과 내용은 이미 대화 컨텍스트의 [파일: ...] 블록에 포함되어 있습니다. 별도 조회 없이 컨텍스트를 참고하세요.`, error: false };
|
||||
@@ -3318,8 +3322,12 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
|
||||
return { name, args, result: `File "${filename}" is a binary file (${ext}, ${(stats.size / 1024).toFixed(1)} KB) and cannot be read as text. Use other tools or download it via ${filename}.`, error: true };
|
||||
}
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
const numbered = content.split('\n').map((line, i) => `${i + 1}: ${line}`).join('\n');
|
||||
return { name, args, result: `${filename} (${content.split('\n').length} lines):\n${numbered}`, error: false };
|
||||
const MAX_READ_CHARS = 200_000; // ~200KB — prevents single read_file from flooding context
|
||||
const truncated = content.length > MAX_READ_CHARS;
|
||||
const displayContent = truncated ? content.slice(0, MAX_READ_CHARS) : content;
|
||||
const numbered = displayContent.split('\n').map((line, i) => `${i + 1}: ${line}`).join('\n');
|
||||
const truncNote = truncated ? `\n…[파일이 너무 큼 — 전체 ${Math.round(content.length / 1024)}KB 중 앞 ${Math.round(MAX_READ_CHARS / 1024)}KB만 표시]` : '';
|
||||
return { name, args, result: `${filename} (${content.split('\n').length} lines):\n${numbered}${truncNote}`, error: false };
|
||||
}
|
||||
|
||||
case 'create_file': {
|
||||
@@ -3512,6 +3520,19 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
|
||||
return { name, args, result: `${filename} deleted`, error: false };
|
||||
}
|
||||
|
||||
case 'move_file': {
|
||||
const srcRaw = resolveCodeFilename(args.source || args.from, workspacePath);
|
||||
const dstRaw = resolveCodeFilename(args.destination || args.to, workspacePath);
|
||||
const srcPath = path.join(workspacePath, srcRaw);
|
||||
const dstPath = path.join(workspacePath, dstRaw);
|
||||
if (!isPathInsideDir(workspacePath, srcPath) || !isPathInsideDir(workspacePath, dstPath))
|
||||
return { name, args, result: 'Access denied: path escapes workspace', error: true };
|
||||
if (!fs.existsSync(srcPath)) return { name, args, result: `"${srcRaw}" not found`, error: true };
|
||||
fs.mkdirSync(path.dirname(dstPath), { recursive: true });
|
||||
fs.renameSync(srcPath, dstPath);
|
||||
return { name, args, result: `${srcRaw} → ${dstRaw}`, error: false };
|
||||
}
|
||||
|
||||
case 'web_search': {
|
||||
const raw = await webSearch(args.query || '');
|
||||
const result = await validateLinksInText(raw);
|
||||
@@ -4330,17 +4351,6 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
|
||||
return { name, args, result: `Note saved [${noteTag}] (${noteContent.length} chars) → intraday-notes`, error: false };
|
||||
}
|
||||
|
||||
case 'architect_workflow':
|
||||
case 'verify_workflow_credentials':
|
||||
case 'test_workflow':
|
||||
case 'deploy_workflow':
|
||||
case 'get_workflow_status':
|
||||
case 'search_workflow_templates':
|
||||
case 'execute_workflow_template':
|
||||
case 'create_node_subagent': {
|
||||
const result = await executeAgentBuilderTool(name, args);
|
||||
return { name, args, result, error: false };
|
||||
}
|
||||
|
||||
case 'create_presentation': {
|
||||
try {
|
||||
@@ -4980,7 +4990,8 @@ async function handleCodeChat(
|
||||
// useTools:false → plan/ask phase; pass empty tools so the model generates text only
|
||||
const tools = useTools ? buildTools().filter((t: any) => !codeAiBlockedTools.has(String(t?.function?.name || ''))) : [];
|
||||
|
||||
const systemPrompt = `You are an expert coding assistant — like Cline — embedded in the user's code editor. Current date: ${dateStr}, ${timeStr}.
|
||||
const _modelDisplayName = modelOverride ? modelOverride.replace(/:cloud$/, '') : 'AI';
|
||||
const systemPrompt = `You are an expert coding assistant embedded in the user's code editor. Your model name is "${_modelDisplayName}" — if asked who you are or what model you are, always answer truthfully with this name. Current date: ${dateStr}, ${timeStr}.
|
||||
|
||||
When making code changes, use tools to edit files — do NOT output code in markdown fenced blocks (\\\`\\\`\\\`). For questions, explanations, or analysis, respond directly in text without using tools. Never repeat or re-summarize what was already said. Start tool calls immediately without preamble.${isLocal ? `
|
||||
|
||||
@@ -4998,6 +5009,7 @@ AVAILABLE TOOLS:
|
||||
- insert_after(filename, after_line, content): Insert lines after a line number (0 = beginning).
|
||||
- delete_lines(filename, start_line, end_line): Delete lines by number.
|
||||
- find_replace(filename, find, replace): Find exact text and replace.
|
||||
- move_file(source, destination): Move or rename a file. Parent directories are created automatically. Works in both server workspace and client-local mode.
|
||||
- shell(command): Run terminal commands to test code.
|
||||
- python_eval(code): Run Python code.
|
||||
- web_search(query): Search the web.
|
||||
@@ -5373,8 +5385,10 @@ async function handleChat(
|
||||
recentToolCalls.push({ name: toolName, argsHash });
|
||||
if (recentToolCalls.length > 20) recentToolCalls.shift();
|
||||
const isSnapshotLoop = toolName === 'browser_snapshot';
|
||||
const blockAt = isSnapshotLoop ? snapshotLoopBlock : loopCriticalThreshold;
|
||||
const warnAt = isSnapshotLoop ? snapshotLoopWarn : loopWarningThreshold;
|
||||
// Pure read tools always return the same result for identical args — block after 1 repeat
|
||||
const isDeterministicRead = ['memory_browse', 'memory_read', 'read_file', 'list_files'].includes(toolName);
|
||||
const blockAt = isSnapshotLoop ? snapshotLoopBlock : isDeterministicRead ? 2 : loopCriticalThreshold;
|
||||
const warnAt = isSnapshotLoop ? snapshotLoopWarn : isDeterministicRead ? 2 : loopWarningThreshold;
|
||||
if (repeats >= blockAt) return { state: 'block', repeats };
|
||||
if (repeats >= warnAt) return { state: 'warn', repeats };
|
||||
return { state: 'ok', repeats };
|
||||
@@ -5606,79 +5620,16 @@ async function handleChat(
|
||||
return '';
|
||||
})();
|
||||
|
||||
const workflowCtx = getWorkflowContextBlock(); // empty string when 0 workflows
|
||||
// Code editor's Coder AI runs as an INDEPENDENT coding assistant: a dedicated
|
||||
// coding system prompt with NO main persona, NO user skills (meteorologist/
|
||||
// presenter…), and NO "keep responses short" rule (which otherwise made it
|
||||
// answer a "make space invaders" request with a single sentence and no code).
|
||||
const isCodeAiLocalSession = codeAiLocalSessions.has(String(sessionId));
|
||||
const codeAiSystemPrompt = `You are an expert coding assistant — like Cline — embedded in the user's code editor. Current date: ${dateStr}, ${timeStr}.
|
||||
|
||||
You MUST use tools to read and edit files. NEVER output code in markdown fenced blocks (\\\`\\\`\\\`). Every code change goes through a tool call. Analysis without action is a critical failure.${isCodeAiLocalSession ? `
|
||||
|
||||
CLIENT-LOCAL MODE: Files are stored in the user's local browser folder via the File System Access API — NOT on the server. The shell, run_command, and bash tools are NOT available in this mode and will return an error if called. After creating or editing files, tell the user the files are ready and they can open them in their browser. NEVER call shell/run_command/bash to open, run, or verify files in this mode.` : ''}
|
||||
|
||||
CONTEXT: The current file and all open project files are ALREADY provided in the conversation WITH line numbers (look for "[현재 파일: …]" and "[파일: …]" blocks). Do NOT call read_file for a file whose content is already shown — edit it directly. Only call read_file for a file that is NOT present in the context.
|
||||
|
||||
AVAILABLE TOOLS:
|
||||
- read_file(filename): Read file content WITH line numbers. Use ONLY for files not already shown in the context above.
|
||||
- list_files(directory): List files in a directory.
|
||||
- search_files(pattern): Search file contents with regex.
|
||||
- edit_file(filename, edits): PREFERRED edit tool. Uses SEARCH/REPLACE blocks — no line numbers needed.
|
||||
- create_file(filename, content): Create a new file. For existing files, use edit_file or replace_lines instead.
|
||||
- replace_lines(filename, start_line, end_line, new_content): Replace lines by number (1-based).
|
||||
- insert_after(filename, after_line, content): Insert lines after a line number (0 = beginning).
|
||||
- delete_lines(filename, start_line, end_line): Delete lines by number.
|
||||
- find_replace(filename, find, replace): Find exact text and replace.
|
||||
- shell(command): Run terminal commands to test code.
|
||||
- python_eval(code): Run Python code.
|
||||
- web_search(query): Search the web.
|
||||
|
||||
edit_file FORMAT (PREFERRED for all edits):
|
||||
------- SEARCH
|
||||
exact text to find (must match the file CHARACTER-BY-CHARACTER including indentation and whitespace)
|
||||
=======
|
||||
replacement text (leave empty between ======= and +++++++ to delete)
|
||||
+++++++ REPLACE
|
||||
|
||||
Multiple edits: list SEARCH/REPLACE blocks in file order. Each SEARCH text must match EXACTLY — copy it verbatim from read_file output. Do NOT modify the marker format.
|
||||
|
||||
TOOL USE RULES:
|
||||
- Use ONE tool per message. Wait for the result before proceeding.
|
||||
- The current/open files are already in context with line numbers — edit them directly without read_file. Only read_file for files NOT shown.
|
||||
- Default to edit_file for most changes. Use create_file only for new files.
|
||||
- After editing: briefly state what you changed (1 line). No extended explanations.
|
||||
- NEVER output code in markdown fences (\\\`\\\`\\\`). ALL code changes via tool calls.
|
||||
- NEVER start your message with "Great", "Certainly", "Okay", "Sure", or similar filler.
|
||||
- Do not ask for more information than necessary. Use tools to find answers.
|
||||
|
||||
WORKFLOW:
|
||||
1. READ: Understand the current code from the context (already provided). read_file only for files not shown.
|
||||
2. EDIT: Use edit_file (preferred) or replace_lines to make changes.
|
||||
3. VERIFY: Use shell to run the code if applicable.
|
||||
|
||||
DEBUGGING (when the user shows an error):
|
||||
1. Read the FULL error message — the exact file/line is there.
|
||||
2. Inspect the file at the error line (it is already in context with line numbers; read_file only if not shown).
|
||||
3. Use edit_file to fix ONLY the lines that caused the error.
|
||||
4. Use shell to verify the fix works.
|
||||
5. If a fix doesn't work, re-read the file and try a different approach. Never repeat the same failed fix.
|
||||
|
||||
CODE QUALITY:
|
||||
- Write complete, runnable code. No placeholder TODO comments, no stub functions.
|
||||
- Stay in the same language/framework as the existing code.
|
||||
- Never run package install commands (pip, npm, apt-get).
|
||||
- If a tool call fails, re-read the file and retry with correct content.`;
|
||||
const messages: any[] = [
|
||||
{
|
||||
role: 'system',
|
||||
content: isCodeAiSession ? codeAiSystemPrompt : isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw 🦞, a local AI assistant.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep responses SHORT (1-2 sentences). Don't think out loud. Act and report. Greet naturally without tools.
|
||||
content: isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw 🦞, a local AI assistant.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep responses SHORT (1-2 sentences). Don't think out loud. Act and report. Greet naturally without tools.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.
|
||||
IMAGE EDITING RULE: NEVER call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user's message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.
|
||||
BROWSER RULE: NEVER call browser_open, browser_snapshot, browser_click, browser_fill, browser_scroll, or any browser_* tool unless the user EXPLICITLY asks to use the browser (e.g. "브라우저로 열어줘", "Chrome으로 봐줘", "사이트 직접 들어가봐"). "열어줘" or "보여줘" alone is NOT a browser request — answer from knowledge, use web_fetch/web_search, or output the relevant URL/embed. Pasting a URL or asking a question is also NOT a browser request.
|
||||
CODE OUTPUT: When writing code in a fenced code block, start with a filename comment on line 1: \`# filename: snake_game.py\` (Python), \`// filename: app.js\` (JS/C), \`<!-- filename: index.html -->\` (HTML). Never repeat code already written in this conversation. For modifications to existing files, use replace_lines or insert_after (not create_file — it only works for NEW files). All code changes are presented as diffs for the user to review before being applied. Write code directly — do not ask for permission.
|
||||
PACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.
|
||||
OUTPUT FORMAT: When presenting 3+ items (news articles, emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. Example: news → table with columns 제목|요약|출처.${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsManager.buildPromptContextForUser(username ? getUserWorkspace(username) : null, 16000, message)}${workflowCtx ? '\n\n' + workflowCtx : ''}`,
|
||||
OUTPUT FORMAT: When presenting 3+ items (news articles, emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. Example: news → table with columns 제목|요약|출처.${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsManager.buildPromptContextForUser(username ? getUserWorkspace(username) : null, 16000, message)}`,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -11290,7 +11241,7 @@ app.post('/api/chat', async (req, res) => {
|
||||
|
||||
// Record whether this code-editor turn uses the browser's local folder. The
|
||||
// server then skips disk file-tool execution (client is source of truth).
|
||||
if (/^code_ai_/.test(String(sessionId || ''))) {
|
||||
if (/^(code_ai_|proj-gen-|proj-plan-)/.test(String(sessionId || ''))) {
|
||||
if (codeAiLocal) codeAiLocalSessions.add(String(sessionId));
|
||||
else codeAiLocalSessions.delete(String(sessionId));
|
||||
}
|
||||
@@ -11419,7 +11370,7 @@ app.post('/api/chat', async (req, res) => {
|
||||
const isCodeEditorSession = /^(code_ai_|proj-plan-|proj-gen-)/.test(String(sessionId));
|
||||
const histOverride = (isCodeEditorSession && Array.isArray(clientHistory)) ? clientHistory : undefined;
|
||||
// Code editor chat runs on its own clean tool loop — no multi-agent orchestration.
|
||||
const isCodeAiChat = /^code_ai_/.test(String(sessionId));
|
||||
const isCodeAiChat = /^(code_ai_|proj-gen-|proj-plan-)/.test(String(sessionId));
|
||||
// Client sends useTools:false for plan/ask phase — honour it so the model doesn't
|
||||
// loop on list_files when it should just generate a text response.
|
||||
const codeAiUseTools = useTools !== false;
|
||||
|
||||
@@ -1,458 +0,0 @@
|
||||
/**
|
||||
* WorkflowStore — Persistent SmallClaw-side workflow registry
|
||||
*
|
||||
* This is the SmallClaw brain for workflow memory. Every workflow
|
||||
* deployed through Agent Builder gets saved here permanently, keyed
|
||||
* by its workflow_id. On next request, SmallClaw checks this store
|
||||
* BEFORE calling architect_workflow(), preventing duplicates and
|
||||
* saving API calls / build time.
|
||||
*
|
||||
* Storage: .smallclaw/workflows.json (same pattern as CronScheduler jobs)
|
||||
* Format: JSON file, human-readable, persists across restarts
|
||||
*
|
||||
* File location: src/gateway/workflow-store.ts
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface StoredWorkflow {
|
||||
/** Permanent ID from Agent Builder database — the canonical reference */
|
||||
workflow_id: string;
|
||||
|
||||
/**
|
||||
* Registry template ID (reg_xxxxxx) from Agent Builder's WorkflowRegistry.
|
||||
* This is what registry/execute expects as template_id.
|
||||
* Populated after deploy_workflow() calls registry/register.
|
||||
*/
|
||||
template_id?: string;
|
||||
|
||||
/** Human-readable name, e.g. "X Daily Posts" */
|
||||
name: string;
|
||||
|
||||
/** What this workflow does in plain English */
|
||||
description: string;
|
||||
|
||||
/**
|
||||
* Type of workflow:
|
||||
* - "action" → runs on-demand (post now, send email now)
|
||||
* - "scheduled" → runs on cron (daily posts, weekly digest)
|
||||
* - "background"→ runs continuously (monitor, listen for events)
|
||||
*/
|
||||
type: 'action' | 'scheduled' | 'background';
|
||||
|
||||
/** Primary verb: post, send, fetch, schedule, monitor, etc. */
|
||||
action: string;
|
||||
|
||||
/**
|
||||
* Searchable tags. Used by SmallClaw to match user intent.
|
||||
* e.g. ["social", "x", "twitter", "post", "quick"]
|
||||
*/
|
||||
tags: string[];
|
||||
|
||||
/** Inputs the workflow REQUIRES to run */
|
||||
required_inputs: string[];
|
||||
|
||||
/** Inputs the workflow ACCEPTS but doesn't require */
|
||||
optional_inputs: string[];
|
||||
|
||||
/** Current state in Agent Builder */
|
||||
status: 'active' | 'inactive' | 'error';
|
||||
|
||||
/** Cron expression if scheduled, e.g. "0 9 * * *" */
|
||||
cron_expression?: string;
|
||||
|
||||
/** Number of times this workflow has been executed via SmallClaw */
|
||||
execution_count: number;
|
||||
|
||||
/** ISO timestamp of last execution */
|
||||
last_executed?: string;
|
||||
|
||||
/** ISO timestamp when this workflow was first deployed */
|
||||
deployed_at: string;
|
||||
|
||||
/** ISO timestamp of last status check */
|
||||
last_verified?: string;
|
||||
|
||||
/**
|
||||
* Credential providers this workflow needs, e.g. ["X API", "OpenAI"]
|
||||
* Populated from Agent Builder's credentials_needed response
|
||||
*/
|
||||
credentials_required: string[];
|
||||
|
||||
/** True once all credentials are confirmed present */
|
||||
credentials_verified: boolean;
|
||||
|
||||
/**
|
||||
* Short phrases that should trigger this workflow.
|
||||
* SmallClaw learns these over time.
|
||||
* e.g. ["post to x", "tweet about", "x post"]
|
||||
*/
|
||||
trigger_phrases: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowStoreData {
|
||||
/** Schema version for future migrations */
|
||||
version: number;
|
||||
|
||||
/** ISO timestamp of last write */
|
||||
last_updated: string;
|
||||
|
||||
/** Total workflows ever registered */
|
||||
total_registered: number;
|
||||
|
||||
/** Total executions across all workflows */
|
||||
total_executions: number;
|
||||
|
||||
/** The actual registry — keyed by workflow_id for O(1) lookup */
|
||||
workflows: Record<string, StoredWorkflow>;
|
||||
}
|
||||
|
||||
// ─── Constants ───────────────────────────────────────────────────────────────
|
||||
|
||||
const STORE_VERSION = 1;
|
||||
|
||||
// Default store path — respects SMALLCLAW_DATA_DIR env var if set
|
||||
function getStorePath(): string {
|
||||
const dataDir = process.env.SMALLCLAW_DATA_DIR
|
||||
|| path.join(os.homedir(), '.smallclaw');
|
||||
|
||||
return path.join(dataDir, 'workflows.json');
|
||||
}
|
||||
|
||||
// ─── WorkflowStore Class ─────────────────────────────────────────────────────
|
||||
|
||||
export class WorkflowStore {
|
||||
private storePath: string;
|
||||
private data: WorkflowStoreData;
|
||||
private dirty: boolean = false;
|
||||
|
||||
constructor(storePath?: string) {
|
||||
this.storePath = storePath || getStorePath();
|
||||
this.data = this.load();
|
||||
}
|
||||
|
||||
// ── Persistence ────────────────────────────────────────────────────────────
|
||||
|
||||
private load(): WorkflowStoreData {
|
||||
try {
|
||||
if (fs.existsSync(this.storePath)) {
|
||||
const raw = fs.readFileSync(this.storePath, 'utf-8');
|
||||
const parsed = JSON.parse(raw) as WorkflowStoreData;
|
||||
console.log(`[WorkflowStore] Loaded ${Object.keys(parsed.workflows).length} workflows from ${this.storePath}`);
|
||||
return parsed;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[WorkflowStore] Failed to load store, starting fresh:', err);
|
||||
}
|
||||
|
||||
return this.emptyStore();
|
||||
}
|
||||
|
||||
private emptyStore(): WorkflowStoreData {
|
||||
return {
|
||||
version: STORE_VERSION,
|
||||
last_updated: new Date().toISOString(),
|
||||
total_registered: 0,
|
||||
total_executions: 0,
|
||||
workflows: {}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the store to disk. Called automatically after mutations.
|
||||
* Creates the directory if it doesn't exist.
|
||||
*/
|
||||
save(): void {
|
||||
try {
|
||||
const dir = path.dirname(this.storePath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
this.data.last_updated = new Date().toISOString();
|
||||
fs.writeFileSync(this.storePath, JSON.stringify(this.data, null, 2), 'utf-8');
|
||||
this.dirty = false;
|
||||
console.log(`[WorkflowStore] Saved ${Object.keys(this.data.workflows).length} workflows to disk`);
|
||||
} catch (err) {
|
||||
console.error('[WorkflowStore] Failed to save store:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Write Operations ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register a newly deployed workflow.
|
||||
* Called automatically by deploy_workflow() tool after successful deploy.
|
||||
*
|
||||
* @returns The stored workflow entry
|
||||
*/
|
||||
register(workflow: Omit<StoredWorkflow, 'execution_count' | 'deployed_at' | 'credentials_verified' | 'trigger_phrases'> & Partial<Pick<StoredWorkflow, 'execution_count' | 'deployed_at' | 'credentials_verified' | 'trigger_phrases'>>): StoredWorkflow {
|
||||
const existing = this.data.workflows[workflow.workflow_id];
|
||||
|
||||
const entry: StoredWorkflow = {
|
||||
...workflow,
|
||||
execution_count: existing?.execution_count ?? 0,
|
||||
deployed_at: existing?.deployed_at ?? new Date().toISOString(),
|
||||
credentials_verified: workflow.credentials_verified ?? false,
|
||||
trigger_phrases: workflow.trigger_phrases ?? existing?.trigger_phrases ?? [],
|
||||
};
|
||||
|
||||
this.data.workflows[workflow.workflow_id] = entry;
|
||||
|
||||
if (!existing) {
|
||||
this.data.total_registered++;
|
||||
}
|
||||
|
||||
this.save();
|
||||
console.log(`[WorkflowStore] Registered workflow: ${workflow.workflow_id} — "${workflow.name}"`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a workflow as executed. Increments counters and updates last_executed.
|
||||
*/
|
||||
recordExecution(workflowId: string): void {
|
||||
const wf = this.data.workflows[workflowId];
|
||||
if (!wf) {
|
||||
console.warn(`[WorkflowStore] recordExecution: unknown workflow ${workflowId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
wf.execution_count++;
|
||||
wf.last_executed = new Date().toISOString();
|
||||
this.data.total_executions++;
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a workflow's status (active/inactive/error).
|
||||
*/
|
||||
updateStatus(workflowId: string, status: StoredWorkflow['status']): void {
|
||||
const wf = this.data.workflows[workflowId];
|
||||
if (!wf) return;
|
||||
wf.status = status;
|
||||
wf.last_verified = new Date().toISOString();
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark credentials as verified for a workflow.
|
||||
*/
|
||||
markCredentialsVerified(workflowId: string): void {
|
||||
const wf = this.data.workflows[workflowId];
|
||||
if (!wf) return;
|
||||
wf.credentials_verified = true;
|
||||
wf.last_verified = new Date().toISOString();
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add trigger phrases that the LLM learned map to this workflow.
|
||||
* Deduplicates automatically.
|
||||
*/
|
||||
addTriggerPhrases(workflowId: string, phrases: string[]): void {
|
||||
const wf = this.data.workflows[workflowId];
|
||||
if (!wf) return;
|
||||
|
||||
const existing = new Set(wf.trigger_phrases.map(p => p.toLowerCase()));
|
||||
const newPhrases = phrases
|
||||
.map(p => p.toLowerCase().trim())
|
||||
.filter(p => p.length > 0 && !existing.has(p));
|
||||
|
||||
if (newPhrases.length > 0) {
|
||||
wf.trigger_phrases.push(...newPhrases);
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a workflow from the store (e.g. user deleted it from Agent Builder)
|
||||
*/
|
||||
remove(workflowId: string): boolean {
|
||||
if (!this.data.workflows[workflowId]) return false;
|
||||
delete this.data.workflows[workflowId];
|
||||
this.save();
|
||||
console.log(`[WorkflowStore] Removed workflow: ${workflowId}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Read Operations ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get a workflow by its Agent Builder ID.
|
||||
*/
|
||||
get(workflowId: string): StoredWorkflow | null {
|
||||
return this.data.workflows[workflowId] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all stored workflows as an array.
|
||||
*/
|
||||
getAll(): StoredWorkflow[] {
|
||||
return Object.values(this.data.workflows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if SmallClaw has a workflow registered for this ID.
|
||||
*/
|
||||
has(workflowId: string): boolean {
|
||||
return workflowId in this.data.workflows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get workflows filtered by type.
|
||||
*/
|
||||
getByType(type: StoredWorkflow['type']): StoredWorkflow[] {
|
||||
return this.getAll().filter(wf => wf.type === type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active workflows.
|
||||
*/
|
||||
getActive(): StoredWorkflow[] {
|
||||
return this.getAll().filter(wf => wf.status === 'active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-text + tag search. Returns ranked results.
|
||||
*
|
||||
* Scoring (higher = better match):
|
||||
* +3 exact tag match
|
||||
* +2 name contains query word
|
||||
* +2 trigger phrase match
|
||||
* +1 description contains query word
|
||||
* +1 action matches
|
||||
*
|
||||
* Filters:
|
||||
* - type: restrict to action | scheduled | background
|
||||
* - activeOnly: only return active workflows (default: true)
|
||||
*/
|
||||
search(query: string, options: {
|
||||
type?: StoredWorkflow['type'];
|
||||
activeOnly?: boolean;
|
||||
limit?: number;
|
||||
} = {}): StoredWorkflow[] {
|
||||
const { type, activeOnly = true, limit = 10 } = options;
|
||||
|
||||
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
let candidates = this.getAll();
|
||||
|
||||
if (activeOnly) {
|
||||
candidates = candidates.filter(wf => wf.status === 'active');
|
||||
}
|
||||
|
||||
if (type) {
|
||||
candidates = candidates.filter(wf => wf.type === type);
|
||||
}
|
||||
|
||||
const scored = candidates.map(wf => {
|
||||
let score = 0;
|
||||
const name = wf.name.toLowerCase();
|
||||
const desc = wf.description.toLowerCase();
|
||||
const tagSet = new Set(wf.tags.map(t => t.toLowerCase()));
|
||||
|
||||
for (const word of words) {
|
||||
if (tagSet.has(word)) score += 3;
|
||||
if (name.includes(word)) score += 2;
|
||||
if (wf.trigger_phrases.some(p => p.toLowerCase().includes(word))) score += 2;
|
||||
if (desc.includes(word)) score += 1;
|
||||
if (wf.action.toLowerCase() === word) score += 1;
|
||||
}
|
||||
|
||||
// Boost by usage — popular workflows float up
|
||||
score += Math.min(wf.execution_count * 0.1, 2);
|
||||
|
||||
return { wf, score };
|
||||
});
|
||||
|
||||
return scored
|
||||
.filter(s => s.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, limit)
|
||||
.map(s => s.wf);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a workflow by matching trigger phrases exactly.
|
||||
* This is the fastest path — O(n) scan but short-circuits on first hit.
|
||||
*/
|
||||
findByTriggerPhrase(phrase: string): StoredWorkflow | null {
|
||||
const normalized = phrase.toLowerCase().trim();
|
||||
for (const wf of this.getAll()) {
|
||||
if (wf.status === 'active' && wf.trigger_phrases.some(p => p === normalized)) {
|
||||
return wf;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns store-level stats for debugging and display.
|
||||
*/
|
||||
getStats(): {
|
||||
total_workflows: number;
|
||||
active_workflows: number;
|
||||
total_executions: number;
|
||||
most_used: StoredWorkflow | null;
|
||||
last_updated: string;
|
||||
} {
|
||||
const all = this.getAll();
|
||||
const mostUsed = all.length > 0
|
||||
? all.reduce((a, b) => a.execution_count > b.execution_count ? a : b)
|
||||
: null;
|
||||
|
||||
return {
|
||||
total_workflows: all.length,
|
||||
active_workflows: all.filter(wf => wf.status === 'active').length,
|
||||
total_executions: this.data.total_executions,
|
||||
most_used: mostUsed,
|
||||
last_updated: this.data.last_updated
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable summary for LLM context injection.
|
||||
* SmallClaw can include this in its system prompt or tool descriptions.
|
||||
*/
|
||||
toLLMSummary(): string {
|
||||
const all = this.getActive();
|
||||
if (all.length === 0) {
|
||||
return 'No workflows registered yet. Use architect_workflow() to create the first one.';
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`## Registered Workflows (${all.length} active)\n`,
|
||||
'These workflows are already built and deployed. Use execute_workflow_template() to run them.',
|
||||
''
|
||||
];
|
||||
|
||||
for (const wf of all.sort((a, b) => b.execution_count - a.execution_count)) {
|
||||
lines.push(`### ${wf.name} [${wf.workflow_id}]`);
|
||||
lines.push(`- **Type:** ${wf.type} | **Action:** ${wf.action}`);
|
||||
lines.push(`- **Description:** ${wf.description}`);
|
||||
if (wf.required_inputs.length > 0) {
|
||||
lines.push(`- **Requires:** ${wf.required_inputs.join(', ')}`);
|
||||
}
|
||||
if (wf.optional_inputs.length > 0) {
|
||||
lines.push(`- **Optional:** ${wf.optional_inputs.join(', ')}`);
|
||||
}
|
||||
lines.push(`- **Tags:** ${wf.tags.join(', ')}`);
|
||||
lines.push(`- **Used:** ${wf.execution_count}x${wf.last_executed ? ` (last: ${new Date(wf.last_executed).toLocaleDateString()})` : ''}`);
|
||||
if (wf.trigger_phrases.length > 0) {
|
||||
lines.push(`- **Triggers:** "${wf.trigger_phrases.slice(0, 3).join('", "')}"`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Singleton ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Shared instance — import this everywhere instead of constructing new ones */
|
||||
export const workflowStore = new WorkflowStore();
|
||||
+3
-4
@@ -1227,10 +1227,9 @@ async function sendChat(queuedMessage = null) {
|
||||
currentTurnStartIndex = processLogEntries.length;
|
||||
addProcessEntry('user', message);
|
||||
|
||||
const historyForAPI = chatHistory.slice(-13, -1).map(m => ({
|
||||
role: m.role === 'user' ? 'user' : 'assistant',
|
||||
content: m.content
|
||||
}));
|
||||
// 서버(session.ts)가 세션 히스토리를 디스크에 영구 저장하므로 클라이언트 history 전송 불필요.
|
||||
// historyOverride를 보내면 서버 세션을 덮어써서 오히려 오작동 + 대용량 413 원인이 됨.
|
||||
const historyForAPI = undefined;
|
||||
|
||||
const allSteps = [];
|
||||
let finalReply = '';
|
||||
|
||||
@@ -211,6 +211,7 @@
|
||||
<div style="display:flex;gap:4px">
|
||||
<button id="code-local-btn" onclick="openLocalFolder()" title="로컬 폴더 열기" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:14px;line-height:1;padding:0 3px">🖥️</button>
|
||||
<button onclick="codeNewFile()" title="새 파일" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:16px;line-height:1;padding:0 3px">+</button>
|
||||
<button onclick="csbNewFolderRoot()" title="새 폴더" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:13px;line-height:1;padding:0 3px">📁</button>
|
||||
<button onclick="codeSbRefresh()" title="새로고침" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:13px;line-height:1;padding:0 3px">↺</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -448,5 +449,6 @@
|
||||
</div>
|
||||
|
||||
<script src="code.js?v=20260604s"></script>
|
||||
<div id="csb-ctx"></div>
|
||||
</body>
|
||||
</html>
|
||||
+462
-57
@@ -51,6 +51,32 @@ let monacoReady = false;
|
||||
let codeFiles = []; // [{id, name, content, language, model}]
|
||||
let activeCodeFileId = null;
|
||||
let codeAiHistory = [];
|
||||
// Strip code blocks from a history entry before storage.
|
||||
// File content is re-sent via contextMsg on every request, so repeating it in history
|
||||
// is pure waste and the main source of payload bloat. Keep only prose/summary text.
|
||||
function _histEntry(text) {
|
||||
if (!text) return text;
|
||||
const stripped = text
|
||||
.replace(/```[\s\S]*?```/g, '[코드]') // fenced code blocks → placeholder
|
||||
.replace(/<think>[\s\S]*?<\/think>/gi, '') // thinking tags
|
||||
.trim();
|
||||
return stripped.slice(0, 3000) || text.slice(0, 200); // prose cap; fallback if all stripped
|
||||
}
|
||||
|
||||
// Returns history entries (excluding last/current user msg) up to maxMsgs count AND maxBytes total
|
||||
function _histForAPI(hist, maxMsgs = 20, maxBytes = 150 * 1024) {
|
||||
if (hist.length <= 1) return [];
|
||||
const src = hist.slice(0, -1);
|
||||
let bytes = 0;
|
||||
const result = [];
|
||||
for (let i = src.length - 1; i >= 0 && result.length < maxMsgs; i--) {
|
||||
const size = (src[i].content || '').length;
|
||||
if (bytes + size > maxBytes) break;
|
||||
bytes += size;
|
||||
result.unshift({ role: src[i].role, content: src[i].content });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let codeAiAbort = null;
|
||||
let _codeAiAutoAccept = false; // when true: skip diff review, write files directly
|
||||
let _autoAcceptTurn = false; // true during an auto-accept execute phase → triggers completion message
|
||||
@@ -918,6 +944,7 @@ function closeCodeTermShell(id, ev) {
|
||||
else renderCodeTermTabs();
|
||||
}
|
||||
// Resize drag (top edge → pull up/down)
|
||||
document.addEventListener('click', e => { if (!e.target.closest('#csb-ctx')) csbCtxClose(); });
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const drag = document.getElementById('code-term-drag');
|
||||
const panel = document.getElementById('code-term-panel');
|
||||
@@ -1806,6 +1833,12 @@ function _projStartGenerate() {
|
||||
list.style.cssText = 'font-size:11px;font-family:monospace;';
|
||||
el.appendChild(list);
|
||||
el._list = list;
|
||||
|
||||
const live = document.createElement('pre');
|
||||
live.style.cssText = 'margin:4px 0 8px;padding:8px;background:var(--panel-2,#1e1e2e);border:1px solid var(--border,#333);border-radius:5px;font-size:10px;line-height:1.4;max-height:200px;overflow-y:auto;white-space:pre-wrap;word-break:break-all;color:var(--text,#ccc);display:none';
|
||||
el.appendChild(live);
|
||||
el._live = live;
|
||||
|
||||
codeAiScrollBottom();
|
||||
}
|
||||
|
||||
@@ -1860,8 +1893,12 @@ async function _projFileCreated(filename, content) {
|
||||
}
|
||||
}
|
||||
|
||||
// 에디터 탭에 추가
|
||||
_npAddTab(filename, content ?? '');
|
||||
// 에디터 탭에 추가 — client-local 모드에서는 프로젝트 slug를 제거한 베어 이름 사용
|
||||
// (_clientLoadProjectFiles와 일관성 유지: 탭은 항상 베어 상대 경로)
|
||||
const tabName = localDirHandle && filename.includes('/')
|
||||
? filename.slice(filename.indexOf('/') + 1)
|
||||
: filename;
|
||||
_npAddTab(tabName, content ?? '');
|
||||
renderCodeFileTabs();
|
||||
codeAiScrollBottom();
|
||||
}
|
||||
@@ -2009,14 +2046,70 @@ async function _projGenerate() {
|
||||
// 새 세션을 쓰면 "위 계획대로"가 뭔지 모델이 알 수 없음
|
||||
const genSessionId = _projSessionId || ('proj-gen-' + Date.now());
|
||||
let genChars = 0;
|
||||
let _liveAccum = '';
|
||||
let _liveFilePath = null;
|
||||
const earlyDone = new Set(); // raw paths processed incrementally during streaming
|
||||
const earlyPromises = []; // promises for early _projFileCreated calls — awaited before switchProject
|
||||
let _earlyRawSlug = null;
|
||||
const _earlyNormPath = rawPath => {
|
||||
if (!rawPath.includes('/')) return rawPath;
|
||||
const pfx = rawPath.split('/')[0];
|
||||
if (!_earlyRawSlug) _earlyRawSlug = pfx;
|
||||
const normPfx = activeProjectName
|
||||
|| pfx.toLowerCase().replace(/[^a-z0-9가-힣_-]/g, '-').replace(/^-+|-+$/g, '');
|
||||
return pfx !== normPfx ? rawPath.replace(pfx + '/', normPfx + '/') : rawPath;
|
||||
};
|
||||
const fullText = await _projStreamSSE(
|
||||
genSessionId, '위 계획대로 각 파일을 @@FILE / @@ENDFILE 형식으로 생성해주세요.',
|
||||
_PROJ_GEN_SYSTEM, _projHistory,
|
||||
chunk => {
|
||||
genChars += chunk.length;
|
||||
if (_projEl?._hdr) _projEl._hdr.textContent = `🤔 코드 생성 중... (${genChars}자)`;
|
||||
_liveAccum += chunk;
|
||||
|
||||
// @@FILE: 헤더 스캔 — 현재 작성 중인 파일 + 부분 내용 표시
|
||||
const hdrRe = /@@FILE:\s*(.+?)[ \t]*\r?\n/g;
|
||||
const hdrs = [];
|
||||
let hm2;
|
||||
while ((hm2 = hdrRe.exec(_liveAccum)) !== null)
|
||||
hdrs.push({ path: hm2[1].trim(), contentStart: hm2.index + hm2[0].length, idx: hm2.index });
|
||||
|
||||
if (!hdrs.length) {
|
||||
if (_projEl?._hdr) _projEl._hdr.textContent = `🤔 코드 생성 중... (${genChars}자)`;
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < hdrs.length; i++) {
|
||||
const { path, contentStart } = hdrs[i];
|
||||
if (earlyDone.has(path)) continue;
|
||||
const nextPos = i + 1 < hdrs.length ? hdrs[i + 1].idx : _liveAccum.length;
|
||||
const endIdx = _liveAccum.indexOf('@@ENDFILE', contentStart);
|
||||
const isComplete = endIdx !== -1 && endIdx < nextPos;
|
||||
|
||||
if (isComplete) {
|
||||
// 완성된 파일 즉시 체크리스트에 추가 (promise 추적 — switchProject 전 await)
|
||||
earlyDone.add(path);
|
||||
earlyPromises.push(_projFileCreated(_earlyNormPath(path), _liveAccum.slice(contentStart, endIdx)));
|
||||
} else if (i === hdrs.length - 1) {
|
||||
// 마지막 헤더 = 현재 스트리밍 중인 파일 — 부분 내용 표시
|
||||
const fname = path.split('/').pop();
|
||||
if (path !== _liveFilePath) {
|
||||
_liveFilePath = path;
|
||||
if (_projEl?._hdr) _projEl._hdr.textContent = `✏️ ${fname} 작성 중...`;
|
||||
}
|
||||
const partial = _liveAccum.slice(contentStart);
|
||||
if (_projEl?._live) {
|
||||
_projEl._live.style.display = 'block';
|
||||
_projEl._live.textContent = partial;
|
||||
_projEl._live.scrollTop = _projEl._live.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 마지막 파일도 완료되면 라이브 프리뷰 숨김
|
||||
if (earlyDone.has(hdrs[hdrs.length - 1].path) && _projEl?._live)
|
||||
_projEl._live.style.display = 'none';
|
||||
}
|
||||
);
|
||||
if (_projEl?._live) _projEl._live.style.display = 'none';
|
||||
|
||||
// @@FILE / @@ENDFILE 파싱 — @@ENDFILE 없는 마지막 블록도 허용
|
||||
const files = [];
|
||||
@@ -2053,21 +2146,33 @@ async function _projGenerate() {
|
||||
// AI가 출력한 경로의 slug prefix → 정규화된 slug로 교체
|
||||
const normalizedFiles = files.map(f => ({
|
||||
...f,
|
||||
rawPath: f.path, // earlyDone 체크용 원본 경로
|
||||
path: rawSlug && rawSlug !== slug ? f.path.replace(rawSlug + '/', slug + '/') : f.path,
|
||||
}));
|
||||
|
||||
for (const f of normalizedFiles) {
|
||||
if (earlyDone.has(f.rawPath)) continue; // 스트리밍 중 이미 처리됨
|
||||
if (f.path && f.content !== undefined)
|
||||
await _projFileCreated(f.path, String(f.content));
|
||||
}
|
||||
|
||||
// earlyDone 파일의 디스크 쓰기가 모두 완료된 후 프로젝트 전환
|
||||
// (_clientLoadProjectFiles가 디스크에서 파일을 읽으므로 write 완료 전에 전환하면 탭이 비어 컨텍스트 없음)
|
||||
await Promise.allSettled(earlyPromises);
|
||||
|
||||
const mainPath = _npMainFile(
|
||||
normalizedFiles.map(f => ({ path: slug ? f.path.replace(slug + '/', '') : f.path })),
|
||||
slug
|
||||
);
|
||||
if (mainPath) switchCodeFile(codeFiles.find(f => f.name === mainPath)?.id);
|
||||
// 새 프로젝트로 자동 전환 (AI 세션 분리)
|
||||
if (slug && slug !== activeProjectName) switchProject(slug);
|
||||
if (slug && slug !== activeProjectName) {
|
||||
switchProject(slug);
|
||||
// switchProject 내부의 _clientLoadProjectFiles()는 await 없이 호출되므로
|
||||
// codeFiles가 비어있는 상태로 _projGenerate가 반환될 수 있다.
|
||||
// 여기서 명시적으로 await해서 다음 메시지 전송 시 파일이 로드된 상태를 보장한다.
|
||||
if (localDirHandle) await _clientLoadProjectFiles();
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.name !== 'AbortError')
|
||||
codeAiAppend('system', '❌ 프로젝트 생성 오류: ' + (e.message || e));
|
||||
@@ -2189,8 +2294,19 @@ async function _codeAiSendImpl() {
|
||||
// 1. All other open tabs (no project prefix required — covers both prefixed and bare filenames)
|
||||
for (const f of codeFiles) {
|
||||
if (f.name === currentFileName) continue;
|
||||
// If activeProjectName set, only include files from same project
|
||||
if (activeProjectName && !f.name.startsWith(activeProjectName + '/') && f.name.includes('/')) continue;
|
||||
// If activeProjectName set, only include files from same project.
|
||||
// 로컬 모드(localDirHandle 있음)에서는 탭이 베어 경로("src/main.py")로 저장될 수 있으므로
|
||||
// 첫 세그먼트가 알려진 다른 프로젝트 이름인 경우에만 제외한다.
|
||||
if (activeProjectName && f.name.includes('/')) {
|
||||
const isCurrentProjPrefix = f.name.startsWith(activeProjectName + '/');
|
||||
if (!isCurrentProjPrefix) {
|
||||
if (!localDirHandle) { continue; } // 서버 모드: 프로젝트 prefix 없으면 다른 프로젝트
|
||||
// 로컬 모드: 첫 세그먼트가 알려진 다른 프로젝트 이름이면 제외
|
||||
const firstSeg = f.name.split('/')[0];
|
||||
const knownProjects = _knownProjectsGet();
|
||||
if (knownProjects.includes(firstSeg) && firstSeg !== activeProjectName) continue;
|
||||
}
|
||||
}
|
||||
if (!isCodeFile(f.name)) continue; // skip .md, .txt etc.
|
||||
const bare = f.name.split('/').pop() || '';
|
||||
if (SKIP_NAMES.test(bare)) continue;
|
||||
@@ -2204,7 +2320,12 @@ async function _codeAiSendImpl() {
|
||||
if (localDirHandle && activeProjectName && otherFilesCtx.length < CTX_TOTAL_BYTES) {
|
||||
try {
|
||||
const allFiles = await localListFiles(localDirHandle, '');
|
||||
const projFiles = allFiles.filter(f => f.startsWith(activeProjectName + '/') && !seen.has(f) && f !== currentFileName && isCodeFile(f) && !SKIP_NAMES.test(f.split('/').pop() || ''));
|
||||
const projFiles = allFiles.filter(f => {
|
||||
if (!f.startsWith(activeProjectName + '/')) return false;
|
||||
const bare = f.slice(activeProjectName.length + 1);
|
||||
// seen에는 베어 이름만 있으므로 양쪽 모두 체크해 중복 포함 방지
|
||||
return !seen.has(f) && !seen.has(bare) && f !== currentFileName && isCodeFile(f) && !SKIP_NAMES.test(f.split('/').pop() || '');
|
||||
});
|
||||
for (const fpath of projFiles) {
|
||||
if (otherFilesCtx.length >= CTX_TOTAL_BYTES) break;
|
||||
const rel = fpath.replace(activeProjectName + '/', '');
|
||||
@@ -2217,7 +2338,8 @@ async function _codeAiSendImpl() {
|
||||
|
||||
// Include current file context (ask/code 모드 모두 포함)
|
||||
const currentFile = codeFiles.find(f => f.id === activeCodeFileId);
|
||||
let contextMsg = resolvedMessage;
|
||||
// otherFilesCtx는 currentFile 유무와 무관하게 항상 contextMsg에 포함 (현재 파일 없어도 프로젝트 파일 보이게)
|
||||
let contextMsg = otherFilesCtx ? otherFilesCtx + resolvedMessage : resolvedMessage;
|
||||
// Add tech hint for the model
|
||||
const techHints = { html: '웹 (HTML/CSS/JS)', python: 'Python', node: 'Node.js/JavaScript', auto: '' };
|
||||
const techHint = techHints[codeAiTech] || '';
|
||||
@@ -2282,7 +2404,7 @@ async function _codeAiSendImpl() {
|
||||
|
||||
if (codeAiAbort) codeAiAbort.abort();
|
||||
codeAiAbort = new AbortController();
|
||||
const historyForAPI = codeAiHistory.slice(-20, -1).map(m => ({ role: m.role, content: m.content }));
|
||||
const historyForAPI = _histForAPI(codeAiHistory);
|
||||
|
||||
// ── Ask 모드: 단일 API 호출, 도구 없이 바로 응답 ─────────────────────────
|
||||
if (codeAiMode === 'ask') {
|
||||
@@ -2296,6 +2418,7 @@ async function _codeAiSendImpl() {
|
||||
body: JSON.stringify({ message: contextMsg, history: historyForAPI, useTools: false, sessionId: codeAiSessionId, codeAiTech, codeAiLocal: !!localDirHandle, ...(codeAiModel ? { model: codeAiModel } : {}) }),
|
||||
});
|
||||
if (askRes.status === 401) { setAuthToken(''); _codeAiShowRelogin(); return; }
|
||||
if (askRes.status === 413) { askEl.textContent = '❌ 요청 크기 초과. 파일이 너무 크거나 대화 히스토리가 너무 깁니다.'; return; }
|
||||
if (askRes.ok) {
|
||||
const askReader = askRes.body.getReader();
|
||||
const askDec = new TextDecoder();
|
||||
@@ -2327,7 +2450,7 @@ async function _codeAiSendImpl() {
|
||||
askText = askText.replace(/<think>[\s\S]*?<\/think>/gi, '').replace(/<\/think>/gi, '').trim();
|
||||
askEl.textContent = askText || '(응답 없음)';
|
||||
codeAiRenderMarkdown(askEl, askText || '(응답 없음)');
|
||||
codeAiHistory.push({ role: 'assistant', content: askText || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'assistant', content: _histEntry(askText) || '(응답 없음)' });
|
||||
_autoSaveChatSession();
|
||||
if (activeProjectName) saveProjectSession(activeProjectName);
|
||||
try { updateSessionPanel(); } catch (_) {}
|
||||
@@ -2335,7 +2458,7 @@ async function _codeAiSendImpl() {
|
||||
}
|
||||
|
||||
// ── Code 모드: Phase 1 (계획) → confirm → Phase 2 (실행) ──────────────────
|
||||
const planInstruction = '\n\n[편집 계획] 코드를 수정해야 한다면: 파일명과 변경 내용을 한 줄씩 나열해. 질문이거나 설명만 필요하면: 바로 답해. 도구 사용 금지.';
|
||||
const planInstruction = '\n\n[편집 계획] 지금은 계획 단계 — 도구를 실행하지 말고 무엇을 할지만 설명해. 코드를 수정/생성/이동해야 한다면: 어떤 파일을 어떻게 바꿀지 한 줄씩 나열해 (예: "move_file: game.js → js/game.js", "edit_file: index.html — script 경로 수정"). 질문이거나 설명만 필요하면: 바로 답해. 승인되면 실행 단계에서 도구로 직접 처리함.';
|
||||
|
||||
const planThinkEl = codeAiAppend('thinking', '계획 중...');
|
||||
let planText = '';
|
||||
@@ -2397,49 +2520,132 @@ async function _codeAiSendImpl() {
|
||||
|
||||
if (!isPlanWithEdits) {
|
||||
// Pure Q&A — plan text is the answer; record it and stop
|
||||
codeAiHistory.push({ role: 'assistant', content: planText || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'assistant', content: _histEntry(planText) || '(응답 없음)' });
|
||||
_autoSaveChatSession();
|
||||
if (activeProjectName) saveProjectSession(activeProjectName);
|
||||
try { updateSessionPanel(); } catch (_) {}
|
||||
return;
|
||||
}
|
||||
|
||||
// Show confirm / cancel buttons and wait for user decision
|
||||
const _userConfirmed = await new Promise(resolve => {
|
||||
// Parse numbered options from plan text (e.g. "1. CSS 방식\n2. JS 방식")
|
||||
// Returns [{num, label}] if 2-5 sequential numbered items found, else []
|
||||
const _parsedOptions = (() => {
|
||||
const opts = [];
|
||||
for (const line of planText.split('\n')) {
|
||||
const m = line.match(/^(\d+)[.)]\s+(.+)/);
|
||||
if (!m) continue;
|
||||
if (parseInt(m[1]) !== opts.length + 1) break; // must be sequential
|
||||
opts.push({ num: parseInt(m[1]), label: m[2].replace(/\*\*/g, '').trim() });
|
||||
if (opts.length === 5) break;
|
||||
}
|
||||
return opts.length >= 2 ? opts : [];
|
||||
})();
|
||||
|
||||
// Show confirm / cancel / modify buttons and wait for user decision
|
||||
// Resolves with: true (execute) | false (cancel) | { modify: string } | { option: num, label: string }
|
||||
const _planDecision = await new Promise(resolve => {
|
||||
const msgs = document.getElementById('code-ai-messages');
|
||||
if (!msgs) { resolve(false); return; }
|
||||
// If the user already hit ⏹ 중지 before we got here, bail immediately.
|
||||
const signal = codeAiAbort?.signal;
|
||||
if (signal?.aborted) { resolve(false); return; }
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'code-ai-msg system';
|
||||
card.style.cssText = 'display:flex;gap:8px;padding:6px 0;align-items:center;flex-wrap:wrap';
|
||||
card.innerHTML = '<span style="font-size:12px;color:var(--muted)">위 계획대로 편집을 실행할까요?</span>';
|
||||
const confirmBtn = document.createElement('button');
|
||||
confirmBtn.textContent = '✅ 실행';
|
||||
confirmBtn.style.cssText = 'background:#28a745;color:#fff;border:none;border-radius:4px;padding:4px 12px;font-size:12px;font-weight:700;cursor:pointer';
|
||||
const cancelBtn = document.createElement('button');
|
||||
cancelBtn.textContent = '❌ 취소';
|
||||
cancelBtn.style.cssText = 'background:#dc3545;color:#fff;border:none;border-radius:4px;padding:4px 10px;font-size:12px;font-weight:700;cursor:pointer';
|
||||
// Resolve the wait if the user presses ⏹ 중지 during the confirm prompt.
|
||||
const onAbort = () => done(false, true);
|
||||
const done = (ok, viaAbort) => {
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
confirmBtn.disabled = cancelBtn.disabled = true;
|
||||
confirmBtn.style.opacity = cancelBtn.style.opacity = '0.5';
|
||||
if (viaAbort) card.innerHTML = '<span style="font-size:12px;color:var(--muted)">편집이 중지되었습니다.</span>';
|
||||
resolve(ok);
|
||||
card.style.cssText = 'padding:6px 0;';
|
||||
|
||||
const mkBtn = (text, bg, extra = '') => {
|
||||
const b = document.createElement('button');
|
||||
b.textContent = text;
|
||||
b.style.cssText = `background:${bg};color:#fff;border:none;border-radius:4px;padding:4px 10px;font-size:12px;font-weight:700;cursor:pointer;${extra}`;
|
||||
return b;
|
||||
};
|
||||
|
||||
const allBtns = [];
|
||||
const onAbort = () => done(false, true);
|
||||
const done = (result, viaAbort) => {
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
allBtns.forEach(b => { b.disabled = true; b.style.opacity = '0.5'; });
|
||||
if (modInput) modInput.disabled = true;
|
||||
if (viaAbort) card.innerHTML = '<span style="font-size:12px;color:var(--muted)">편집이 중지되었습니다.</span>';
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
// ── Option chips (shown when model presented numbered alternatives) ──────
|
||||
let modInput = null;
|
||||
if (_parsedOptions.length) {
|
||||
const optLabel = document.createElement('div');
|
||||
optLabel.style.cssText = 'font-size:11px;color:var(--muted);margin-bottom:4px';
|
||||
optLabel.textContent = '어떤 방법으로 진행할까요?';
|
||||
card.appendChild(optLabel);
|
||||
|
||||
const optRow = document.createElement('div');
|
||||
optRow.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px';
|
||||
for (const opt of _parsedOptions) {
|
||||
const short = opt.label.length > 28 ? opt.label.slice(0, 28) + '…' : opt.label;
|
||||
const ob = mkBtn(`${opt.num}. ${short}`, '#0d6efd', 'text-align:left;white-space:normal;max-width:220px;line-height:1.3;padding:5px 10px');
|
||||
ob.title = opt.label;
|
||||
ob.onclick = () => done({ option: opt.num, label: opt.label });
|
||||
allBtns.push(ob);
|
||||
optRow.appendChild(ob);
|
||||
}
|
||||
card.appendChild(optRow);
|
||||
}
|
||||
|
||||
// ── Main action row ──────────────────────────────────────────────────────
|
||||
const btnRow = document.createElement('div');
|
||||
btnRow.style.cssText = 'display:flex;gap:8px;align-items:center;flex-wrap:wrap';
|
||||
const hint = _parsedOptions.length
|
||||
? '<span style="font-size:12px;color:var(--muted)">또는:</span>'
|
||||
: '<span style="font-size:12px;color:var(--muted)">위 계획대로 편집을 실행할까요?</span>';
|
||||
btnRow.innerHTML = hint;
|
||||
|
||||
const confirmBtn = mkBtn('✅ 실행', '#28a745');
|
||||
const modifyBtn = mkBtn('✏️ 수정', '#6c757d');
|
||||
const cancelBtn = mkBtn('❌ 취소', '#dc3545');
|
||||
allBtns.push(confirmBtn, modifyBtn, cancelBtn);
|
||||
|
||||
// Modify row (hidden until ✏️ clicked)
|
||||
const modRow = document.createElement('div');
|
||||
modRow.style.cssText = 'display:none;margin-top:6px;gap:6px;align-items:flex-start;flex-direction:column';
|
||||
modInput = document.createElement('textarea');
|
||||
modInput.placeholder = '수정 요청 입력 (예: 버튼 색상은 파란색으로)';
|
||||
modInput.style.cssText = 'width:100%;box-sizing:border-box;padding:5px 8px;font-size:12px;border:1px solid var(--border,#444);border-radius:4px;background:var(--panel-2,#1e1e2e);color:var(--text,#ccc);resize:vertical;min-height:54px';
|
||||
const replanBtn = mkBtn('🔄 다시 계획', '#0d6efd');
|
||||
allBtns.push(replanBtn);
|
||||
modRow.appendChild(modInput);
|
||||
modRow.appendChild(replanBtn);
|
||||
|
||||
confirmBtn.onclick = () => done(true);
|
||||
cancelBtn.onclick = () => done(false);
|
||||
cancelBtn.onclick = () => done(false);
|
||||
modifyBtn.onclick = () => { modRow.style.display = 'flex'; modifyBtn.style.display = 'none'; modInput.focus(); };
|
||||
replanBtn.onclick = () => { const t = modInput.value.trim(); done(t ? { modify: t } : false); };
|
||||
modInput.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) replanBtn.click(); });
|
||||
|
||||
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
||||
card.appendChild(confirmBtn);
|
||||
card.appendChild(cancelBtn);
|
||||
btnRow.appendChild(confirmBtn);
|
||||
btnRow.appendChild(modifyBtn);
|
||||
btnRow.appendChild(cancelBtn);
|
||||
card.appendChild(btnRow);
|
||||
card.appendChild(modRow);
|
||||
msgs.appendChild(card);
|
||||
codeAiScrollBottom();
|
||||
});
|
||||
|
||||
if (!_userConfirmed) return; // user cancelled
|
||||
if (!_planDecision) return; // cancelled
|
||||
|
||||
// ── Option selected → re-plan with chosen option ────────────────────────────
|
||||
if (typeof _planDecision === 'object' && _planDecision.option != null) {
|
||||
await _codeAiSend(`${_planDecision.option}번 방법으로 진행해줘: ${_planDecision.label}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Re-plan with modification ────────────────────────────────────────────────
|
||||
if (typeof _planDecision === 'object' && _planDecision.modify) {
|
||||
await _codeAiSend(`위 계획을 다음 조건으로 수정해서 다시 계획해줘: ${_planDecision.modify}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const _userConfirmed = _planDecision; // true → proceed to execute
|
||||
|
||||
// ── Phase 2: execute (with tools, auto-accept) ─────────────────────────────
|
||||
_codeAiAutoAccept = true;
|
||||
@@ -2462,11 +2668,14 @@ async function _codeAiSendImpl() {
|
||||
execContextMsg = `${otherFilesCtx}[현재 파일: ${displayName} (전체 ${fullContent.split('\n').length}줄${bigNote})]\n\`\`\`${ext}\n${numberedFull}\n\`\`\`\n\n${resolvedMessage}`;
|
||||
}
|
||||
|
||||
// Include plan in execute history so model knows exactly what to do
|
||||
// Include plan in execute history so model knows exactly what to do.
|
||||
// Cap planText: if the plan phase returned huge content (e.g. full file rewrite), sending
|
||||
// it raw can push the request body over 50MB and cause 413 errors.
|
||||
const planTextCapped = planText.length > 12000 ? planText.slice(0, 12000) + '\n…[계획 잘림]' : planText;
|
||||
const execHistory = [
|
||||
...historyForAPI,
|
||||
{ role: 'assistant', content: planText },
|
||||
{ role: 'user', content: '위 계획대로 edit_file 도구를 즉시 실행해줘. 계획을 다시 요약하거나 반복하지 마. 첫 번째 메시지부터 바로 도구를 호출해. SEARCH 블록은 파일 내용에서 정확히 복사.' },
|
||||
{ role: 'assistant', content: planTextCapped },
|
||||
{ role: 'user', content: '위 계획대로 도구를 즉시 실행해줘 (edit_file, move_file, create_file 등 계획에 맞는 도구 사용). 계획을 다시 요약하거나 반복하지 마. 첫 번째 메시지부터 바로 도구를 호출해. SEARCH 블록은 파일 내용에서 정확히 복사.' },
|
||||
];
|
||||
|
||||
try {
|
||||
@@ -2535,7 +2744,7 @@ async function _codeAiSendImpl() {
|
||||
const toolError = ev.error || false;
|
||||
_codeAiToolAction(toolName, null, toolResult, toolError);
|
||||
// Refresh file list after successful file-modifying tools
|
||||
if (!toolError && ['create_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'edit_file'].includes(toolName)) {
|
||||
if (!toolError && ['create_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'edit_file', 'move_file', 'delete_file'].includes(toolName)) {
|
||||
codeSbRefresh();
|
||||
}
|
||||
}
|
||||
@@ -2726,18 +2935,18 @@ async function _codeAiSendImpl() {
|
||||
/^(what|how|why|when|where|who|which|can you explain|tell me|is there|are there|does|do |did )/i.test(message.trim());
|
||||
if (!hasCodeBlock && !hasDiffBlock && !toolsWereUsed && looksLikeAnalysis && !isQuestion && codeAiHistory.length > 0) {
|
||||
const retryMsg = '위 분석만 하지 말고 edit_file 또는 create_file 도구를 사용해서 실제로 파일을 수정해줘.';
|
||||
codeAiHistory.push({ role: 'assistant', content: reply || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'assistant', content: _histEntry(reply) || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'user', content: retryMsg });
|
||||
thinkEl.classList.add('streaming');
|
||||
thinkEl.textContent = '🔄 분석만 감지 — 도구로 파일 수정 재시도 중...';
|
||||
const retryAbort = new AbortController();
|
||||
try {
|
||||
const retryHistory = codeAiHistory.slice(-20).map(m => ({ role: m.role, content: m.content }));
|
||||
const retryHistory = _histForAPI(codeAiHistory);
|
||||
const retryRes = await fetch('/api/chat', {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'Content-Type': 'application/json', 'Accept': 'text/event-stream' }),
|
||||
signal: retryAbort.signal,
|
||||
body: JSON.stringify({ message: retryMsg, history: retryHistory.slice(0, -1), useTools: true, sessionId: codeAiSessionId + '_retry', codeAiTech, codeAiLocal: !!localDirHandle }),
|
||||
body: JSON.stringify({ message: retryMsg, history: retryHistory, useTools: true, sessionId: codeAiSessionId + '_retry', codeAiTech, codeAiLocal: !!localDirHandle }),
|
||||
});
|
||||
if (retryRes.ok) {
|
||||
const retryReader = retryRes.body.getReader();
|
||||
@@ -2849,7 +3058,7 @@ async function _codeAiSendImpl() {
|
||||
}
|
||||
if (failedParts.length) {
|
||||
const fixMsg = `edit_file SEARCH 블록이 실제 파일 내용과 일치하지 않았습니다. 아래 현재 내용을 기준으로 다시 수정해줘:\n\n${failedParts.join('\n\n')}`;
|
||||
codeAiHistory.push({ role: 'assistant', content: reply || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'assistant', content: _histEntry(reply) || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'user', content: fixMsg });
|
||||
thinkEl.classList.add('streaming');
|
||||
thinkEl.textContent = '🔄 SEARCH 불일치 — 실제 파일로 재시도 중...';
|
||||
@@ -2858,7 +3067,7 @@ async function _codeAiSendImpl() {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'Content-Type': 'application/json', 'Accept': 'text/event-stream' }),
|
||||
signal: codeAiAbort?.signal,
|
||||
body: JSON.stringify({ message: fixMsg, history: codeAiHistory.slice(-20, -1).map(m => ({ role: m.role, content: m.content })), useTools: true, sessionId: codeAiSessionId + '_fix', codeAiTech, codeAiLocal: !!localDirHandle, ...(codeAiModel ? { model: codeAiModel } : {}) }),
|
||||
body: JSON.stringify({ message: fixMsg, history: _histForAPI(codeAiHistory), useTools: true, sessionId: codeAiSessionId + '_fix', codeAiTech, codeAiLocal: !!localDirHandle, ...(codeAiModel ? { model: codeAiModel } : {}) }),
|
||||
});
|
||||
if (fixRes.ok) {
|
||||
const fixReader = fixRes.body.getReader();
|
||||
@@ -2902,7 +3111,7 @@ async function _codeAiSendImpl() {
|
||||
}
|
||||
}
|
||||
|
||||
codeAiHistory.push({ role: 'assistant', content: reply || '(응답 없음)' });
|
||||
codeAiHistory.push({ role: 'assistant', content: _histEntry(reply) || '(응답 없음)' });
|
||||
_autoSaveChatSession();
|
||||
if (activeProjectName) saveProjectSession(activeProjectName);
|
||||
try { updateSessionPanel(); } catch (_) {}
|
||||
@@ -2928,15 +3137,15 @@ const _TOOL_ICONS = {
|
||||
read_file: '📖', list_files: '📂', search_files: '🔍',
|
||||
edit_file: '✏️', create_file: '📄', replace_lines: '✏️',
|
||||
insert_after: '➕', delete_lines: '🗑️', find_replace: '🔄',
|
||||
delete_file: '🗑️', shell: '▶️', python_eval: '🐍', web_search: '🌐',
|
||||
delete_file: '🗑️', move_file: '📦', shell: '▶️', python_eval: '🐍', web_search: '🌐',
|
||||
};
|
||||
const _TOOL_COLORS = {
|
||||
read_file: '#3b82f6', list_files: '#3b82f6', search_files: '#3b82f6',
|
||||
edit_file: '#22c55e', create_file: '#22c55e', replace_lines: '#22c55e',
|
||||
insert_after: '#22c55e', delete_lines: '#f87171', find_replace: '#22c55e',
|
||||
delete_file: '#f87171', shell: '#f59e0b', python_eval: '#f59e0b', web_search: '#8b5cf6',
|
||||
delete_file: '#f87171', move_file: '#f59e0b', shell: '#f59e0b', python_eval: '#f59e0b', web_search: '#8b5cf6',
|
||||
};
|
||||
const _FILE_TOOLS = new Set(['read_file', 'create_file', 'edit_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'delete_file']);
|
||||
const _FILE_TOOLS = new Set(['read_file', 'create_file', 'edit_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'delete_file', 'move_file']);
|
||||
|
||||
function _codeAiToolAction(toolName, toolArgs, toolResult, toolError) {
|
||||
const msgs = document.getElementById('code-ai-messages');
|
||||
@@ -2952,7 +3161,9 @@ function _codeAiToolAction(toolName, toolArgs, toolResult, toolError) {
|
||||
const fname = toolArgs.filename || toolArgs.name || '';
|
||||
const shortName = fname.replace(/^code\//, '').split('/').pop() || '';
|
||||
const isFile = _FILE_TOOLS.has(toolName);
|
||||
const detail = isFile ? escHtml(shortName || fname) : (toolArgs.command || toolArgs.query || toolArgs.code || '').slice(0, 60);
|
||||
const detail = toolName === 'move_file'
|
||||
? escHtml(`${toolArgs.source || ''} → ${toolArgs.destination || ''}`)
|
||||
: isFile ? escHtml(shortName || fname) : (toolArgs.command || toolArgs.query || toolArgs.code || '').slice(0, 60);
|
||||
card.innerHTML = `<span class="code-ai-tool-icon" style="color:${color}">${icon}</span> <span class="code-ai-tool-name">${escHtml(toolName)}</span> <span class="code-ai-tool-detail" style="color:var(--muted);font-size:11px">${detail}</span>`;
|
||||
msgs.appendChild(card);
|
||||
codeAiScrollBottom();
|
||||
@@ -2963,10 +3174,11 @@ function _codeAiToolAction(toolName, toolArgs, toolResult, toolError) {
|
||||
if (card && !card.dataset.done) {
|
||||
card.dataset.done = '1';
|
||||
const resultIcon = toolError ? '❌' : '✅';
|
||||
const resultText = toolError ? escHtml((toolResult || 'Error').slice(0, 120)) : escHtml((toolResult || 'OK').slice(0, 80));
|
||||
const noDetail = !toolError && (toolName === 'move_file' || toolName === 'delete_file');
|
||||
const resultText = toolError ? escHtml((toolResult || 'Error').slice(0, 120)) : noDetail ? '' : escHtml((toolResult || '').slice(0, 80));
|
||||
const resultEl = document.createElement('span');
|
||||
resultEl.className = 'code-ai-tool-result';
|
||||
resultEl.innerHTML = `${resultIcon} ${resultText}`;
|
||||
resultEl.innerHTML = resultText ? `${resultIcon} ${resultText}` : resultIcon;
|
||||
card.appendChild(resultEl);
|
||||
if (toolError) card.style.borderLeftColor = '#f87171';
|
||||
}
|
||||
@@ -2993,9 +3205,9 @@ async function _codeAiApplyToolLocally(toolName, args) {
|
||||
}
|
||||
const fname = _clientBareFileName(rawFname);
|
||||
const diskPath = _clientProjectPath(fname);
|
||||
const _FILE_TOOLS = new Set(['create_file', 'edit_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'delete_file']);
|
||||
const _FILE_TOOLS = new Set(['create_file', 'edit_file', 'replace_lines', 'insert_after', 'delete_lines', 'find_replace', 'delete_file', 'move_file']);
|
||||
if (!_FILE_TOOLS.has(toolName)) return { ok: true };
|
||||
if (!fname) return { ok: false, reason: '파일명이 없습니다' };
|
||||
if (!fname && toolName !== 'move_file') return { ok: false, reason: '파일명이 없습니다' };
|
||||
|
||||
try {
|
||||
switch (toolName) {
|
||||
@@ -3071,6 +3283,29 @@ async function _codeAiApplyToolLocally(toolName, args) {
|
||||
if (fileId) { codeFiles.splice(codeFiles.findIndex(f => f.id === fileId), 1); renderCodeFileTabs(); }
|
||||
return { ok: true };
|
||||
}
|
||||
case 'move_file': {
|
||||
const srcRaw = _clientBareFileName((args.source || args.from || '').replace(/^code\//, ''));
|
||||
const dstRaw = _clientBareFileName((args.destination || args.to || '').replace(/^code\//, ''));
|
||||
const srcDisk = _clientProjectPath(srcRaw);
|
||||
const dstDisk = _clientProjectPath(dstRaw);
|
||||
if (!srcRaw || !dstRaw) return { ok: false, reason: 'source/destination가 없습니다' };
|
||||
const content = await _codeAiReadLocalFile(srcRaw);
|
||||
if (content === null) return { ok: false, reason: `${srcRaw}을(를) 찾을 수 없습니다 (탭에 파일이 열려있어야 합니다)` };
|
||||
if (localDirHandle) {
|
||||
const writeOk = await localWriteFile(dstDisk, content);
|
||||
if (!writeOk) return { ok: false, reason: `${dstRaw} 쓰기 실패 (폴더 권한 확인)` };
|
||||
}
|
||||
codeEditorWriteFile(dstRaw, content);
|
||||
if (localDirHandle) {
|
||||
const delOk = await localDeleteFile(srcDisk);
|
||||
if (!delOk) console.warn('[move_file] 소스 파일 삭제 실패:', srcDisk);
|
||||
}
|
||||
const srcId = codeFiles.find(f => f.name === srcRaw)?.id;
|
||||
if (srcId) { codeFiles.splice(codeFiles.findIndex(f => f.id === srcId), 1); renderCodeFileTabs(); }
|
||||
// Refresh sidebar after disk I/O is complete
|
||||
codeSbRefresh();
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
@@ -4239,6 +4474,7 @@ async function deleteActiveProject() {
|
||||
}
|
||||
|
||||
function switchProject(name) {
|
||||
_autoSaveChatSession(); // null 프로젝트 상태의 히스토리도 세션 목록에 보존
|
||||
if (activeProjectName) saveProjectSession(activeProjectName);
|
||||
activeProjectName = name || null;
|
||||
localStorage.setItem('code_active_project', activeProjectName || '');
|
||||
@@ -4653,9 +4889,15 @@ async function codeSbRefresh() {
|
||||
const isOpen = openDirs.has(dirId);
|
||||
const dirPath = (parentPath+'/'+name).replace(/^\//,'');
|
||||
const safeDirPath = dirPath.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||
html += `<div class="csb-file-item" style="padding-left:${indent+8}px;font-weight:600;color:var(--muted)" onclick="csbToggleDir('${dirId}')">
|
||||
html += `<div class="csb-file-item" data-dirpath="${escHtml(dirPath)}" style="padding-left:${indent+8}px;font-weight:600;color:var(--muted)"
|
||||
onclick="csbToggleDir('${dirId}')"
|
||||
oncontextmenu="csbCtxMenu(event,this,true)"
|
||||
ondragover="event.preventDefault();event.dataTransfer.dropEffect='move';this.classList.add('csb-drop-target')"
|
||||
ondragleave="this.classList.remove('csb-drop-target')"
|
||||
ondrop="csbDrop(event,this)">
|
||||
<span id="${dirId}_arrow" style="font-size:9px;transition:.15s;flex-shrink:0">${isOpen ? '▼' : '▶'}</span><span style="flex-shrink:0">📂</span>
|
||||
<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1">${escHtml(name)}/</span>
|
||||
<span class="csb-item-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1">${escHtml(name)}/</span>
|
||||
<button class="csb-add-btn" onclick="csbNewInDir(this.closest('[data-dirpath]').dataset.dirpath,event)" title="새 파일">+</button>
|
||||
<button class="csb-del" onclick="csbDeleteDir('${safeDirPath}',event)" title="디렉토리 삭제">✕</button>
|
||||
</div>
|
||||
<div id="${dirId}" style="display:${isOpen ? 'block' : 'none'}">
|
||||
@@ -4666,9 +4908,13 @@ async function codeSbRefresh() {
|
||||
const ext = name.split('.').pop().toLowerCase();
|
||||
const icon = extIcon[ext] || '📄';
|
||||
const safe = fullPath.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||
html += `<div class="csb-file-item" style="padding-left:${indent+8}px" onclick="csbOpenFile('${safe}')">
|
||||
html += `<div class="csb-file-item" data-path="${escHtml(fullPath)}" style="padding-left:${indent+8}px"
|
||||
draggable="true"
|
||||
ondragstart="event.dataTransfer.setData('text/plain',this.dataset.path);event.dataTransfer.effectAllowed='move'"
|
||||
oncontextmenu="csbCtxMenu(event,this,false)"
|
||||
onclick="csbOpenFile('${safe}')">
|
||||
<span style="flex-shrink:0">${icon}</span>
|
||||
<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1" title="${escHtml(fullPath)}">${escHtml(name)}</span>
|
||||
<span class="csb-item-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1" title="${escHtml(fullPath)}">${escHtml(name)}</span>
|
||||
<button class="csb-del" onclick="csbDeleteFile('${safe}',event)" title="삭제">✕</button>
|
||||
</div>`;
|
||||
}
|
||||
@@ -4745,6 +4991,165 @@ async function csbDeleteDir(dirPath, ev) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Context menu ─────────────────────────────────────────────────────────────
|
||||
let _csbCtxTarget = null;
|
||||
|
||||
function csbCtxMenu(ev, el, isDir) {
|
||||
ev.preventDefault(); ev.stopPropagation();
|
||||
_csbCtxTarget = { path: el.dataset.path || el.dataset.dirpath, isDir };
|
||||
const menu = document.getElementById('csb-ctx');
|
||||
if (!menu) return;
|
||||
const items = isDir ? [
|
||||
{ label: '📄 새 파일', action: 'newfile' },
|
||||
{ label: '📁 새 폴더', action: 'newfolder' },
|
||||
{ label: '✏️ 이름 바꾸기', action: 'rename' },
|
||||
{ label: '🗑️ 삭제', action: 'delete' },
|
||||
] : [
|
||||
{ label: '✏️ 이름 바꾸기', action: 'rename' },
|
||||
{ label: '🗑️ 삭제', action: 'delete' },
|
||||
];
|
||||
menu.innerHTML = items.map(i => `<div class="csb-ctx-item" onclick="csbCtxAction('${i.action}')">${i.label}</div>`).join('');
|
||||
menu.style.display = 'block';
|
||||
const x = Math.min(ev.clientX, window.innerWidth - 160);
|
||||
const y = Math.min(ev.clientY, window.innerHeight - (items.length * 34) - 16);
|
||||
menu.style.left = x + 'px';
|
||||
menu.style.top = y + 'px';
|
||||
}
|
||||
function csbCtxClose() {
|
||||
const menu = document.getElementById('csb-ctx');
|
||||
if (menu) menu.style.display = 'none';
|
||||
_csbCtxTarget = null;
|
||||
}
|
||||
function csbCtxAction(action) {
|
||||
const target = _csbCtxTarget;
|
||||
csbCtxClose();
|
||||
if (!target) return;
|
||||
const { path, isDir } = target;
|
||||
if (action === 'rename') csbInlineRename(path, isDir);
|
||||
else if (action === 'delete') isDir ? csbDeleteDir(path, { stopPropagation: () => {} }) : csbDeleteFile(path, { stopPropagation: () => {} });
|
||||
else if (action === 'newfile') csbNewInDir(path, null);
|
||||
else if (action === 'newfolder') csbNewFolderAt(path);
|
||||
}
|
||||
|
||||
// ── Inline rename ─────────────────────────────────────────────────────────────
|
||||
function csbInlineRename(path, isDir) {
|
||||
const tree = document.getElementById('csb-file-tree');
|
||||
if (!tree) return;
|
||||
const attr = isDir ? 'data-dirpath' : 'data-path';
|
||||
const item = tree.querySelector(`[${attr}="${path.replace(/\\/g,'\\\\').replace(/"/g,'\\"')}"]`);
|
||||
if (!item) return;
|
||||
const nameEl = item.querySelector('.csb-item-name');
|
||||
if (!nameEl) return;
|
||||
const oldBase = path.split('/').pop();
|
||||
const inp = document.createElement('input');
|
||||
inp.value = oldBase;
|
||||
inp.style.cssText = 'flex:1;min-width:0;font-size:11px;padding:1px 4px;background:var(--panel);color:var(--text);border:1px solid var(--brand);border-radius:3px;outline:none;font-family:inherit';
|
||||
nameEl.replaceWith(inp);
|
||||
inp.focus(); inp.select();
|
||||
let done = false;
|
||||
const commit = async () => {
|
||||
if (done) return; done = true;
|
||||
const newName = inp.value.trim();
|
||||
if (newName && newName !== oldBase) await csbRenameExec(path, newName, isDir);
|
||||
else await codeSbRefresh();
|
||||
};
|
||||
inp.onblur = commit;
|
||||
inp.onkeydown = e => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); commit(); }
|
||||
if (e.key === 'Escape') { done = true; codeSbRefresh(); }
|
||||
};
|
||||
}
|
||||
|
||||
async function csbRenameExec(oldPath, newName, isDir) {
|
||||
if (!localDirHandle) return;
|
||||
const parts = oldPath.split('/');
|
||||
parts[parts.length - 1] = newName;
|
||||
const newPath = parts.join('/');
|
||||
try {
|
||||
if (!isDir) {
|
||||
const content = await localReadFile(oldPath);
|
||||
if (content === null) throw new Error('읽기 실패');
|
||||
await localWriteFile(newPath, content);
|
||||
await localDeleteFile(oldPath);
|
||||
const bare = _clientBareFileName(oldPath);
|
||||
const tab = codeFiles.find(f => f.name === bare);
|
||||
if (tab) { tab.name = _clientBareFileName(newPath); renderCodeFileTabs(); }
|
||||
} else {
|
||||
const allFiles = await localListFiles(localDirHandle, '');
|
||||
const prefix = oldPath + '/';
|
||||
for (const f of allFiles.filter(f => f.startsWith(prefix))) {
|
||||
const content = await localReadFile(f);
|
||||
if (content !== null) await localWriteFile(newPath + '/' + f.slice(prefix.length), content);
|
||||
}
|
||||
const ps = oldPath.split('/');
|
||||
let parent = localDirHandle;
|
||||
for (let i = 0; i < ps.length - 1; i++) parent = await parent.getDirectoryHandle(ps[i]);
|
||||
await parent.removeEntry(ps[ps.length - 1], { recursive: true });
|
||||
for (const f of codeFiles) {
|
||||
const disk = _clientProjectPath(f.name);
|
||||
if (disk.startsWith(prefix)) f.name = _clientBareFileName(newPath + '/' + disk.slice(prefix.length));
|
||||
}
|
||||
renderCodeFileTabs();
|
||||
}
|
||||
await codeSbRefresh();
|
||||
} catch (e) { alert('이름 바꾸기 실패: ' + (e.message || e)); await codeSbRefresh(); }
|
||||
}
|
||||
|
||||
// ── New file/folder helpers ───────────────────────────────────────────────────
|
||||
async function csbNewInDir(dirPath, ev) {
|
||||
if (ev) ev.stopPropagation();
|
||||
if (!localDirHandle) return;
|
||||
const name = prompt(`새 파일 이름 (${dirPath.split('/').pop()}/ 에 생성):`);
|
||||
if (!name?.trim()) return;
|
||||
const fullPath = dirPath + '/' + name.trim();
|
||||
await localWriteFile(fullPath, '');
|
||||
codeNewFile(_clientBareFileName(fullPath), '');
|
||||
codeSbRefresh();
|
||||
}
|
||||
|
||||
async function csbNewFolderAt(parentPath, ev) {
|
||||
if (ev) ev.stopPropagation();
|
||||
if (!localDirHandle) return;
|
||||
const name = prompt(`새 폴더 이름 (${parentPath.split('/').pop()}/ 안에 생성):`);
|
||||
if (!name?.trim()) return;
|
||||
await localWriteFile(parentPath + '/' + name.trim() + '/.gitkeep', '');
|
||||
codeSbRefresh();
|
||||
}
|
||||
|
||||
async function csbNewFolderRoot() {
|
||||
if (!localDirHandle) return;
|
||||
const base = activeProjectName ? activeProjectName + '/' : '';
|
||||
const name = prompt('새 폴더 이름:');
|
||||
if (!name?.trim()) return;
|
||||
await localWriteFile(base + name.trim() + '/.gitkeep', '');
|
||||
codeSbRefresh();
|
||||
}
|
||||
|
||||
// ── Drag and drop ─────────────────────────────────────────────────────────────
|
||||
function csbDrop(ev, el) {
|
||||
ev.preventDefault(); ev.stopPropagation();
|
||||
el.classList.remove('csb-drop-target');
|
||||
const srcPath = ev.dataTransfer.getData('text/plain');
|
||||
const dirPath = el.dataset.dirpath;
|
||||
if (!srcPath || !dirPath) return;
|
||||
const dstPath = dirPath + '/' + srcPath.split('/').pop();
|
||||
if (srcPath === dstPath) return;
|
||||
csbMoveFile(srcPath, dstPath);
|
||||
}
|
||||
|
||||
async function csbMoveFile(srcPath, dstPath) {
|
||||
if (!localDirHandle) return;
|
||||
try {
|
||||
const content = await localReadFile(srcPath);
|
||||
if (content === null) { alert(`읽기 실패: ${srcPath}`); return; }
|
||||
await localWriteFile(dstPath, content);
|
||||
await localDeleteFile(srcPath);
|
||||
const tab = codeFiles.find(f => f.name === _clientBareFileName(srcPath));
|
||||
if (tab) { tab.name = _clientBareFileName(dstPath); renderCodeFileTabs(); }
|
||||
await codeSbRefresh();
|
||||
} catch (e) { alert('이동 실패: ' + (e.message || e)); }
|
||||
}
|
||||
|
||||
async function csbLoadModels() {
|
||||
const sel = document.getElementById('csb-model-select');
|
||||
if (!sel) return;
|
||||
|
||||
@@ -2796,6 +2796,24 @@
|
||||
border-radius: 4px; flex-shrink: 0; transition: opacity .15s;
|
||||
}
|
||||
.csb-del:hover { background: rgba(248,113,113,.18); }
|
||||
.csb-add-btn {
|
||||
opacity: 0; background: none; border: none; color: var(--muted);
|
||||
cursor: pointer; font-size: 14px; padding: 1px 4px; border-radius: 4px;
|
||||
flex-shrink: 0; transition: opacity .15s; line-height: 1;
|
||||
}
|
||||
.csb-file-item:hover .csb-add-btn { opacity: 1; }
|
||||
.csb-add-btn:hover { background: rgba(99,102,241,.2); color: var(--brand); }
|
||||
.csb-drop-target { background: rgba(99,102,241,.15) !important; outline: 1px dashed #818cf8; border-radius: 4px; }
|
||||
#csb-ctx {
|
||||
position: fixed; z-index: 9999; display: none;
|
||||
background: var(--panel-2); border: 1px solid var(--line);
|
||||
border-radius: 7px; box-shadow: 0 4px 20px rgba(0,0,0,.45);
|
||||
min-width: 148px; overflow: hidden; padding: 3px 0;
|
||||
}
|
||||
.csb-ctx-item {
|
||||
padding: 7px 16px; font-size: 12px; cursor: pointer; white-space: nowrap; color: var(--text);
|
||||
}
|
||||
.csb-ctx-item:hover { background: var(--brand); color: #fff; }
|
||||
.code-folder-item {
|
||||
display: flex; align-items: center;
|
||||
padding: 5px 10px 5px 14px; font-size: 11px;
|
||||
|
||||
Reference in new issue
Block a user