mirror of
https://github.com/qwibitai/nanoclaw.git
synced 2026-07-06 18:52:03 +08:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0dfde3aa5b | |||
| 33d2366252 | |||
| 9bf1514f26 | |||
| be3502c23b | |||
| e3f38dbed9 | |||
| d8a6b99f0e | |||
| 8ca7564fbc | |||
| afa07f0566 | |||
| 8059ee4eec | |||
| 41c486cacc | |||
| 190a7d4f43 | |||
| 0626dcec92 | |||
| b42329551d | |||
| 855f204d8a |
@@ -48,7 +48,11 @@ export function openInboundDb(): Database {
|
||||
// so the singleton survives for the rest of the test.
|
||||
if (_testMode && _inbound) {
|
||||
const db = _inbound;
|
||||
return { prepare: (sql: string) => db.prepare(sql), exec: (sql: string) => db.exec(sql), close: () => {} } as unknown as Database;
|
||||
return {
|
||||
prepare: (sql: string) => db.prepare(sql),
|
||||
exec: (sql: string) => db.exec(sql),
|
||||
close: () => {},
|
||||
} as unknown as Database;
|
||||
}
|
||||
const db = new Database(DEFAULT_INBOUND_PATH, { readonly: true });
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
@@ -260,11 +264,3 @@ export function closeSessionDb(): void {
|
||||
_outbound?.close();
|
||||
_outbound = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use getInboundDb() / getOutboundDb() instead.
|
||||
* Kept for backward compatibility during migration.
|
||||
*/
|
||||
export function getSessionDb(): Database {
|
||||
return getInboundDb();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
export {
|
||||
getInboundDb,
|
||||
getOutboundDb,
|
||||
getSessionDb,
|
||||
initTestSessionDb,
|
||||
closeSessionDb,
|
||||
touchHeartbeat,
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nanoclaw",
|
||||
"version": "2.1.32",
|
||||
"version": "2.1.34",
|
||||
"description": "Personal Claude assistant. Lightweight, secure, customizable.",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@10.33.0",
|
||||
|
||||
@@ -33,7 +33,9 @@ db.exec(`
|
||||
`);
|
||||
|
||||
// Insert test message
|
||||
db.prepare(`INSERT INTO messages_in (id, kind, timestamp, status, content) VALUES (?, 'chat', datetime('now'), 'pending', ?)`).run(
|
||||
db.prepare(
|
||||
`INSERT INTO messages_in (id, kind, timestamp, status, content) VALUES (?, 'chat', datetime('now'), 'pending', ?)`,
|
||||
).run(
|
||||
'test-1',
|
||||
JSON.stringify({ sender: 'Gavriel', text: 'Say "Hello from v2!" and nothing else. Do not use any tools.' }),
|
||||
);
|
||||
@@ -44,7 +46,7 @@ db.close();
|
||||
process.env.SESSION_DB_PATH = DB_PATH;
|
||||
process.env.AGENT_PROVIDER = 'claude';
|
||||
|
||||
const { getSessionDb, closeSessionDb } = await import('../container/agent-runner/src/db/connection.js');
|
||||
const { getInboundDb, closeSessionDb } = await import('../container/agent-runner/src/db/connection.js');
|
||||
const { getUndeliveredMessages } = await import('../container/agent-runner/src/db/messages-out.js');
|
||||
const { getPendingMessages } = await import('../container/agent-runner/src/db/messages-in.js');
|
||||
const { createProvider } = await import('../container/agent-runner/src/providers/factory.js');
|
||||
|
||||
@@ -71,7 +71,7 @@ import { routeInbound } from '../src/router.js';
|
||||
import { setDeliveryAdapter, startActiveDeliveryPoll, stopDeliveryPolls } from '../src/delivery.js';
|
||||
import { getChannelAdapter, registerChannelAdapter, initChannelAdapters } from '../src/channels/channel-registry.js';
|
||||
import { findSession } from '../src/db/sessions.js';
|
||||
import { sessionDbPath } from '../src/session-manager.js';
|
||||
import { inboundDbPath } from '../src/session-manager.js';
|
||||
import type { ChannelAdapter, ChannelSetup, OutboundMessage } from '../src/channels/adapter.js';
|
||||
|
||||
// Track delivered messages
|
||||
@@ -99,7 +99,9 @@ const mockAdapter: ChannelAdapter = {
|
||||
|
||||
async setTyping() {},
|
||||
async teardown() {},
|
||||
isConnected() { return true; },
|
||||
isConnected() {
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
// Register mock adapter
|
||||
@@ -179,15 +181,19 @@ console.log(`✓ Container status: ${session.container_status}`);
|
||||
import { execSync } from 'child_process';
|
||||
const checkContainerLogs = () => {
|
||||
try {
|
||||
const containers = execSync('docker ps -a --filter name=nanoclaw-v2-test-channel --format "{{.Names}}"').toString().trim();
|
||||
const containers = execSync('docker ps -a --filter name=nanoclaw-v2-test-channel --format "{{.Names}}"')
|
||||
.toString()
|
||||
.trim();
|
||||
for (const name of containers.split('\n').filter(Boolean)) {
|
||||
console.log(`\nContainer logs (${name}):`);
|
||||
console.log(execSync(`docker logs ${name} 2>&1`).toString());
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const sessDbPath = sessionDbPath('ag-chan', session.id);
|
||||
const sessDbPath = inboundDbPath('ag-chan', session.id);
|
||||
console.log(`✓ Session DB: ${sessDbPath}`);
|
||||
|
||||
// --- Step 4: Wait for delivery through mock adapter ---
|
||||
@@ -210,7 +216,9 @@ await new Promise<void>((resolve) => {
|
||||
console.log(` messages_out rows: ${out.length}`);
|
||||
if (out.length > 0) console.log(' (messages exist but delivery failed)');
|
||||
db.close();
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
checkContainerLogs();
|
||||
cleanup();
|
||||
process.exit(1);
|
||||
|
||||
@@ -27,7 +27,7 @@ register({
|
||||
if (cliScope === 'group') {
|
||||
resources = resources.filter((r) => GROUP_SCOPE_RESOURCES.has(r.plural));
|
||||
}
|
||||
const commands = listCommands().filter((c) => c.access !== 'hidden' && !c.resource);
|
||||
const commands = listCommands().filter((c) => !c.resource);
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
|
||||
+1
-2
@@ -10,14 +10,13 @@ import { randomUUID } from 'crypto';
|
||||
|
||||
import { getDb } from '../db/connection.js';
|
||||
import { register } from './registry.js';
|
||||
import type { Access } from './registry.js';
|
||||
import type { CallerContext } from './frame.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type Access = 'open' | 'approval' | 'hidden';
|
||||
|
||||
export interface ColumnDef {
|
||||
name: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'json';
|
||||
|
||||
+1
-3
@@ -11,7 +11,7 @@
|
||||
export type RequestFrame = {
|
||||
/** Correlation key set by the client. */
|
||||
id: string;
|
||||
/** Registry name, e.g. "list-groups". */
|
||||
/** Registry name, e.g. "groups-list". */
|
||||
command: string;
|
||||
/** Command-specific. Each command's parseArgs validates. */
|
||||
args: Record<string, unknown>;
|
||||
@@ -24,10 +24,8 @@ export type ResponseFrame =
|
||||
export type ErrorCode =
|
||||
| 'unknown-command'
|
||||
| 'invalid-args'
|
||||
| 'permission-denied'
|
||||
| 'forbidden'
|
||||
| 'approval-pending'
|
||||
| 'not-found'
|
||||
| 'handler-error'
|
||||
| 'transport-error';
|
||||
|
||||
|
||||
+14
-5
@@ -1,19 +1,28 @@
|
||||
/**
|
||||
* Command registry — single source of truth for what `ncl` can do.
|
||||
*
|
||||
* Each command file under `commands/` calls `register()` at top level,
|
||||
* and `commands/index.ts` imports them all for side effects so the
|
||||
* registry is populated before the host's CLI server accepts connections.
|
||||
* Most commands come from resource modules under `resources/`, which call
|
||||
* `registerResource()` (one `register()` per CRUD verb); the top-level `help`
|
||||
* command and the per-resource help commands register directly. The barrel
|
||||
* `commands/index.ts` imports the resource barrel for its side effects and then
|
||||
* registers the help commands, so the registry is populated before the host's
|
||||
* CLI server accepts connections.
|
||||
*/
|
||||
import type { CallerContext } from './frame.js';
|
||||
|
||||
export type Access = 'open' | 'approval' | 'hidden';
|
||||
export type Access = 'open' | 'approval';
|
||||
|
||||
export type CommandDef<TArgs = unknown, TData = unknown> = {
|
||||
name: string;
|
||||
description: string;
|
||||
access: Access;
|
||||
/** Resource this command belongs to (for help grouping). */
|
||||
/**
|
||||
* The group-scope whitelist key. Under `cli_scope: 'group'` the dispatcher
|
||||
* only lets an agent run commands whose `resource` is on the whitelist
|
||||
* (`groups`, `sessions`, `destinations`, `members`); it also drives help
|
||||
* grouping. Omitting `resource` exempts the command from the whitelist —
|
||||
* that's how general commands like `help` stay reachable in group scope.
|
||||
*/
|
||||
resource?: string;
|
||||
/**
|
||||
* Set on the auto-generated `list` / `get` handlers (see `registerResource`).
|
||||
|
||||
@@ -181,14 +181,6 @@ export function syncProcessingAcks(inDb: Database.Database, outDb: Database.Data
|
||||
})();
|
||||
}
|
||||
|
||||
export function getStuckProcessingIds(outDb: Database.Database): string[] {
|
||||
return (
|
||||
outDb.prepare("SELECT message_id FROM processing_ack WHERE status = 'processing'").all() as Array<{
|
||||
message_id: string;
|
||||
}>
|
||||
).map((r) => r.message_id);
|
||||
}
|
||||
|
||||
export interface ProcessingClaim {
|
||||
message_id: string;
|
||||
status_changed: string;
|
||||
|
||||
+1
-10
@@ -24,16 +24,7 @@ import { enforceUpgradeTripwire } from './upgrade-state.js';
|
||||
// effects, and the modules call registerResponseHandler/onShutdown at top
|
||||
// level — which would hit a TDZ error if the arrays lived here. Re-exported
|
||||
// here so existing callers see the same surface.
|
||||
import {
|
||||
registerResponseHandler,
|
||||
getResponseHandlers,
|
||||
onShutdown,
|
||||
getShutdownCallbacks,
|
||||
type ResponsePayload,
|
||||
type ResponseHandler,
|
||||
} from './response-registry.js';
|
||||
export { registerResponseHandler, onShutdown };
|
||||
export type { ResponsePayload, ResponseHandler };
|
||||
import { getResponseHandlers, getShutdownCallbacks, type ResponsePayload } from './response-registry.js';
|
||||
|
||||
async function dispatchResponse(payload: ResponsePayload): Promise<void> {
|
||||
for (const handler of getResponseHandlers()) {
|
||||
|
||||
@@ -16,7 +16,17 @@ vi.mock('./config.js', async () => {
|
||||
return { ...actual, DATA_DIR: '/tmp/nanoclaw-test-write-outbound' };
|
||||
});
|
||||
|
||||
import { initSessionFolder, outboundDbPath, writeOutboundDirect } from './session-manager.js';
|
||||
import {
|
||||
initSessionFolder,
|
||||
inboundDbPath,
|
||||
outboundDbPath,
|
||||
sessionDir,
|
||||
writeOutboundDirect,
|
||||
writeSessionMessage,
|
||||
} from './session-manager.js';
|
||||
import { initTestDb, closeDb, runMigrations, createAgentGroup } from './db/index.js';
|
||||
import { createSession } from './db/sessions.js';
|
||||
import type { Session } from './types.js';
|
||||
|
||||
const TEST_DIR = '/tmp/nanoclaw-test-write-outbound';
|
||||
const AG = 'ag-test';
|
||||
@@ -98,3 +108,71 @@ describe('writeOutboundDirect', () => {
|
||||
expect(rows.map((r) => r.seq)).toEqual([2, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The `/debug` skill tells operators to `rm -rf` a session folder to reset a
|
||||
* stuck session. The sessions row survives, so the next message takes the
|
||||
* existing-session path and lands in `writeSessionMessage` with a missing
|
||||
* inbound.db. Without re-provisioning, better-sqlite3 throws on open and the
|
||||
* message is logged-and-dropped forever — the reset silently kills the chat.
|
||||
*/
|
||||
describe('writeSessionMessage re-provisions a deleted session folder', () => {
|
||||
beforeEach(() => {
|
||||
const db = initTestDb();
|
||||
runMigrations(db);
|
||||
createAgentGroup({
|
||||
id: AG,
|
||||
name: 'Reset',
|
||||
folder: 'reset',
|
||||
agent_provider: null,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
const sess: Session = {
|
||||
id: SESS,
|
||||
agent_group_id: AG,
|
||||
messaging_group_id: null,
|
||||
thread_id: null,
|
||||
agent_provider: null,
|
||||
status: 'active',
|
||||
container_status: 'stopped',
|
||||
last_active: null,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
createSession(sess);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDb();
|
||||
});
|
||||
|
||||
it('re-creates the folder + inbound.db and does not throw when the row still exists', () => {
|
||||
// Operator resets a stuck session by deleting its folder; the row survives.
|
||||
fs.rmSync(sessionDir(AG, SESS), { recursive: true, force: true });
|
||||
expect(fs.existsSync(inboundDbPath(AG, SESS))).toBe(false);
|
||||
|
||||
expect(() =>
|
||||
writeSessionMessage(AG, SESS, {
|
||||
id: 'after-reset-1',
|
||||
kind: 'chat',
|
||||
timestamp: new Date().toISOString(),
|
||||
platformId: 'slack:C1',
|
||||
channelType: 'slack',
|
||||
threadId: null,
|
||||
content: JSON.stringify({ text: 'still here?' }),
|
||||
}),
|
||||
).not.toThrow();
|
||||
|
||||
// The folder + inbound.db are back and the message landed.
|
||||
expect(fs.existsSync(inboundDbPath(AG, SESS))).toBe(true);
|
||||
const db = new Database(inboundDbPath(AG, SESS), { readonly: true });
|
||||
try {
|
||||
const row = db.prepare('SELECT id, content FROM messages_in WHERE id = ?').get('after-reset-1') as
|
||||
| { id: string; content: string }
|
||||
| undefined;
|
||||
expect(row?.id).toBe('after-reset-1');
|
||||
expect(JSON.parse(row!.content).text).toBe('still here?');
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+10
-36
@@ -64,14 +64,6 @@ export function heartbeatPath(agentGroupId: string, sessionId: string): string {
|
||||
return path.join(sessionDir(agentGroupId, sessionId), '.heartbeat');
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use inboundDbPath / outboundDbPath instead.
|
||||
* Kept temporarily for test compatibility during migration.
|
||||
*/
|
||||
export function sessionDbPath(agentGroupId: string, sessionId: string): string {
|
||||
return inboundDbPath(agentGroupId, sessionId);
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
return `sess-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
@@ -219,6 +211,16 @@ export function writeSessionMessage(
|
||||
onWake?: 0 | 1;
|
||||
},
|
||||
): void {
|
||||
// Documented reset: operators `rm -rf` a session folder to clear a stuck
|
||||
// session. The sessions row survives, so the next message takes the
|
||||
// existing-session path and lands here with a missing inbound.db — the open
|
||||
// below would throw and the message would be logged-and-dropped forever.
|
||||
// Re-provision the folder + DBs (initSessionFolder is idempotent) so the
|
||||
// documented reset actually re-provisions instead of killing the chat.
|
||||
if (!fs.existsSync(inboundDbPath(agentGroupId, sessionId))) {
|
||||
initSessionFolder(agentGroupId, sessionId);
|
||||
}
|
||||
|
||||
// Extract base64 attachment data, save to inbox, replace with file paths
|
||||
const content = extractAttachmentFiles(agentGroupId, sessionId, message.id, message.content);
|
||||
|
||||
@@ -392,34 +394,6 @@ export function writeOutboundDirect(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use openInboundDb / openOutboundDb instead.
|
||||
*/
|
||||
export function openSessionDb(agentGroupId: string, sessionId: string): Database.Database {
|
||||
return openInboundDb(agentGroupId, sessionId);
|
||||
}
|
||||
|
||||
/** Write a system response to a session's inbound.db so the container's findQuestionResponse() picks it up. */
|
||||
export function writeSystemResponse(
|
||||
agentGroupId: string,
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
status: string,
|
||||
result: Record<string, unknown>,
|
||||
): void {
|
||||
writeSessionMessage(agentGroupId, sessionId, {
|
||||
id: `sys-resp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
kind: 'system',
|
||||
timestamp: new Date().toISOString(),
|
||||
content: JSON.stringify({
|
||||
type: 'question_response',
|
||||
questionId: requestId,
|
||||
status,
|
||||
result,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load outbox attachments for a delivered message.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user