Skip to content

Your always-on AI coworkers that move between text, calls, and Slack.

TypeScript

Add per-Dot Automatic Learning and published skill delivery (#4)

Jerel Velardef2616a283277
diff --git a/docs/SETUP.md b/docs/SETUP.md
index 1241380..645c2cf 100644
--- a/docs/SETUP.md
+++ b/docs/SETUP.md
@@ -130,6 +130,51 @@ docker compose down
For remote hosting, configure an HTTPS reverse proxy and the matching `APP_ORIGIN`. See [Security](../SECURITY.md) for the template's deployment boundary.
+## Automatic Learning
+
+OpenDots connects [CopilotKit Automatic Learning](https://docs.copilotkit.ai/learning)
+to individual Dots. It uses the existing server-side `INTELLIGENCE_API_KEY` and
+optional `INTELLIGENCE_API_URL`; no additional model key or frontend key is needed.
+
+1. Open **Learning** in the same Intelligence project and create a container for
+ one focused workflow, such as `research-workflow`. IDs use 1–64 lowercase
+ letters, numbers, and single hyphens.
+2. In OpenDots, edit the Dot and enter that ID under **Automatic Learning**.
+ Saving the ID configures routing; it does not create or verify the remote container.
+3. Start new conversations and complete related workflows. Each conversation keeps
+ the container assigned when it was created. Existing conversations, including
+ ones created before this integration, are not enrolled retroactively. Changing
+ or clearing the Dot's ID affects only new conversations. This applies to page
+ chat, scheduled and voice compute in those conversations, and new Slack threads.
+4. In Intelligence, inspect the evidence, run Learning manually or use its schedule,
+ and review and publish proposed skills. The default automatic threshold is 15
+ eligible threads; use the readiness count shown in your deployment.
+5. Enable **Skill delivery** on the Intelligence container, then enable **Use
+ published skills** in the Dot's settings. Start a new turn in an enrolled
+ conversation. The native BuiltInAgent integration loads the latest published
+ catalog and exposes `copilotkit_load_skill` and `copilotkit_read_skill_file`.
+ The model decides which relevant skills to load. Check the run's tool calls to
+ verify actual use; saving settings alone does not establish connectivity.
+
+Skill delivery always uses the conversation's original container, even after the
+Dot is pointed at another container. The Dot's delivery checkbox applies to all its
+conversations. Unchecking it stops delivery on subsequent turns; changing Learning
+settings also stops active work. Conversations without a container do not request
+skills. Existing research, memory, page, and computer permissions still apply.
+
+Ingestion and delivery are separate. Clearing the container does not unenroll older
+conversations; pause Learning in Intelligence to stop its analysis. Turning off
+delivery does not stop evidence collection. A delivery denial or an unavailable
+initial skill snapshot fails the turn rather than silently continuing without the
+configured skills. Restore delivery or uncheck **Use published skills** to continue
+without them. Skills require review and publication in Intelligence; OpenDots does
+not automatically approve them.
+
+The integration uses an explicit container list, so ambient
+`CPK_INTELLIGENCE_LEARNING_CONTAINER_ID` and `CPK_INTELLIGENCE_SKILLS_REVISION`
+variables do not override a conversation's configuration. Self-hosted Intelligence
+must support the [skill delivery endpoints](https://docs.copilotkit.ai/intelligence/learned-skills).
+
## Development checks
```sh
diff --git a/src/client/WorkspaceDialog.tsx b/src/client/WorkspaceDialog.tsx
index 7106aed..234fa4d 100644
--- a/src/client/WorkspaceDialog.tsx
+++ b/src/client/WorkspaceDialog.tsx
@@ -47,6 +47,12 @@ export function WorkspaceDialog({
dialog.type === 'dot' ? (dialog.dot?.spaceId ?? dialog.spaceId) : '',
);
const [interval, setInterval] = useState('86400');
+ const [learningContainer, setLearningContainer] = useState(
+ dialog.type === 'dot' ? (dialog.dot?.learningContainerId ?? '') : '',
+ );
+ const [skillDelivery, setSkillDelivery] = useState(
+ dialog.type === 'dot' ? (dialog.dot?.skillDeliveryEnabled ?? false) : false,
+ );
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const container = useRef<HTMLElement>(null);
@@ -134,6 +140,8 @@ export function WorkspaceDialog({
instructions: text,
researchAllowed: research,
memoryAllowed: memory,
+ learningContainerId: learningContainer.trim() || null,
+ skillDeliveryEnabled: skillDelivery,
};
}
if (dialog.type === 'settings') {
@@ -279,6 +287,56 @@ export function WorkspaceDialog({
</label>
</>
)}
+ {dialog.type === 'dot' && (
+ <fieldset className="space-access-fields">
+ <legend>Automatic Learning</legend>
+ <label className="field-label" htmlFor="learning-container">
+ Learning container ID
+ </label>
+ <input
+ id="learning-container"
+ value={learningContainer}
+ maxLength={64}
+ pattern="[a-z0-9]+(-[a-z0-9]+)*"
+ placeholder="research-workflow"
+ aria-describedby="learning-help"
+ onChange={(event) => {
+ setLearningContainer(event.target.value);
+ if (!event.target.value.trim()) setSkillDelivery(false);
+ }}
+ />
+ <p className="muted" id="learning-help">
+ Create this container in your Intelligence project first. New
+ conversations will contribute evidence to it. Leave blank to
+ keep new conversations out of Learning. Existing conversations
+ retain their original assignment.
+ </p>
+ <label className="permission-row">
+ <input
+ type="checkbox"
+ checked={skillDelivery}
+ disabled={!learningContainer.trim()}
+ onChange={(event) => setSkillDelivery(event.target.checked)}
+ />
+ <span>
+ <strong>Use published skills</strong>
+ <small>
+ Load reviewed skills from each conversation’s assigned
+ container. Enable delivery in Intelligence too. Turning this
+ off stops skill loading; it does not stop evidence
+ collection.
+ </small>
+ </span>
+ </label>
+ <a
+ href="https://docs.copilotkit.ai/learning"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Set up Learning and review skills ↗
+ </a>
+ </fieldset>
+ )}
{dialog.type === 'schedule' && (
<>
<label className="field-label" htmlFor="schedule-interval">
diff --git a/src/server/dot-agent.ts b/src/server/dot-agent.ts
index cc2f470..6e334c6 100644
--- a/src/server/dot-agent.ts
+++ b/src/server/dot-agent.ts
@@ -62,7 +62,10 @@ export class DotAgent extends AbstractAgent {
dot.id,
'Slack conversation',
);
- this.workspace.requireThread(input.threadId, dot.id);
+ const conversation = this.workspace.requireThread(
+ input.threadId,
+ dot.id,
+ );
if (
!this.config.intelligenceKey ||
!this.config.apiKey ||
@@ -79,6 +82,8 @@ export class DotAgent extends AbstractAgent {
settings.researchAllowed !== initialSettings.researchAllowed ||
settings.memoryAllowed !== initialSettings.memoryAllowed ||
current.memoryAllowed !== dot.memoryAllowed ||
+ current.learningContainerId !== dot.learningContainerId ||
+ current.skillDeliveryEnabled !== dot.skillDeliveryEnabled ||
current.researchAllowed !== dot.researchAllowed ||
current.spaceId !== dot.spaceId ||
JSON.stringify(current.spaceIds) !== JSON.stringify(dot.spaceIds)
@@ -173,7 +178,18 @@ export class DotAgent extends AbstractAgent {
}).chat(this.config.model);
this.inner = new BuiltInAgent({
model,
- maxSteps: 5,
+ learnedSkills:
+ dot.skillDeliveryEnabled && conversation.learningContainerId
+ ? {
+ containers: [{ id: conversation.learningContainerId }],
+ apiKey: this.config.intelligenceKey,
+ apiUrl: this.config.intelligenceApiUrl,
+ }
+ : undefined,
+ maxSteps:
+ dot.skillDeliveryEnabled && conversation.learningContainerId
+ ? 10
+ : 5,
maxOutputTokens: 2200,
maxRetries: 1,
tools: [
diff --git a/src/server/learning.ts b/src/server/learning.ts
new file mode 100644
index 0000000..c3eeb15
--- /dev/null
+++ b/src/server/learning.ts
@@ -0,0 +1,35 @@
+import type { CopilotKitIntelligence } from '@copilotkit/runtime/v2';
+import type { WorkspaceStore } from './workspace.js';
+
+type Selector = NonNullable<
+ ConstructorParameters<
+ typeof CopilotKitIntelligence
+ >[0]['getLearningContainerId']
+>;
+
+/** Called before execution, including before a new channel thread reaches DotAgent. */
+export function learningSelector(
+ workspace: WorkspaceStore,
+ channelDotId?: string,
+): Selector {
+ return ({ surface, user, agentId, input }) => {
+ if (user?.id !== workspace.ownerId)
+ throw new Error('Conversation learning requires the workspace owner.');
+ if (surface === 'channel') {
+ if (agentId !== channelDotId)
+ throw new Error(
+ 'Conversation learning requires the configured Slack Dot.',
+ );
+ if (
+ !workspace
+ .conversations()
+ .some((thread) => thread.id === input.threadId)
+ )
+ workspace.bindThread(input.threadId, agentId, 'Slack conversation');
+ }
+ return (
+ workspace.requireThread(input.threadId, agentId).learningContainerId ??
+ null
+ );
+ };
+}
diff --git a/src/server/platform.ts b/src/server/platform.ts
index 99325c5..f3a9947 100644
--- a/src/server/platform.ts
+++ b/src/server/platform.ts
@@ -15,6 +15,7 @@ import { DotAgent } from './dot-agent.js';
import { runThreadTurn } from './headless.js';
import { setupStatus, type PlatformConfig } from './platform-config.js';
import { validateRuntimeScope } from './runtime-scope.js';
+import { learningSelector } from './learning.js';
export class Platform {
private channelStartupFailed = false;
readonly pages: PageService;
@@ -40,6 +41,10 @@ export class Platform {
apiKey: config.intelligenceKey,
apiUrl: config.intelligenceApiUrl,
wsUrl: config.intelligenceWsUrl,
+ getLearningContainerId: learningSelector(
+ workspace,
+ config.slackDotId ?? workspace.dots()[0]?.id,
+ ),
});
const channels = [];
if (config.slackChannel && config.slackTeam && config.slackUsers.length) {
diff --git a/src/server/workspace-routes.ts b/src/server/workspace-routes.ts
index 1661aee..82ba5bb 100644
--- a/src/server/workspace-routes.ts
+++ b/src/server/workspace-routes.ts
@@ -3,12 +3,18 @@ import { Hono } from 'hono';
import { z } from 'zod';
import { Platform } from './platform.js';
import { VoiceService } from './voice.js';
+import {
+ learningContainerIdSchema,
+ validateLearningSettings,
+} from '../shared/learning.js';
const dotSchema = z
.object({
name: z.string().trim().min(1).max(40),
instructions: z.string().trim().min(3).max(2000),
researchAllowed: z.boolean(),
memoryAllowed: z.boolean(),
+ learningContainerId: learningContainerIdSchema.optional(),
+ skillDeliveryEnabled: z.boolean().optional(),
spaceIds: z.array(z.string().min(1)).min(1).max(100).optional(),
spaceId: z.string().min(1).optional(),
})
@@ -55,6 +61,22 @@ export function workspaceRoutes(platform: Platform, voice: VoiceService) {
},
400,
);
+ try {
+ validateLearningSettings(
+ data.data.learningContainerId ?? null,
+ data.data.skillDeliveryEnabled ?? false,
+ );
+ } catch (error) {
+ return c.json(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : 'Invalid Learning settings.',
+ },
+ 400,
+ );
+ }
return c.json(
platform.workspace.createDot(
data.data.spaceId,
@@ -63,6 +85,8 @@ export function workspaceRoutes(platform: Platform, voice: VoiceService) {
data.data.researchAllowed,
data.data.memoryAllowed,
data.data.spaceIds,
+ data.data.learningContainerId,
+ data.data.skillDeliveryEnabled,
),
201,
);
@@ -71,6 +95,26 @@ export function workspaceRoutes(platform: Platform, voice: VoiceService) {
const data = dotSchema.safeParse(await c.req.json());
if (!data.success)
return c.json({ error: 'Invalid specialist settings.' }, 400);
+ const current = platform.workspace.dot(c.req.param('id'));
+ if (!current) return c.json({ error: 'Dot not found.' }, 404);
+ try {
+ validateLearningSettings(
+ data.data.learningContainerId === undefined
+ ? (current.learningContainerId ?? null)
+ : data.data.learningContainerId,
+ data.data.skillDeliveryEnabled ?? current.skillDeliveryEnabled ?? false,
+ );
+ } catch (error) {
+ return c.json(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : 'Invalid Learning settings.',
+ },
+ 400,
+ );
+ }
return c.json(platform.workspace.updateDot(c.req.param('id'), data.data));
});
app.post('/conversations', async (c) => {
diff --git a/src/server/workspace.ts b/src/server/workspace.ts
index 40ae878..c2b9a1b 100644
--- a/src/server/workspace.ts
+++ b/src/server/workspace.ts
@@ -4,6 +4,7 @@ import { DatabaseSync } from 'node:sqlite';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { randomUUID } from 'node:crypto';
+import { validateLearningSettings } from '../shared/learning.js';
import type { CallReceipt, Conversation, Dot, Space } from '../shared/types.js';
export class WorkspaceStore {
private db: DatabaseSync;
@@ -22,6 +23,19 @@ export class WorkspaceStore {
CREATE TABLE IF NOT EXISTS task_threads(taskId TEXT PRIMARY KEY, threadId TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS calls(id TEXT PRIMARY KEY, threadId TEXT NOT NULL, startedAt INTEGER NOT NULL, endedAt INTEGER, status TEXT NOT NULL, transcript TEXT NOT NULL, error TEXT);
CREATE TABLE IF NOT EXISTS captures(threadId TEXT PRIMARY KEY, value TEXT NOT NULL);`);
+ for (const [table, column, definition] of [
+ ['dots', 'learningContainerId', 'TEXT'],
+ ['dots', 'skillDeliveryEnabled', 'INTEGER NOT NULL DEFAULT 0'],
+ ['thread_bindings', 'learningContainerId', 'TEXT'],
+ ]) {
+ if (
+ !this.db
+ .prepare(`PRAGMA table_info(${table})`)
+ .all()
+ .some((field) => field.name === column)
+ )
+ this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
+ }
// Migrate only once: restarting must never restore a revoked grant.
if (
!this.db
@@ -94,6 +108,7 @@ export class WorkspaceStore {
.map((grant) => String(grant.spaceId)),
researchAllowed: !!row.researchAllowed,
memoryAllowed: !!row.memoryAllowed,
+ skillDeliveryEnabled: !!row.skillDeliveryEnabled,
})) as unknown as Dot[];
}
dot(id: string) {
@@ -106,8 +121,11 @@ export class WorkspaceStore {
researchAllowed: boolean,
memoryAllowed: boolean,
spaceIds: string[] = [spaceId],
+ learningContainerId: string | null = null,
+ skillDeliveryEnabled = false,
): Dot {
this.validateSpaceAccess(spaceId, spaceIds);
+ validateLearningSettings(learningContainerId, skillDeliveryEnabled);
const dot: Dot = {
id: randomUUID(),
spaceId,
@@ -116,12 +134,16 @@ export class WorkspaceStore {
instructions,
researchAllowed,
memoryAllowed,
+ learningContainerId,
+ skillDeliveryEnabled,
createdAt: Date.now(),
};
this.db.exec('BEGIN');
try {
this.db
- .prepare('INSERT INTO dots VALUES (?, ?, ?, ?, ?, ?, ?)')
+ .prepare(
+ 'INSERT INTO dots (id, spaceId, name, instructions, researchAllowed, memoryAllowed, createdAt, learningContainerId, skillDeliveryEnabled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ )
.run(
dot.id,
spaceId,
@@ -130,6 +152,8 @@ export class WorkspaceStore {
+researchAllowed,
+memoryAllowed,
dot.createdAt,
+ learningContainerId,
+ +skillDeliveryEnabled,
);
for (const id of dot.spaceIds)
this.db.prepare('INSERT INTO dot_spaces VALUES (?, ?)').run(dot.id, id);
@@ -157,24 +181,38 @@ export class WorkspaceStore {
patch: Pick<
Dot,
'name' | 'instructions' | 'researchAllowed' | 'memoryAllowed'
- > & { spaceId?: string; spaceIds?: string[] },
+ > & {
+ spaceId?: string;
+ spaceIds?: string[];
+ learningContainerId?: string | null;
+ skillDeliveryEnabled?: boolean;
+ },
): Dot {
const current = this.dot(id);
if (!current) throw new Error('Dot not found.');
const defaultSpace = patch.spaceId ?? current.spaceId;
const spaceIds = patch.spaceIds ?? current.spaceIds;
this.validateSpaceAccess(defaultSpace, spaceIds);
+ const learningContainerId =
+ patch.learningContainerId === undefined
+ ? (current.learningContainerId ?? null)
+ : patch.learningContainerId;
+ const skillDeliveryEnabled =
+ patch.skillDeliveryEnabled ?? current.skillDeliveryEnabled ?? false;
+ validateLearningSettings(learningContainerId, skillDeliveryEnabled);
this.db.exec('BEGIN');
try {
this.db
.prepare(
- 'UPDATE dots SET name=?, instructions=?, researchAllowed=?, memoryAllowed=? WHERE id=?',
+ 'UPDATE dots SET name=?, instructions=?, researchAllowed=?, memoryAllowed=?, learningContainerId=?, skillDeliveryEnabled=? WHERE id=?',
)
.run(
patch.name,
patch.instructions,
+patch.researchAllowed,
+patch.memoryAllowed,
+ learningContainerId,
+ +skillDeliveryEnabled,
id,
);
this.db
@@ -198,17 +236,28 @@ export class WorkspaceStore {
.all(this.ownerId) as unknown as Conversation[];
}
bindThread(id: string, dotId: string, title: string): Conversation {
- if (!this.dot(dotId)) throw new Error('Dot not found.');
+ const dot = this.dot(dotId);
+ if (!dot) throw new Error('Dot not found.');
const value: Conversation = {
id,
dotId,
ownerId: this.ownerId,
title,
createdAt: Date.now(),
+ learningContainerId: dot.learningContainerId ?? null,
};
this.db
- .prepare('INSERT INTO thread_bindings VALUES (?, ?, ?, ?, ?)')
- .run(id, dotId, this.ownerId, title, value.createdAt);
+ .prepare(
+ 'INSERT INTO thread_bindings (id, dotId, ownerId, title, createdAt, learningContainerId) VALUES (?, ?, ?, ?, ?, ?)',
+ )
+ .run(
+ id,
+ dotId,
+ this.ownerId,
+ title,
+ value.createdAt,
+ value.learningContainerId ?? null,
+ );
return value;
}
requireThread(id: string, dotId?: string): Conversation {
diff --git a/src/shared/learning.ts b/src/shared/learning.ts
new file mode 100644
index 0000000..e5276c1
--- /dev/null
+++ b/src/shared/learning.ts
@@ -0,0 +1,22 @@
+import { z } from 'zod';
+
+export const learningContainerIdSchema = z
+ .string()
+ .max(64)
+ .regex(
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
+ 'Use 1–64 lowercase letters, numbers, and single hyphens.',
+ )
+ .nullable();
+
+export function validateLearningSettings(
+ containerId: string | null,
+ delivery: boolean,
+) {
+ if (!learningContainerIdSchema.safeParse(containerId).success)
+ throw new Error(
+ 'Dot Learning container ID must use 1–64 lowercase letters, numbers, and single hyphens.',
+ );
+ if (delivery && !containerId)
+ throw new Error('Dot skill delivery requires a Learning container.');
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c998224..c87b548 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -79,6 +79,8 @@ export interface Dot {
researchAllowed: boolean;
memoryAllowed: boolean;
createdAt: number;
+ learningContainerId?: string | null;
+ skillDeliveryEnabled?: boolean;
}
export interface Conversation {
id: string;
@@ -86,6 +88,8 @@ export interface Conversation {
ownerId: string;
title: string;
createdAt: number;
+ /** Frozen at creation; null means this conversation does not participate. */
+ learningContainerId?: string | null;
}
export interface CallReceipt {
anchorMessageId?: string | null;
diff --git a/tests/dot-agent-channel.test.ts b/tests/dot-agent-channel.test.ts
index 87eca78..b59403e 100644
--- a/tests/dot-agent-channel.test.ts
+++ b/tests/dot-agent-channel.test.ts
@@ -5,6 +5,14 @@ import { DotAgent } from '../src/server/dot-agent.js';
import { Store } from '../src/server/store.js';
import { WorkspaceStore } from '../src/server/workspace.js';
const inner = vi.hoisted(() => ({
+ configure:
+ vi.fn<
+ (
+ options: ConstructorParameters<
+ typeof import('@copilotkit/runtime/v2').BuiltInAgent
+ >[0],
+ ) => void
+ >(),
run: vi.fn<() => Observable<BaseEvent>>(),
abortRun: vi.fn(),
}));
@@ -14,6 +22,11 @@ vi.mock('@copilotkit/runtime/v2', async (importOriginal) => {
return {
...original,
BuiltInAgent: class {
+ constructor(
+ options: ConstructorParameters<typeof original.BuiltInAgent>[0],
+ ) {
+ inner.configure(options);
+ }
run = inner.run;
abortRun = inner.abortRun;
},
@@ -23,6 +36,56 @@ const databases: Array<{ close(): void }> = [];
afterEach(() => {
databases.splice(0).forEach((db) => db.close());
vi.restoreAllMocks();
+ inner.configure.mockClear();
+});
+
+it('uses the conversation container for delivery and preserves tools and override restrictions', async () => {
+ const f = fixture(false);
+ const dot = f.workspace.dots()[0];
+ f.workspace.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ f.workspace.bindThread('learning', dot.id, 'Learning');
+ f.workspace.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'writing',
+ skillDeliveryEnabled: true,
+ });
+ inner.run.mockReturnValue(of());
+ await lastValueFrom(
+ f.agent.run({ ...f.input, threadId: 'learning' }).pipe(toArray()),
+ );
+ expect(inner.configure).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ learnedSkills: {
+ containers: [{ id: 'research' }],
+ apiKey: 'fixture',
+ apiUrl: undefined,
+ },
+ maxSteps: 10,
+ overridableProperties: [],
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: 'read_space_page' }),
+ ]),
+ }),
+ );
+ await lastValueFrom(f.agent.run(f.input).pipe(toArray()));
+ expect(inner.configure).toHaveBeenLastCalledWith(
+ expect.objectContaining({ learnedSkills: undefined, maxSteps: 5 }),
+ );
+ f.workspace.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'writing',
+ skillDeliveryEnabled: false,
+ });
+ await lastValueFrom(
+ f.agent.run({ ...f.input, threadId: 'learning' }).pipe(toArray()),
+ );
+ expect(inner.configure).toHaveBeenLastCalledWith(
+ expect.objectContaining({ learnedSkills: undefined, maxSteps: 5 }),
+ );
});
function fixture(channel = true) {
const store = new Store(':memory:');
diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md
new file mode 100644
index 0000000..19bc7e7
--- /dev/null
+++ b/tests/fixtures/README.md
@@ -0,0 +1,7 @@
+# Learning delivery fixture
+
+`learning-skills.zip` is a synthetic Intelligence skill snapshot, revision
+`fixture-v1`. It contains `manifest.json` and `evidence-review/SKILL.md`; the
+manifest records the content's size and SHA-256. ZIP entries have fixed timestamps.
+It contains no real conversation data. The native SDK validates this archive in
+the delivery integration test before exposing its catalog and tools to the model.
diff --git a/tests/fixtures/learning-skills.zip b/tests/fixtures/learning-skills.zip
new file mode 100644
index 0000000..7a778d0
Binary files /dev/null and b/tests/fixtures/learning-skills.zip differ
diff --git a/tests/learning-delivery.test.ts b/tests/learning-delivery.test.ts
new file mode 100644
index 0000000..b2ae0ae
--- /dev/null
+++ b/tests/learning-delivery.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import {
+ CopilotKitIntelligence,
+ LearnedSkillsError,
+} from '@copilotkit/runtime/v2';
+import type { RunAgentInput } from '@ag-ui/core';
+import { lastValueFrom, toArray } from 'rxjs';
+import { DotAgent } from '../src/server/dot-agent.js';
+import { Store } from '../src/server/store.js';
+import { WorkspaceStore } from '../src/server/workspace.js';
+
+afterEach(() => vi.restoreAllMocks());
+
+it('native delivery adds a verified published catalog and skill tools to the existing model request', async () => {
+ const store = new Store(':memory:');
+ const workspace = new WorkspaceStore(':memory:', 'owner');
+ try {
+ const dot = workspace.dots()[0];
+ workspace.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ workspace.bindThread('thread', dot.id, 'Learning');
+ const bytes = readFileSync(
+ new URL('./fixtures/learning-skills.zip', import.meta.url),
+ );
+ vi.spyOn(
+ CopilotKitIntelligence.prototype,
+ 'getLearnedSkillsSnapshots',
+ ).mockResolvedValue([
+ {
+ containerId: 'research',
+ status: 'snapshot',
+ bytes,
+ revision: 'fixture-v1',
+ etag: `"${createHash('sha256').update(bytes).digest('hex')}"`,
+ contentType: 'application/zip',
+ },
+ ]);
+ const network = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(
+ new Response(
+ `data: ${JSON.stringify({ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: { role: 'assistant', content: 'Ready to review evidence.' }, finish_reason: null }] })}\n\n` +
+ `data: ${JSON.stringify({ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`,
+ { headers: { 'Content-Type': 'text/event-stream' } },
+ ),
+ );
+ const agent = new DotAgent(
+ store,
+ workspace,
+ {
+ intelligenceKey: 'fixture',
+ apiKey: 'fixture',
+ model: 'fixture',
+ baseUrl: 'https://unused.invalid',
+ runtimeUrl: '',
+ voiceName: 'marin',
+ slackUsers: [],
+ },
+ dot.id,
+ );
+ const events = await lastValueFrom(
+ agent
+ .run({
+ threadId: 'thread',
+ runId: 'run',
+ messages: [
+ { id: 'message', role: 'user', content: 'Review the evidence.' },
+ ],
+ state: {},
+ tools: [],
+ context: [],
+ forwardedProps: {},
+ })
+ .pipe(toArray()),
+ );
+ expect(JSON.stringify(events)).toContain('Ready to review evidence.');
+ expect(network).toHaveBeenCalledTimes(1);
+ const request = String(network.mock.calls[0][1]?.body);
+ expect(request).toContain('evidence-review');
+ expect(request).toContain('copilotkit_load_skill');
+ expect(request).toContain('copilotkit_read_skill_file');
+ expect(request).toContain('read_space_page');
+ expect(request).toContain('Use only the authorized server tools');
+ } finally {
+ workspace.close();
+ store.close();
+ }
+});
+
+it('native skill delivery fails the invocation before contacting the model when delivery is denied', async () => {
+ const store = new Store(':memory:');
+ const workspace = new WorkspaceStore(':memory:', 'owner');
+ try {
+ const dot = workspace.dots()[0];
+ workspace.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ workspace.bindThread('thread', dot.id, 'Learning');
+ const delivery = vi
+ .spyOn(CopilotKitIntelligence.prototype, 'getLearnedSkillsSnapshots')
+ .mockRejectedValue(new LearnedSkillsError('DELIVERY_DISABLED', false));
+ const network = vi
+ .spyOn(globalThis, 'fetch')
+ .mockRejectedValue(new Error('Unexpected network request'));
+ const agent = new DotAgent(
+ store,
+ workspace,
+ {
+ intelligenceKey: 'fixture',
+ apiKey: 'fixture',
+ model: 'fixture',
+ baseUrl: 'https://unused.invalid',
+ runtimeUrl: '',
+ voiceName: 'marin',
+ slackUsers: [],
+ },
+ dot.id,
+ );
+ const input: RunAgentInput = {
+ threadId: 'thread',
+ runId: 'run',
+ messages: [],
+ tools: [],
+ context: [],
+ state: {},
+ forwardedProps: {},
+ };
+ await expect(
+ lastValueFrom(agent.run(input).pipe(toArray())),
+ ).rejects.toMatchObject({ code: 'DELIVERY_DISABLED' });
+ expect(delivery).toHaveBeenCalledWith(
+ expect.objectContaining({ containers: [{ containerId: 'research' }] }),
+ );
+ expect(network).not.toHaveBeenCalled();
+ } finally {
+ workspace.close();
+ store.close();
+ }
+});
diff --git a/tests/learning.test.ts b/tests/learning.test.ts
new file mode 100644
index 0000000..40a19a4
--- /dev/null
+++ b/tests/learning.test.ts
@@ -0,0 +1,166 @@
+import { DatabaseSync } from 'node:sqlite';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, expect, it } from 'vitest';
+import type { RunAgentInput } from '@ag-ui/core';
+import { WorkspaceStore } from '../src/server/workspace.js';
+import { learningSelector } from '../src/server/learning.js';
+
+const cleanup: (() => void)[] = [];
+afterEach(() =>
+ cleanup
+ .splice(0)
+ .reverse()
+ .forEach((fn) => fn()),
+);
+function fixture() {
+ const ws = new WorkspaceStore(':memory:', 'owner');
+ cleanup.push(() => ws.close());
+ const dot = ws.dots()[0];
+ return { ws, dot };
+}
+const input = (threadId: string): RunAgentInput => ({
+ threadId,
+ runId: 'run',
+ state: {},
+ messages: [],
+ tools: [],
+ context: [],
+ forwardedProps: {},
+});
+
+it('freezes container assignments, including disabled conversations, when a Dot changes', () => {
+ const { ws, dot } = fixture();
+ ws.bindThread('disabled', dot.id, 'Before learning');
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ ws.bindThread('research', dot.id, 'Research');
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'writing',
+ skillDeliveryEnabled: true,
+ });
+ ws.bindThread('writing', dot.id, 'Writing');
+ expect(ws.requireThread('disabled').learningContainerId).toBeNull();
+ expect(ws.requireThread('research').learningContainerId).toBe('research');
+ expect(ws.requireThread('writing').learningContainerId).toBe('writing');
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: null,
+ skillDeliveryEnabled: false,
+ });
+ expect(ws.requireThread('research').learningContainerId).toBe('research');
+});
+
+it('migrates legacy threads without enrolling them and persists configuration across restart', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'opendots-learning-'));
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
+ const path = join(dir, 'workspace.sqlite');
+ const legacy = new DatabaseSync(path);
+ legacy.exec(`CREATE TABLE thread_bindings(id TEXT PRIMARY KEY, dotId TEXT NOT NULL, ownerId TEXT NOT NULL, title TEXT NOT NULL, createdAt INTEGER NOT NULL);
+ INSERT INTO thread_bindings VALUES ('old', 'dot', 'owner', 'Existing', 1);`);
+ legacy.close();
+ const ws = new WorkspaceStore(path, 'owner');
+ const dot = ws.dots()[0];
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ ws.bindThread('new', dot.id, 'New');
+ ws.close();
+ const reopened = new WorkspaceStore(path, 'owner');
+ cleanup.push(() => reopened.close());
+ expect(reopened.requireThread('old').learningContainerId).toBeNull();
+ expect(reopened.requireThread('new').learningContainerId).toBe('research');
+ expect(reopened.dot(dot.id)).toMatchObject({
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+});
+
+it('selects only owned web threads and binds the configured channel Dot before its first run', () => {
+ const { ws, dot } = fixture();
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ ws.bindThread('web', dot.id, 'Web');
+ const select = learningSelector(ws, dot.id);
+ const user = { id: 'owner', name: 'Owner' };
+ expect(
+ select({ surface: 'web', user, agentId: dot.id, input: input('web') }),
+ ).toBe('research');
+ expect(() =>
+ select({ surface: 'web', user, agentId: dot.id, input: input('unknown') }),
+ ).toThrow();
+ expect(
+ select({
+ surface: 'channel',
+ user,
+ agentId: dot.id,
+ input: input('slack'),
+ }),
+ ).toBe('research');
+ expect(ws.requireThread('slack', dot.id).learningContainerId).toBe(
+ 'research',
+ );
+ expect(() =>
+ select({
+ surface: 'channel',
+ user: null,
+ agentId: dot.id,
+ input: input('unauthorized'),
+ }),
+ ).toThrow();
+ expect(() =>
+ select({
+ surface: 'web',
+ user: { id: 'other', name: 'Other' },
+ agentId: dot.id,
+ input: input('web'),
+ }),
+ ).toThrow();
+ const other = ws.createDot(dot.spaceId, 'Other', 'Other role', true, true);
+ expect(() =>
+ select({
+ surface: 'channel',
+ user,
+ agentId: other.id,
+ input: input('wrong-dot'),
+ }),
+ ).toThrow();
+ expect(() =>
+ select({ surface: 'web', user, agentId: other.id, input: input('web') }),
+ ).toThrow();
+ expect(ws.conversations()).toHaveLength(2);
+});
+
+it('rejects invalid container IDs and delivery without a container', () => {
+ const { ws, dot } = fixture();
+ for (const learningContainerId of [
+ '',
+ 'Upper',
+ 'two--hyphens',
+ '-leading',
+ 'trailing-',
+ 'a'.repeat(65),
+ ]) {
+ expect(() =>
+ ws.updateDot(dot.id, { ...dot, learningContainerId }),
+ ).toThrow();
+ }
+ expect(() =>
+ ws.updateDot(dot.id, {
+ ...dot,
+ learningContainerId: null,
+ skillDeliveryEnabled: true,
+ }),
+ ).toThrow();
+ expect(ws.dot(dot.id)?.learningContainerId).toBeNull();
+});
diff --git a/tests/page-routes.test.ts b/tests/page-routes.test.ts
index f1d7877..841710c 100644
--- a/tests/page-routes.test.ts
+++ b/tests/page-routes.test.ts
@@ -36,6 +36,60 @@ const request = (body: unknown, method = 'POST') => ({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
+
+it('saves Learning settings through the owner API and rejects malformed container IDs', async () => {
+ const { ws, app } = fixture();
+ const dot = ws.dots()[0];
+ const body = {
+ name: dot.name,
+ instructions: dot.instructions,
+ researchAllowed: true,
+ memoryAllowed: true,
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ };
+ expect(
+ (await app.request(`/api/dots/${dot.id}`, request(body, 'PUT'))).status,
+ ).toBe(200);
+ expect(ws.dot(dot.id)).toMatchObject({
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ expect(
+ (
+ await app.request(
+ `/api/dots/${dot.id}`,
+ request({ ...body, learningContainerId: 'bad--id' }, 'PUT'),
+ )
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await app.request(
+ `/api/dots/${dot.id}`,
+ request({ ...body, learningContainerId: null }, 'PUT'),
+ )
+ ).status,
+ ).toBe(400);
+ const created = await app.request(
+ '/api/dots',
+ request({ ...body, spaceId: dot.spaceId }),
+ );
+ expect(created.status).toBe(201);
+ expect(await created.json()).toMatchObject({
+ learningContainerId: 'research',
+ skillDeliveryEnabled: true,
+ });
+ const privateApp = fixture('owner-secret');
+ expect(
+ (
+ await privateApp.app.request(
+ `/api/dots/${privateApp.ws.dots()[0].id}`,
+ request(body, 'PUT'),
+ )
+ ).status,
+ ).toBe(401);
+});
it('supports manual pages without credentials and returns validation, scope and conflict statuses', async () => {
const { ws, app } = fixture();
const space = ws.spaces()[0].id;