+
+ )
+}
+
+export const PromptBlockExtension = Node.create({
+ name: 'promptBlock',
+ group: 'block',
+ atom: true,
+ selectable: true,
+ draggable: false,
+
+ addOptions() {
+ return {
+ notePath: undefined as string | undefined,
+ }
+ },
+
+ addAttributes() {
+ return {
+ data: {
+ default: '',
+ },
+ }
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: 'pre',
+ priority: 60,
+ getAttrs(element) {
+ const code = element.querySelector('code')
+ if (!code) return false
+ const cls = code.className || ''
+ if (cls.includes('language-prompt')) {
+ return { data: code.textContent || '' }
+ }
+ return false
+ },
+ },
+ ]
+ },
+
+ renderHTML({ HTMLAttributes }: { HTMLAttributes: Record }) {
+ return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'prompt-block' })]
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(PromptBlockView)
+ },
+
+ addStorage() {
+ return {
+ markdown: {
+ serialize(state: { write: (text: string) => void; closeBlock: (node: unknown) => void }, node: { attrs: { data: string } }) {
+ state.write('```prompt\n' + node.attrs.data + '\n```')
+ state.closeBlock(node)
+ },
+ parse: {
+ // handled by parseHTML
+ },
+ },
+ }
+ },
+})
diff --git a/apps/x/apps/renderer/src/extensions/track-block.tsx b/apps/x/apps/renderer/src/extensions/track-block.tsx
index c0704906..a87decc8 100644
--- a/apps/x/apps/renderer/src/extensions/track-block.tsx
+++ b/apps/x/apps/renderer/src/extensions/track-block.tsx
@@ -36,11 +36,12 @@ function TrackBlockView({ node, deleteNode, extension }: {
extension: { options: { notePath?: string } }
}) {
const raw = node.attrs.data as string
+ const cleaned = raw.replace(/[\u200B-\u200D\uFEFF]/g, "");
const track = useMemo | null>(() => {
try {
- return TrackBlockSchema.parse(parseYaml(raw))
- } catch { return null }
+ return TrackBlockSchema.parse(parseYaml(cleaned))
+ } catch(error) { console.error('error', error); return null }
}, [raw]) as z.infer | null;
const trackId = track?.trackId ?? ''
diff --git a/apps/x/apps/renderer/src/styles/editor.css b/apps/x/apps/renderer/src/styles/editor.css
index 2083f4b0..ca935a14 100644
--- a/apps/x/apps/renderer/src/styles/editor.css
+++ b/apps/x/apps/renderer/src/styles/editor.css
@@ -146,6 +146,48 @@
color: #eb5757;
}
+/* Native GFM tables (distinct from the custom tableBlock above) */
+.tiptap-editor .ProseMirror .tableWrapper {
+ overflow-x: auto;
+ margin: 8px 0;
+}
+
+.tiptap-editor .ProseMirror table {
+ width: 100%;
+ border-collapse: collapse;
+ table-layout: fixed;
+ font-size: 13px;
+ margin: 8px 0;
+}
+
+.tiptap-editor .ProseMirror table th,
+.tiptap-editor .ProseMirror table td {
+ border: 1px solid var(--border);
+ padding: 6px 10px;
+ vertical-align: top;
+ box-sizing: border-box;
+ position: relative;
+ min-width: 60px;
+}
+
+.tiptap-editor .ProseMirror table th {
+ background: color-mix(in srgb, var(--foreground) 4%, transparent);
+ font-weight: 600;
+ text-align: left;
+}
+
+.tiptap-editor .ProseMirror table p {
+ margin: 0;
+}
+
+.tiptap-editor .ProseMirror table .selectedCell::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: color-mix(in srgb, var(--foreground) 8%, transparent);
+ pointer-events: none;
+}
+
/* Divider */
.tiptap-editor .ProseMirror hr {
border: none;
@@ -764,6 +806,7 @@
/* Shared block styles (image, embed, chart, table) */
.tiptap-editor .ProseMirror .image-block-wrapper,
.tiptap-editor .ProseMirror .embed-block-wrapper,
+.tiptap-editor .ProseMirror .iframe-block-wrapper,
.tiptap-editor .ProseMirror .chart-block-wrapper,
.tiptap-editor .ProseMirror .table-block-wrapper,
.tiptap-editor .ProseMirror .calendar-block-wrapper,
@@ -775,6 +818,7 @@
.tiptap-editor .ProseMirror .image-block-card,
.tiptap-editor .ProseMirror .embed-block-card,
+.tiptap-editor .ProseMirror .iframe-block-card,
.tiptap-editor .ProseMirror .chart-block-card,
.tiptap-editor .ProseMirror .table-block-card,
.tiptap-editor .ProseMirror .calendar-block-card,
@@ -793,6 +837,7 @@
.tiptap-editor .ProseMirror .image-block-card:hover,
.tiptap-editor .ProseMirror .embed-block-card:hover,
+.tiptap-editor .ProseMirror .iframe-block-card:hover,
.tiptap-editor .ProseMirror .chart-block-card:hover,
.tiptap-editor .ProseMirror .table-block-card:hover,
.tiptap-editor .ProseMirror .calendar-block-card:hover,
@@ -805,6 +850,7 @@
.tiptap-editor .ProseMirror .image-block-wrapper.ProseMirror-selectednode .image-block-card,
.tiptap-editor .ProseMirror .embed-block-wrapper.ProseMirror-selectednode .embed-block-card,
+.tiptap-editor .ProseMirror .iframe-block-wrapper.ProseMirror-selectednode .iframe-block-card,
.tiptap-editor .ProseMirror .chart-block-wrapper.ProseMirror-selectednode .chart-block-card,
.tiptap-editor .ProseMirror .table-block-wrapper.ProseMirror-selectednode .table-block-card,
.tiptap-editor .ProseMirror .calendar-block-wrapper.ProseMirror-selectednode .calendar-block-card,
@@ -817,6 +863,7 @@
.tiptap-editor .ProseMirror .image-block-delete,
.tiptap-editor .ProseMirror .embed-block-delete,
+.tiptap-editor .ProseMirror .iframe-block-delete,
.tiptap-editor .ProseMirror .chart-block-delete,
.tiptap-editor .ProseMirror .table-block-delete,
.tiptap-editor .ProseMirror .calendar-block-delete,
@@ -843,6 +890,7 @@
.tiptap-editor .ProseMirror .image-block-card:hover .image-block-delete,
.tiptap-editor .ProseMirror .embed-block-card:hover .embed-block-delete,
+.tiptap-editor .ProseMirror .iframe-block-card:hover .iframe-block-delete,
.tiptap-editor .ProseMirror .chart-block-card:hover .chart-block-delete,
.tiptap-editor .ProseMirror .table-block-card:hover .table-block-delete,
.tiptap-editor .ProseMirror .calendar-block-card:hover .calendar-block-delete,
@@ -854,6 +902,7 @@
.tiptap-editor .ProseMirror .image-block-delete:hover,
.tiptap-editor .ProseMirror .embed-block-delete:hover,
+.tiptap-editor .ProseMirror .iframe-block-delete:hover,
.tiptap-editor .ProseMirror .chart-block-delete:hover,
.tiptap-editor .ProseMirror .table-block-delete:hover,
.tiptap-editor .ProseMirror .calendar-block-delete:hover,
@@ -943,6 +992,103 @@
font-size: 13px;
}
+/* Iframe block */
+.tiptap-editor .ProseMirror .iframe-block-card {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--foreground);
+ padding-right: 28px;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-frame-shell {
+ position: relative;
+ width: 100%;
+ min-height: 240px;
+ border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);
+ border-radius: 12px;
+ overflow: hidden;
+ transition: height 0.18s ease;
+ background:
+ radial-gradient(circle at top left, color-mix(in srgb, var(--primary) 14%, transparent), transparent 45%),
+ linear-gradient(180deg, color-mix(in srgb, var(--muted) 65%, transparent), color-mix(in srgb, var(--background) 95%, transparent));
+}
+
+.tiptap-editor .ProseMirror .iframe-block-loading-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ background:
+ radial-gradient(circle at top left, color-mix(in srgb, var(--primary) 10%, transparent), transparent 42%),
+ linear-gradient(180deg, color-mix(in srgb, var(--muted) 88%, transparent), color-mix(in srgb, var(--background) 98%, transparent));
+ color: color-mix(in srgb, var(--foreground) 60%, transparent);
+ pointer-events: none;
+ opacity: 1;
+ transition: opacity 0.18s ease;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-loading-bar {
+ width: min(220px, 46%);
+ height: 7px;
+ border-radius: 999px;
+ background:
+ linear-gradient(90deg, transparent 0%, color-mix(in srgb, var(--primary) 60%, transparent) 50%, transparent 100%),
+ color-mix(in srgb, var(--foreground) 8%, transparent);
+ background-size: 180px 100%, auto;
+ background-repeat: no-repeat;
+ animation: iframe-block-loading-sweep 1.05s linear infinite;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-loading-copy {
+ font-size: 12px;
+ font-weight: 500;
+ letter-spacing: 0.01em;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-frame-shell-ready .iframe-block-loading-overlay {
+ opacity: 0;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-frame {
+ width: 100%;
+ height: 100%;
+ border: none;
+ background: #fff;
+ opacity: 1;
+ transition: opacity 0.18s ease;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-frame-shell-loading .iframe-block-frame {
+ opacity: 0;
+}
+
+.tiptap-editor .ProseMirror .iframe-block-error {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: color-mix(in srgb, var(--foreground) 55%, transparent);
+ font-size: 13px;
+}
+
+@keyframes iframe-block-loading-sweep {
+ from {
+ background-position: -180px 0, 0 0;
+ }
+ to {
+ background-position: calc(100% + 180px) 0, 0 0;
+ }
+}
+
/* Chart block */
.tiptap-editor .ProseMirror .chart-block-title {
font-size: 14px;
diff --git a/apps/x/packages/core/src/agent-schedule/runner.ts b/apps/x/packages/core/src/agent-schedule/runner.ts
index 4eab6081..5fca6878 100644
--- a/apps/x/packages/core/src/agent-schedule/runner.ts
+++ b/apps/x/packages/core/src/agent-schedule/runner.ts
@@ -8,6 +8,7 @@ import { IMonotonicallyIncreasingIdGenerator } from "../application/lib/id-gen.j
import { AgentScheduleConfig, AgentScheduleEntry } from "@x/shared/dist/agent-schedule.js";
import { AgentScheduleState, AgentScheduleStateEntry } from "@x/shared/dist/agent-schedule-state.js";
import { MessageEvent } from "@x/shared/dist/runs.js";
+import { createRun } from "../runs/runs.js";
import z from "zod";
const DEFAULT_STARTING_MESSAGE = "go";
@@ -162,8 +163,8 @@ async function runAgent(
});
try {
- // Create a new run
- const run = await runsRepo.create({ agentId: agentName });
+ // Create a new run via core (resolves agent + default model+provider).
+ const run = await createRun({ agentId: agentName });
console.log(`[AgentRunner] Created run ${run.id} for agent ${agentName}`);
// Add the starting message as a user message
diff --git a/apps/x/packages/core/src/agents/runtime.ts b/apps/x/packages/core/src/agents/runtime.ts
index 507bd0c7..6c84ac8b 100644
--- a/apps/x/packages/core/src/agents/runtime.ts
+++ b/apps/x/packages/core/src/agents/runtime.ts
@@ -16,8 +16,7 @@ import { isBlocked, extractCommandNames } from "../application/lib/command-execu
import container from "../di/container.js";
import { IModelConfigRepo } from "../models/repo.js";
import { createProvider } from "../models/models.js";
-import { isSignedIn } from "../account/account.js";
-import { getGatewayProvider } from "../models/gateway.js";
+import { resolveProviderConfig } from "../models/defaults.js";
import { IAgentsRepo } from "./repo.js";
import { IMonotonicallyIncreasingIdGenerator } from "../application/lib/id-gen.js";
import { IBus } from "../application/lib/bus.js";
@@ -194,6 +193,19 @@ export class AgentRuntime implements IAgentRuntime {
await this.runsRepo.appendEvents(runId, [stoppedEvent]);
await this.bus.publish(stoppedEvent);
}
+ } catch (error) {
+ console.error(`Run ${runId} failed:`, error);
+ const message = error instanceof Error
+ ? (error.stack || error.message || error.name)
+ : typeof error === "string" ? error : JSON.stringify(error);
+ const errorEvent: z.infer = {
+ runId,
+ type: "error",
+ error: message,
+ subflow: [],
+ };
+ await this.runsRepo.appendEvents(runId, [errorEvent]);
+ await this.bus.publish(errorEvent);
} finally {
this.abortRegistry.cleanup(runId);
await this.runsLock.release(runId);
@@ -636,6 +648,8 @@ export class AgentState {
runId: string | null = null;
agent: z.infer | null = null;
agentName: string | null = null;
+ runModel: string | null = null;
+ runProvider: string | null = null;
messages: z.infer = [];
lastAssistantMsg: z.infer | null = null;
subflowStates: Record = {};
@@ -749,13 +763,18 @@ export class AgentState {
case "start":
this.runId = event.runId;
this.agentName = event.agentName;
+ this.runModel = event.model;
+ this.runProvider = event.provider;
break;
case "spawn-subflow":
// Seed the subflow state with its agent so downstream loadAgent works.
+ // Subflows inherit the parent run's model+provider — there's one pair per run.
if (!this.subflowStates[event.toolCallId]) {
this.subflowStates[event.toolCallId] = new AgentState();
}
this.subflowStates[event.toolCallId].agentName = event.agentName;
+ this.subflowStates[event.toolCallId].runModel = this.runModel;
+ this.subflowStates[event.toolCallId].runProvider = this.runProvider;
break;
case "message":
this.messages.push(event.message);
@@ -844,40 +863,32 @@ export async function* streamAgent({
yield event;
}
- const modelConfig = await modelConfigRepo.getConfig();
- if (!modelConfig) {
- throw new Error("Model config not found");
- }
-
// set up agent
const agent = await loadAgent(state.agentName!);
// set up tools
const tools = await buildTools(agent);
- // set up provider + model
- const signedIn = await isSignedIn();
- const provider = signedIn
- ? await getGatewayProvider()
- : createProvider(modelConfig.provider);
- const knowledgeGraphAgents = ["note_creation", "email-draft", "meeting-prep", "labeling_agent", "note_tagging_agent", "agent_notes_agent"];
- const isKgAgent = knowledgeGraphAgents.includes(state.agentName!);
- const isInlineTaskAgent = state.agentName === "inline_task_agent";
- const defaultModel = signedIn ? "gpt-5.4" : modelConfig.model;
- const defaultKgModel = signedIn ? "anthropic/claude-haiku-4.5" : defaultModel;
- const defaultInlineTaskModel = signedIn ? "anthropic/claude-sonnet-4.6" : defaultModel;
- const modelId = isInlineTaskAgent
- ? defaultInlineTaskModel
- : (isKgAgent && modelConfig.knowledgeGraphModel)
- ? modelConfig.knowledgeGraphModel
- : isKgAgent ? defaultKgModel : defaultModel;
+ // model+provider were resolved and frozen on the run at runs:create time.
+ // Look up the named provider's current credentials from models.json and
+ // instantiate the LLM client. No selection happens here.
+ if (!state.runModel || !state.runProvider) {
+ throw new Error(`Run ${runId} is missing model/provider on its start event`);
+ }
+ const modelId = state.runModel;
+ const providerConfig = await resolveProviderConfig(state.runProvider);
+ const provider = createProvider(providerConfig);
const model = provider.languageModel(modelId);
- logger.log(`using model: ${modelId}`);
+ logger.log(`using model: ${modelId} (provider: ${state.runProvider})`);
let loopCounter = 0;
let voiceInput = false;
let voiceOutput: 'summary' | 'full' | null = null;
let searchEnabled = false;
+ let middlePaneContext:
+ | { kind: 'note'; path: string; content: string }
+ | { kind: 'browser'; url: string; title: string }
+ | null = null;
while (true) {
// Check abort at the top of each iteration
signal.throwIfAborted();
@@ -938,27 +949,40 @@ export async function* streamAgent({
subflow: [],
});
let result: unknown = null;
- if (agent.tools![toolCall.toolName].type === "agent") {
- const subflowState = state.subflowStates[toolCallId];
- for await (const event of streamAgent({
- state: subflowState,
- idGenerator,
- runId,
- messageQueue,
- modelConfigRepo,
- signal,
- abortRegistry,
- })) {
- yield* processEvent({
- ...event,
- subflow: [toolCallId, ...event.subflow],
- });
+ try {
+ if (agent.tools![toolCall.toolName].type === "agent") {
+ const subflowState = state.subflowStates[toolCallId];
+ for await (const event of streamAgent({
+ state: subflowState,
+ idGenerator,
+ runId,
+ messageQueue,
+ modelConfigRepo,
+ signal,
+ abortRegistry,
+ })) {
+ yield* processEvent({
+ ...event,
+ subflow: [toolCallId, ...event.subflow],
+ });
+ }
+ if (!subflowState.getPendingAskHumans().length && !subflowState.getPendingPermissions().length) {
+ result = subflowState.finalResponse();
+ }
+ } else {
+ result = await execTool(agent.tools![toolCall.toolName], toolCall.arguments, { runId, signal, abortRegistry });
}
- if (!subflowState.getPendingAskHumans().length && !subflowState.getPendingPermissions().length) {
- result = subflowState.finalResponse();
+ } catch (error) {
+ if ((error instanceof Error && error.name === "AbortError") || signal.aborted) {
+ throw error;
}
- } else {
- result = await execTool(agent.tools![toolCall.toolName], toolCall.arguments, { runId, signal, abortRegistry });
+ const message = error instanceof Error ? (error.message || error.name) : String(error);
+ _logger.log('tool failed', message);
+ result = {
+ success: false,
+ error: message,
+ toolName: toolCall.toolName,
+ };
}
const resultPayload = result === undefined ? null : result;
const resultMsg: z.infer = {
@@ -1005,6 +1029,9 @@ export async function* streamAgent({
if (msg.voiceOutput) {
voiceOutput = msg.voiceOutput;
}
+ // Middle pane is NOT sticky — it should reflect the state at the moment of the
+ // latest user message. If the user closed the pane between messages, clear it.
+ middlePaneContext = msg.middlePaneContext ?? null;
loopLogger.log('dequeued user message', msg.messageId);
yield* processEvent({
runId,
@@ -1051,6 +1078,19 @@ export async function* streamAgent({
if (agentNotesContext) {
instructionsWithDateTime += `\n\n${agentNotesContext}`;
}
+ // Always inject a Middle Pane section so the LLM has a clear, up-to-date signal
+ // that supersedes any earlier middle-pane mention in the conversation history.
+ const middlePaneHeader = `\n\n# Middle Pane (Current State)\nThis section reflects what the user has open in the middle pane RIGHT NOW, at the time of their latest message. **This is authoritative and overrides any earlier mention of a note or web page in this conversation** — if the conversation history references a different note or browser page, the user has since closed or navigated away from it. Do not treat earlier context as current.\n\n`;
+ if (!middlePaneContext) {
+ loopLogger.log('injecting middle pane context (empty)');
+ instructionsWithDateTime += `${middlePaneHeader}**Nothing relevant is open in the middle pane right now.** The user is not looking at any note or web page. If earlier in this conversation you referenced a note or browser page as "what the user is viewing", that is no longer accurate — do not refer to it as currently open. Answer the user's latest message on its own merits.`;
+ } else if (middlePaneContext.kind === 'note') {
+ loopLogger.log('injecting middle pane context (note)', middlePaneContext.path);
+ instructionsWithDateTime += `${middlePaneHeader}The user has a note open. Its path and full content are provided below so you can reference it when relevant.\n\n**How to use this context:**\n- The user may or may not be talking about this note. Do NOT assume every message is about it.\n- Only reference or act on this note when the user's message clearly relates to it (e.g. "this note", "what I'm looking at", "here", "above", "below", or questions whose subject is plainly this note's content).\n- For unrelated questions (general chat, questions about other notes, tasks, emails, calendar, etc.), ignore this context entirely and answer normally.\n- Do not mention that you can see this note unless it is relevant to the answer.\n\n## Open note path\n${middlePaneContext.path}\n\n## Open note content\n\`\`\`\n${middlePaneContext.content}\n\`\`\``;
+ } else if (middlePaneContext.kind === 'browser') {
+ loopLogger.log('injecting middle pane context (browser)', middlePaneContext.url);
+ instructionsWithDateTime += `${middlePaneHeader}The user has the embedded browser open and is viewing a web page. Only the URL and page title are shown below — the page content itself is NOT included here. If you need the page content to answer, use the browser tools available to you to read the page.\n\n**How to use this context:**\n- The user may or may not be talking about this page. Do NOT assume every message is about it.\n- Only reference or act on this page when the user's message clearly relates to it (e.g. "this page", "this article", "what I'm looking at", "this site", "summarize this").\n- For unrelated questions (general chat, questions about other notes, tasks, emails, calendar, etc.), ignore this context entirely and answer normally.\n- Do not mention that you can see the browser unless it is relevant to the answer.\n\n## Current page\nURL: ${middlePaneContext.url}\nTitle: ${middlePaneContext.title}`;
+ }
}
if (voiceInput) {
loopLogger.log('voice input enabled, injecting voice input prompt');
diff --git a/apps/x/packages/core/src/application/assistant/instructions.ts b/apps/x/packages/core/src/application/assistant/instructions.ts
index 32d22fd9..af2d7a20 100644
--- a/apps/x/packages/core/src/application/assistant/instructions.ts
+++ b/apps/x/packages/core/src/application/assistant/instructions.ts
@@ -1,4 +1,4 @@
-import { skillCatalog } from "./skills/index.js"; // eslint-disable-line @typescript-eslint/no-unused-vars -- used in template literal
+import { skillCatalog, buildSkillCatalog } from "./skills/index.js";
import { getRuntimeContext, getRuntimeContextPrompt } from "./runtime-context.js";
import { composioAccountsRepo } from "../../composio/repo.js";
import { isConfigured as isComposioConfigured } from "../../composio/client.js";
@@ -12,15 +12,7 @@ const runtimeContextPrompt = getRuntimeContextPrompt(getRuntimeContext());
*/
async function getComposioToolsPrompt(): Promise {
if (!(await isComposioConfigured())) {
- return `
-## Composio Integrations
-
-**Composio is not configured.** Composio enables integrations with third-party services like Google Sheets, GitHub, Slack, Jira, Notion, LinkedIn, and 20+ others.
-
-When the user asks to interact with any third-party service (e.g., "connect to Google Sheets", "create a GitHub issue"), do NOT attempt to write code, use shell commands, or load the composio-integration skill. Instead, let the user know that these integrations are available through Composio, and they can enable them by adding their Composio API key in **Settings > Tools Library**. They can get their key from https://app.composio.dev/settings.
-
-**Exception — Email and Calendar:** For email-related requests (reading emails, sending emails, drafting replies) or calendar-related requests (checking schedule, listing events), do NOT direct the user to Composio. Instead, tell them to connect their email and calendar in **Settings > Connected Accounts**.
-`;
+ return '';
}
const connectedToolkits = composioAccountsRepo.getConnectedToolkits();
@@ -37,7 +29,29 @@ Load the \`composio-integration\` skill when the user asks to interact with any
`;
}
-export const CopilotInstructions = `You are Rowboat Copilot - an AI assistant for everyday work. You help users with anything they want. For instance, drafting emails, prepping for meetings, tracking projects, or answering questions - with memory that compounds from their emails, calendar, and notes. Everything runs locally on the user's machine. The nerdy coworker who remembers everything.
+function buildStaticInstructions(composioEnabled: boolean, catalog: string): string {
+ // Conditionally include Composio-related instruction sections
+ const emailDraftSuffix = composioEnabled
+ ? ` Do NOT load this skill for reading, fetching, or checking emails — use the \`composio-integration\` skill for that instead.`
+ : ` Do NOT load this skill for reading, fetching, or checking emails.`;
+
+ const thirdPartyBlock = composioEnabled
+ ? `\n**Third-Party Services:** When users ask to interact with any external service (Gmail, GitHub, Slack, LinkedIn, Notion, Google Sheets, Jira, etc.) — reading emails, listing issues, sending messages, fetching profiles — load the \`composio-integration\` skill first. Do NOT look in local \`gmail_sync/\` or \`calendar_sync/\` folders for live data.\n`
+ : '';
+
+ const toolPriority = composioEnabled
+ ? `For third-party services (GitHub, Gmail, Slack, etc.), load the \`composio-integration\` skill. For capabilities Composio doesn't cover (web search, file scraping, audio), use MCP tools via the \`mcp-integration\` skill.`
+ : `For capabilities like web search, file scraping, and audio, use MCP tools via the \`mcp-integration\` skill.`;
+
+ const slackToolsLine = composioEnabled
+ ? `- \`slack-checkConnection\`, \`slack-listAvailableTools\`, \`slack-executeAction\` - Slack integration (requires Slack to be connected via Composio). Use \`slack-listAvailableTools\` first to discover available tool slugs, then \`slack-executeAction\` to execute them.\n`
+ : '';
+
+ const composioToolsLine = composioEnabled
+ ? `- \`composio-list-toolkits\`, \`composio-search-tools\`, \`composio-execute-tool\`, \`composio-connect-toolkit\` — Composio integration tools. Load the \`composio-integration\` skill for usage guidance.\n`
+ : '';
+
+ return `You are Rowboat Copilot - an AI assistant for everyday work. You help users with anything they want. For instance, drafting emails, prepping for meetings, tracking projects, or answering questions - with memory that compounds from their emails, calendar, and notes. Everything runs locally on the user's machine. The nerdy coworker who remembers everything.
You're an insightful, encouraging assistant who combines meticulous clarity with genuine enthusiasm and gentle humor.
@@ -58,11 +72,9 @@ You're an insightful, encouraging assistant who combines meticulous clarity with
## What Rowboat Is
Rowboat is an agentic assistant for everyday work - emails, meetings, projects, and people. Users give you tasks like "draft a follow-up email," "prep me for this meeting," or "summarize where we are with this project." You figure out what context you need, pull from emails and meetings, and get it done.
-**Email Drafting:** When users ask you to **draft** or **compose** emails (e.g., "draft a follow-up to Monica", "write an email to John about the project"), load the \`draft-emails\` skill first. Do NOT load this skill for reading, fetching, or checking emails — use the \`composio-integration\` skill for that instead.
+**Email Drafting:** When users ask you to **draft** or **compose** emails (e.g., "draft a follow-up to Monica", "write an email to John about the project"), load the \`draft-emails\` skill first.${emailDraftSuffix}
-**Third-Party Services:** When users ask to interact with any external service (Gmail, GitHub, Slack, LinkedIn, Notion, Google Sheets, Jira, etc.) — reading emails, listing issues, sending messages, fetching profiles — load the \`composio-integration\` skill first. Do NOT look in local \`gmail_sync/\` or \`calendar_sync/\` folders for live data.
-
-**Meeting Prep:** When users ask you to prepare for a meeting, prep for a call, or brief them on attendees, load the \`meeting-prep\` skill first. It provides structured guidance for gathering context about attendees from the knowledge base and creating useful meeting briefs.
+${thirdPartyBlock}**Meeting Prep:** When users ask you to prepare for a meeting, prep for a call, or brief them on attendees, load the \`meeting-prep\` skill first. It provides structured guidance for gathering context about attendees from the knowledge base and creating useful meeting briefs.
**Create Presentations:** When users ask you to create a presentation, slide deck, pitch deck, or PDF slides, load the \`create-presentations\` skill first. It provides structured guidance for generating PDF presentations using context from the knowledge base.
@@ -104,7 +116,8 @@ Unlike other AI assistants that start cold every session, you have access to a l
When a user asks you to prep them for a call with someone, you already know every prior decision, concerns they've raised, and commitments on both sides - because memory has been accumulating across every email and call, not reconstructed on demand.
## The Knowledge Graph
-The knowledge graph is stored as plain markdown with Obsidian-style backlinks in \`knowledge/\` (inside the workspace). The folder is organized into four categories:
+The knowledge graph is stored as plain markdown with Obsidian-style backlinks in \`knowledge/\` (inside the workspace). The folder is organized into these categories:
+- **Notes/** - Default location for user-authored notes. Create new notes here unless the user specifies a different folder.
- **People/** - Notes on individuals, tracking relationships, decisions, and commitments
- **Organizations/** - Notes on companies and teams
- **Projects/** - Notes on ongoing initiatives and workstreams
@@ -178,7 +191,7 @@ Use the catalog below to decide which skills to load for each user request. Befo
- Call the \`loadSkill\` tool with the skill's name or path so you can read its guidance string.
- Apply the instructions from every loaded skill while working on the request.
-\${skillCatalog}
+${catalog}
Always consult this catalog first so you load the right skills before taking action.
@@ -205,7 +218,7 @@ Always consult this catalog first so you load the right skills before taking act
## Tool Priority
-For third-party services (GitHub, Gmail, Slack, etc.), load the \`composio-integration\` skill. For capabilities Composio doesn't cover (web search, file scraping, audio), use MCP tools via the \`mcp-integration\` skill.
+${toolPriority}
## Execution Reminders
- Explore existing files and structure before creating new assets.
@@ -241,12 +254,11 @@ ${runtimeContextPrompt}
- \`analyzeAgent\` - Agent analysis
- \`addMcpServer\`, \`listMcpServers\`, \`listMcpTools\`, \`executeMcpTool\` - MCP server management and execution
- \`loadSkill\` - Skill loading
-- \`slack-checkConnection\`, \`slack-listAvailableTools\`, \`slack-executeAction\` - Slack integration (requires Slack to be connected via Composio). Use \`slack-listAvailableTools\` first to discover available tool slugs, then \`slack-executeAction\` to execute them.
-- \`web-search\` - Search the web. Returns rich results with full text, highlights, and metadata. The \`category\` parameter defaults to \`general\` (full web search) — only use a specific category like \`news\`, \`company\`, \`research paper\` etc. when the query is clearly about that type. For everyday queries (weather, restaurants, prices, how-to), use \`general\`.
+${slackToolsLine}- \`web-search\` - Search the web. Returns rich results with full text, highlights, and metadata. The \`category\` parameter defaults to \`general\` (full web search) — only use a specific category like \`news\`, \`company\`, \`research paper\` etc. when the query is clearly about that type. For everyday queries (weather, restaurants, prices, how-to), use \`general\`.
- \`app-navigation\` - Control the app UI: open notes, switch views, filter/search the knowledge base, manage saved views. **Load the \`app-navigation\` skill before using this tool.**
- \`browser-control\` - Control the embedded browser pane: open sites, inspect the live page, switch tabs, and interact with indexed page elements. **Load the \`browser-control\` skill before using this tool.**
- \`save-to-memory\` - Save observations about the user to the agent memory system. Use this proactively during conversations.
-- \`composio-list-toolkits\`, \`composio-search-tools\`, \`composio-execute-tool\`, \`composio-connect-toolkit\` — Composio integration tools. Load the \`composio-integration\` skill for usage guidance.
+${composioToolsLine}
**Prefer these tools whenever possible** — they work instantly with zero friction. For file operations inside the workspace root, always use these instead of \`executeCommand\`.
@@ -293,6 +305,10 @@ For browser pages, mention the URL in plain text or use the browser-control tool
**IMPORTANT:** Only use filepath blocks for files that already exist. The card is clickable and opens the file, so it must point to a real file. If you are proposing a path for a file that hasn't been created yet (e.g., "Shall I save it at ~/Documents/report.pdf?"), use inline code (\`~/Documents/report.pdf\`) instead of a filepath block. Use the filepath block only after the file has been written/created successfully.
Never output raw file paths in plain text when they could be wrapped in a filepath block — unless the file does not exist yet.`;
+}
+
+/** Keep backward-compatible export for any external consumers */
+export const CopilotInstructions = buildStaticInstructions(true, skillCatalog);
/**
* Cached Composio instructions. Invalidated by calling invalidateCopilotInstructionsCache().
@@ -313,9 +329,14 @@ export function invalidateCopilotInstructionsCache(): void {
*/
export async function buildCopilotInstructions(): Promise {
if (cachedInstructions !== null) return cachedInstructions;
+ const composioEnabled = await isComposioConfigured();
+ const catalog = composioEnabled
+ ? skillCatalog
+ : buildSkillCatalog({ excludeIds: ['composio-integration'] });
+ const baseInstructions = buildStaticInstructions(composioEnabled, catalog);
const composioPrompt = await getComposioToolsPrompt();
cachedInstructions = composioPrompt
- ? CopilotInstructions + '\n' + composioPrompt
- : CopilotInstructions;
+ ? baseInstructions + '\n' + composioPrompt
+ : baseInstructions;
return cachedInstructions;
}
diff --git a/apps/x/packages/core/src/application/assistant/skills/doc-collab/skill.ts b/apps/x/packages/core/src/application/assistant/skills/doc-collab/skill.ts
index f5f63c17..ed3096f8 100644
--- a/apps/x/packages/core/src/application/assistant/skills/doc-collab/skill.ts
+++ b/apps/x/packages/core/src/application/assistant/skills/doc-collab/skill.ts
@@ -71,24 +71,24 @@ workspace-grep({ pattern: "[name]", path: "knowledge/" })
- Ask: "Which document would you like to work on?"
**Creating new documents:**
-1. Ask simply: "Shall I create [filename]?" (don't ask about location - default to \`knowledge/\` root)
+1. Ask simply: "Shall I create [filename]?" (don't ask about location - default to \`knowledge/Notes/\` unless the user specifies a different folder)
2. Create it with just a title - don't pre-populate with structure or outlines
3. Ask: "What would you like in this?"
\`\`\`
workspace-createFile({
- path: "knowledge/[Document Name].md",
+ path: "knowledge/Notes/[Document Name].md",
content: "# [Document Title]\n\n"
})
\`\`\`
**WRONG approach:**
-- "Should this be in Projects/ or Topics/?" - don't ask, just use root
+- "Should this be in Projects/ or Topics/?" - don't ask, just use \`knowledge/Notes/\`
- "Here's a proposed outline..." - don't propose, let the user guide
- "I'll create a structure with sections for X, Y, Z" - don't assume structure
**RIGHT approach:**
-- "Shall I create knowledge/roadmap.md?"
+- "Shall I create knowledge/Notes/roadmap.md?"
- *creates file with just the title*
- "Created. What would you like in this?"
@@ -167,11 +167,11 @@ workspace-readFile("knowledge/Projects/[Project].md")
## Document Locations
Documents are stored in \`knowledge/\` within the workspace root, with subfolders:
+- \`Notes/\` - **Default location for user notes. Create new notes here unless the user specifies a different folder.**
- \`People/\` - Notes about individuals
- \`Organizations/\` - Notes about companies, teams
- \`Projects/\` - Project documentation
- \`Topics/\` - Subject matter notes
-- Root level for general documents
## Rich Blocks
@@ -196,6 +196,17 @@ Embeds external content (YouTube videos, Figma designs, or generic links).
- \`caption\` (optional): Caption displayed below the embed
- YouTube and Figma render as iframes; generic shows a link card
+### Iframe Block
+Embeds an arbitrary web page or a locally-served dashboard in the note.
+\`\`\`iframe
+{"url": "http://localhost:3210/sites/example-dashboard/", "title": "Trend Dashboard", "height": 640}
+\`\`\`
+- \`url\` (required): Full URL to render. Use \`https://\` for remote sites, or \`http://localhost:3210/sites//\` for local dashboards
+- \`title\` (optional): Title shown above the iframe
+- \`height\` (optional): Height in pixels. Good dashboard defaults are 480-800
+- \`allow\` (optional): Custom iframe \`allow\` attribute when the page needs extra browser capabilities
+- Remote sites may refuse to render in iframes because of their own CSP / X-Frame-Options headers. When you need a reliable embed, create a local site in \`sites//\` and use the localhost URL above
+
### Chart Block
Renders a chart from inline data.
\`\`\`chart
@@ -220,8 +231,9 @@ Renders a styled table from structured data.
### Block Guidelines
- The JSON must be valid and on a single line (no pretty-printing)
- Insert blocks using \`workspace-editFile\` just like any other content
-- When the user asks for a chart, table, or embed — use blocks rather than plain Markdown tables or image links
+- When the user asks for a chart, table, embed, or live dashboard — use blocks rather than plain Markdown tables or image links
- When editing a note that already contains blocks, preserve them unless the user asks to change them
+- For local dashboards and mini apps, put the site files in \`sites//\` and point an \`iframe\` block at \`http://localhost:3210/sites//\`
## Best Practices
diff --git a/apps/x/packages/core/src/application/assistant/skills/index.ts b/apps/x/packages/core/src/application/assistant/skills/index.ts
index d22db680..cad23177 100644
--- a/apps/x/packages/core/src/application/assistant/skills/index.ts
+++ b/apps/x/packages/core/src/application/assistant/skills/index.ts
@@ -133,6 +133,27 @@ export const skillCatalog = [
catalogSections.join("\n\n"),
].join("\n");
+/**
+ * Build a skill catalog string, optionally excluding specific skills by ID.
+ */
+export function buildSkillCatalog(options?: { excludeIds?: string[] }): string {
+ const entries = options?.excludeIds
+ ? skillEntries.filter(e => !options.excludeIds!.includes(e.id))
+ : skillEntries;
+ const sections = entries.map((entry) => [
+ `## ${entry.title}`,
+ `- **Skill file:** \`${entry.catalogPath}\``,
+ `- **Use it for:** ${entry.summary}`,
+ ].join("\n"));
+ return [
+ "# Rowboat Skill Catalog",
+ "",
+ "Use this catalog to see which specialized skills you can load. Each entry lists the exact skill file plus a short description of when it helps.",
+ "",
+ sections.join("\n\n"),
+ ].join("\n");
+}
+
const normalizeIdentifier = (value: string) =>
value.trim().replace(/\\/g, "/").replace(/^\.\/+/, "");
diff --git a/apps/x/packages/core/src/application/assistant/skills/tracks/skill.ts b/apps/x/packages/core/src/application/assistant/skills/tracks/skill.ts
index f60173f4..17521806 100644
--- a/apps/x/packages/core/src/application/assistant/skills/tracks/skill.ts
+++ b/apps/x/packages/core/src/application/assistant/skills/tracks/skill.ts
@@ -4,11 +4,40 @@ import { TrackBlockSchema } from '@x/shared/dist/track-block.js';
const schemaYaml = stringifyYaml(z.toJSONSchema(TrackBlockSchema)).trimEnd();
+const richBlockMenu = `**5. Rich block render — when the data has a natural visual form.**
+
+The track agent can emit *rich blocks* — special fenced blocks the editor renders as styled UI (charts, calendars, embedded iframes, etc.). When the data fits one of these shapes, instruct the agent explicitly so it doesn't fall back to plain markdown:
+
+- \`table\` — multi-row data, scoreboards, leaderboards. *"Render as a \`table\` block with columns Rank, Title, Points, Comments."*
+- \`chart\` — time series, breakdowns, share-of-total. *"Render as a \`chart\` block (line, bar, or pie) with x=date, y=rate."*
+- \`mermaid\` — flowcharts, sequence/relationship diagrams, gantt charts. *"Render as a \`mermaid\` diagram."*
+- \`calendar\` — upcoming events / agenda. *"Render as a \`calendar\` block."*
+- \`email\` — single email thread digest (subject, from, summary, latest body, optional draft). *"Render the most important unanswered thread as an \`email\` block."*
+- \`image\` — single image with caption. *"Render as an \`image\` block."*
+- \`embed\` — YouTube or Figma. *"Render as an \`embed\` block."*
+- \`iframe\` — live dashboards, status pages, anything that benefits from being live not snapshotted. *"Render as an \`iframe\` block pointing to ."*
+- \`transcript\` — long meeting transcripts (collapsible). *"Render as a \`transcript\` block."*
+- \`prompt\` — a "next step" Copilot card the user can click to start a chat. *"End with a \`prompt\` block labeled '' that runs ''."*
+
+You **do not** need to write the block body yourself — describe the desired output in the instruction and the track agent will format it (it knows each block's exact schema). Avoid \`track\` and \`task\` block types — those are user-authored input, not agent output.
+
+- Good: "Show today's calendar events. Render as a \`calendar\` block with \`showJoinButton: true\`."
+- Good: "Plot USD/INR over the last 7 days as a \`chart\` block — line chart, x=date, y=rate."
+- Bad: "Show today's calendar." (vague — agent may produce a markdown bullet list when the user wants the rich block)`;
+
export const skill = String.raw`
# Tracks Skill
You are helping the user create and manage **track blocks** — YAML-fenced, auto-updating content blocks embedded in notes. Load this skill whenever the user wants to track, monitor, watch, or keep an eye on something in a note, asks for recurring/auto-refreshing content ("every morning...", "show current...", "pin live X here"), or presses Cmd+K and requests auto-updating content at the cursor.
+## First: Just Do It — Do Not Ask About Edit Mode
+
+Track creation and editing are **action-first**. When the user asks to track, monitor, watch, or pin auto-updating content, you proceed directly — read the file, construct the block, ` + "`" + `workspace-edit` + "`" + ` it in. Do not ask "Should I make edits directly, or show you changes first for approval?" — that prompt belongs to generic document editing, not to tracks.
+
+- If another skill or an earlier turn already asked about edit mode and is waiting, treat the user's track request as implicit "direct mode" and proceed.
+- You may still ask **one** short clarifying question when genuinely ambiguous (e.g. which note to add it to). Not about permission to edit.
+- The Suggested Topics flow below is the one first-turn-confirmation exception — leave it intact.
+
## What Is a Track Block
A track block is a scheduled, agent-run block embedded directly inside a markdown note. Each block has:
@@ -19,7 +48,8 @@ A track block is a scheduled, agent-run block embedded directly inside a markdow
` + "```" + `track
trackId: chicago-time
-instruction: Show the current time in Chicago, IL in 12-hour format.
+instruction: |
+ Show the current time in Chicago, IL in 12-hour format.
active: true
schedule:
type: cron
@@ -57,6 +87,23 @@ ${schemaYaml}
**Runtime-managed fields — never write these yourself:** ` + "`" + `lastRunAt` + "`" + `, ` + "`" + `lastRunId` + "`" + `, ` + "`" + `lastRunSummary` + "`" + `.
+## Do Not Set ` + "`" + `model` + "`" + ` or ` + "`" + `provider` + "`" + ` (almost always)
+
+The schema includes optional ` + "`" + `model` + "`" + ` and ` + "`" + `provider` + "`" + ` fields. **Omit them.** A user-configurable global default already picks the right model and provider for tracks; setting per-track values bypasses that and is almost always wrong.
+
+The only time these belong on a track:
+
+- The user **explicitly** named a model or provider for *this specific track* in their request ("use Claude Opus for this one", "force this track onto OpenAI"). Quote the user's wording back when confirming.
+
+Things that are **not** reasons to set these:
+
+- "Tracks should be fast" / "I want a small model" — that's a global preference, not a per-track one. Leave it; the global default exists.
+- "This track is complex" — write a clearer instruction; don't reach for a different model.
+- "Just to be safe" / "in case it matters" — this is the antipattern. Leave them out.
+- The user changed their main chat model — that has nothing to do with tracks. Leave them out.
+
+When in doubt: omit both fields. Never volunteer them. Never include them in a starter template you suggest. If you find yourself adding them as a sensible default, stop — you're wrong.
+
## Choosing a trackId
- Kebab-case, short, descriptive: ` + "`" + `chicago-time` + "`" + `, ` + "`" + `sfo-weather` + "`" + `, ` + "`" + `hn-top5` + "`" + `, ` + "`" + `btc-usd` + "`" + `.
@@ -68,16 +115,118 @@ ${schemaYaml}
## Writing a Good Instruction
+### The Frame: This Is a Personal Knowledge Tracker
+
+Track output lives in a personal knowledge base the user scans frequently. Aim for data-forward, scannable output — the answer to "what's current / what changed?" in the fewest words that carry real information. Not prose. Not decoration.
+
+### Core Rules
+
- **Specific and actionable.** State exactly what to fetch or compute.
- **Single-focus.** One block = one purpose. Split "weather + news + stocks" into three blocks, don't bundle.
- **Imperative voice, 1-3 sentences.**
-- **Mention output style** if it matters ("markdown bullet list", "one sentence", "table with 5 rows").
+- **Specify output shape.** Describe it concretely: "one line: ` + "`" + `°F, ` + "`" + `", "3-column markdown table", "bulleted digest of 5 items".
-Good:
-> Fetch the current temperature, feels-like, and conditions for Chicago, IL in Fahrenheit. Return as a single line: "72°F (feels like 70°F), partly cloudy".
+### Self-Sufficiency (critical)
-Bad:
-> Tell me about Chicago.
+The instruction runs later, in a background scheduler, with **no chat context and no memory of this conversation**. It must stand alone.
+
+**Never use phrases that depend on prior conversation or prior runs:**
+- "as before", "same style as before", "like last time"
+- "keep the format we discussed", "matching the previous output"
+- "continue from where you left off" (without stating the state)
+
+If you want consistent style across runs, **describe the style inline** (e.g. "a 3-column markdown table with headers ` + "`" + `Location` + "`" + `, ` + "`" + `Local Time` + "`" + `, ` + "`" + `Offset` + "`" + `"; "a one-line status: HH:MM, conditions, temp"). The track agent only sees your instruction — not this chat, not what you produced last time.
+
+### Output Patterns — Match the Data
+
+Pick a shape that fits what the user is tracking. Five common patterns — the first four are plain markdown; the fifth is a rich rendered block:
+
+**1. Single metric / status line.**
+- Good: "Fetch USD/INR. Return one line: ` + "`" + `USD/INR: (as of )` + "`" + `."
+- Bad: "Give me a nice update about the dollar rate."
+
+**2. Compact table.**
+- Good: "Show current local time for India, Chicago, Indianapolis as a 3-column markdown table: ` + "`" + `Location | Local Time | Offset vs India` + "`" + `. One row per location, no prose."
+- Bad: "Show a polished, table-first world clock with a pleasant layout."
+
+**3. Rolling digest.**
+- Good: "Summarize the top 5 HN front-page stories as bullets: ` + "`" + `- ( pts, comments)` + "`" + `. No commentary."
+- Bad: "Give me the top HN stories with thoughtful takeaways."
+
+**4. Status / threshold watch.**
+- Good: "Check https://status.example.com. Return one line: ` + "`" + `✓ All systems operational` + "`" + ` or ` + "`" + `⚠ : ` + "`" + `. If degraded, add one bullet per affected component."
+- Bad: "Keep an eye on the status page and tell me how it looks."
+
+${richBlockMenu}
+
+### Anti-Patterns
+
+- **Decorative adjectives** describing the output: "polished", "clean", "beautiful", "pleasant", "nicely formatted" — they tell the agent nothing concrete.
+- **References to past state** without a mechanism to access it ("as before", "same as last time").
+- **Bundling multiple purposes** into one instruction — split into separate track blocks.
+- **Open-ended prose requests** ("tell me about X", "give me thoughts on X").
+- **Output-shape words without a concrete shape** ("dashboard-like", "report-style").
+
+## YAML String Style (critical — read before writing any ` + "`" + `instruction` + "`" + ` or ` + "`" + `eventMatchCriteria` + "`" + `)
+
+The two free-form fields — ` + "`" + `instruction` + "`" + ` and ` + "`" + `eventMatchCriteria` + "`" + ` — are where YAML parsing usually breaks. The runner re-emits the full YAML block every time it writes ` + "`" + `lastRunAt` + "`" + `, ` + "`" + `lastRunSummary` + "`" + `, etc., and the YAML library may re-flow long plain (unquoted) strings onto multiple lines. Once that happens, any ` + "`" + `:` + "`" + ` **followed by a space** inside the value silently corrupts the block: YAML interprets the ` + "`" + `:` + "`" + ` as a new key/value separator and the instruction gets truncated.
+
+Real failure seen in the wild — an instruction containing the phrase ` + "`" + `"polished UI style as before: clean, compact..."` + "`" + ` was written as a plain scalar, got re-emitted across multiple lines on the next run, and the ` + "`" + `as before:` + "`" + ` became a phantom key. The block parsed as garbage after that.
+
+### The rule: always use a safe scalar style
+
+**Default to the literal block scalar (` + "`" + `|` + "`" + `) for ` + "`" + `instruction` + "`" + ` and ` + "`" + `eventMatchCriteria` + "`" + `, every time.** It is the only style that is robust across the full range of punctuation these fields typically contain, and it is safe even if the content later grows to multiple lines.
+
+### Preferred: literal block scalar (` + "`" + `|` + "`" + `)
+
+` + "```" + `yaml
+instruction: |
+ Show current local time for India, Chicago, and Indianapolis as a
+ 3-column markdown table: Location | Local Time | Offset vs India.
+ One row per location, 24-hour time (HH:MM), no extra prose.
+ Note: when a location is in DST, reflect that in the offset column.
+eventMatchCriteria: |
+ Emails from the finance team about Q3 budget or OKRs.
+` + "```" + `
+
+- ` + "`" + `|` + "`" + ` preserves line breaks verbatim. Colons, ` + "`" + `#` + "`" + `, quotes, leading ` + "`" + `-` + "`" + `, percent signs — all literal. No escaping needed.
+- **Indent every content line by 2 spaces** relative to the key (` + "`" + `instruction:` + "`" + `). Use spaces, never tabs.
+- Leave a real newline after ` + "`" + `|` + "`" + ` — content starts on the next line, not the same line.
+- Default chomping (no modifier) is fine. Do **not** add ` + "`" + `-` + "`" + ` or ` + "`" + `+` + "`" + ` unless you know you need them.
+- A ` + "`" + `|` + "`" + ` block is terminated by a line indented less than the content — typically the next sibling key (` + "`" + `active:` + "`" + `, ` + "`" + `schedule:` + "`" + `).
+
+### Acceptable alternative: double-quoted on a single line
+
+Fine for short single-sentence fields with no newline needs:
+
+` + "```" + `yaml
+instruction: "Show the current time in Chicago, IL in 12-hour format."
+eventMatchCriteria: "Emails about Q3 planning, OKRs, or roadmap decisions."
+` + "```" + `
+
+- Escape ` + "`" + `"` + "`" + ` as ` + "`" + `\"` + "`" + ` and backslash as ` + "`" + `\\` + "`" + `.
+- Prefer ` + "`" + `|` + "`" + ` the moment the string needs two sentences or a newline.
+
+### Single-quoted on a single line (only if double-quoted would require heavy escaping)
+
+` + "```" + `yaml
+instruction: 'He said "hi" at 9:00.'
+` + "```" + `
+
+- A literal single quote is escaped by doubling it: ` + "`" + `'it''s fine'` + "`" + `.
+- No other escape sequences work.
+
+### Do NOT use plain (unquoted) scalars for these two fields
+
+Even if the current value looks safe, a future edit (by you or the user) may introduce a ` + "`" + `:` + "`" + ` or ` + "`" + `#` + "`" + `, and a future re-emit may fold the line. The ` + "`" + `|` + "`" + ` style is safe under **all** future edits — plain scalars are not.
+
+### Editing an existing track
+
+If you ` + "`" + `workspace-edit` + "`" + ` an existing track's ` + "`" + `instruction` + "`" + ` or ` + "`" + `eventMatchCriteria` + "`" + ` and find it is still a plain scalar, **upgrade it to ` + "`" + `|` + "`" + `** in the same edit. Don't leave a plain scalar behind that the next run will corrupt.
+
+### Never-hand-write fields
+
+` + "`" + `lastRunAt` + "`" + `, ` + "`" + `lastRunId` + "`" + `, ` + "`" + `lastRunSummary` + "`" + ` are owned by the runner. Don't touch them — don't even try to style them. If your ` + "`" + `workspace-edit` + "`" + `'s ` + "`" + `oldString` + "`" + ` happens to include these lines, copy them byte-for-byte into ` + "`" + `newString` + "`" + ` unchanged.
## Schedules
@@ -132,9 +281,12 @@ In addition to manual and scheduled, a track can be triggered by **events** —
` + "```" + `track
trackId: q3-planning-emails
-instruction: Maintain a running summary of decisions and open questions about Q3 planning, drawn from emails on the topic.
+instruction: |
+ Maintain a running summary of decisions and open questions about Q3
+ planning, drawn from emails on the topic.
active: true
-eventMatchCriteria: Emails about Q3 planning, roadmap decisions, or quarterly OKRs
+eventMatchCriteria: |
+ Emails about Q3 planning, roadmap decisions, or quarterly OKRs.
` + "```" + `
How it works:
@@ -155,6 +307,8 @@ Tracks **without** ` + "`" + `eventMatchCriteria` + "`" + ` opt out of events en
## Insertion Workflow
+**Reminder:** once you have enough to act, act. Do not pause to ask about edit mode.
+
### Cmd+K with cursor context
When the user invokes Cmd+K, the context includes an attachment mention like:
@@ -180,13 +334,29 @@ Workflow:
Ask one question: "Which note should this track live in?" Don't create a new note unless the user asks.
+### Suggested Topics exploration flow
+
+Sometimes the user arrives from the Suggested Topics panel and gives you a prompt like:
+- "I am exploring a suggested topic card from the Suggested Topics panel."
+- a title, category, description, and target folder such as ` + "`" + `knowledge/Topics/` + "`" + ` or ` + "`" + `knowledge/People/` + "`" + `
+
+In that flow:
+1. On the first turn, **do not create or modify anything yet**. Briefly explain the tracking note you can set up and ask for confirmation.
+2. If the user clearly confirms ("yes", "set it up", "do it"), treat that as explicit permission to proceed.
+3. Before creating a new note, search the target folder for an existing matching note and update it if one already exists.
+4. If no matching note exists and the prompt gave you a target folder, create the new note there without bouncing back to ask "which note should this live in?".
+5. Use the card title as the default note title / filename unless a small normalization is clearly needed.
+6. Keep the surrounding note scaffolding minimal but useful. The track block should be the core of the note.
+7. If the target folder is one of the structured knowledge folders (` + "`" + `knowledge/People/` + "`" + `, ` + "`" + `knowledge/Organizations/` + "`" + `, ` + "`" + `knowledge/Projects/` + "`" + `, ` + "`" + `knowledge/Topics/` + "`" + `), mirror the local note style by quickly checking a nearby note or config before writing if needed.
+
## The Exact Text to Insert
Write it verbatim like this (including the blank line between fence and target):
` + "```" + `track
trackId:
-instruction:
+instruction: |
+
active: true
schedule:
type: cron
@@ -199,6 +369,7 @@ schedule:
**Rules:**
- One blank line between the closing ` + "`" + "```" + `" + " fence and the ` + "`" + `` + "`" + `.
- Target pair is **empty on creation**. The runner fills it on the first run.
+- **Always use the literal block scalar (` + "`" + `|` + "`" + `)** for ` + "`" + `instruction` + "`" + ` and ` + "`" + `eventMatchCriteria` + "`" + `, indented 2 spaces. Never a plain (unquoted) scalar — see the YAML String Style section above for why.
- **Always quote cron expressions** in YAML — they contain spaces and ` + "`" + `*` + "`" + `.
- Use 2-space YAML indent. No tabs.
- Top-level markdown only — never inside a code fence, blockquote, or table.
@@ -302,7 +473,8 @@ Minimal template:
` + "```" + `track
trackId:
-instruction:
+instruction: |
+
active: true
schedule:
type: cron
@@ -313,6 +485,8 @@ schedule:
Top cron expressions: ` + "`" + `"0 * * * *"` + "`" + ` (hourly), ` + "`" + `"0 8 * * *"` + "`" + ` (daily 8am), ` + "`" + `"0 9 * * 1-5"` + "`" + ` (weekdays 9am), ` + "`" + `"*/15 * * * *"` + "`" + ` (every 15m).
+
+YAML style reminder: ` + "`" + `instruction` + "`" + ` and ` + "`" + `eventMatchCriteria` + "`" + ` are **always** ` + "`" + `|` + "`" + ` block scalars. Never plain. Never leave a plain scalar in place when editing.
`;
export default skill;
diff --git a/apps/x/packages/core/src/application/lib/builtin-tools.ts b/apps/x/packages/core/src/application/lib/builtin-tools.ts
index a2b68427..52083277 100644
--- a/apps/x/packages/core/src/application/lib/builtin-tools.ts
+++ b/apps/x/packages/core/src/application/lib/builtin-tools.ts
@@ -21,9 +21,8 @@ import { BrowserControlInputSchema, type BrowserControlInput } from "@x/shared/d
import type { ToolContext } from "./exec-tool.js";
import { generateText } from "ai";
import { createProvider } from "../../models/models.js";
-import { IModelConfigRepo } from "../../models/repo.js";
+import { getDefaultModelAndProvider, resolveProviderConfig } from "../../models/defaults.js";
import { isSignedIn } from "../../account/account.js";
-import { getGatewayProvider } from "../../models/gateway.js";
import { getAccessToken } from "../../auth/tokens.js";
import { API_URL } from "../../config/env.js";
import { updateContent, updateTrackBlock } from "../../knowledge/track/fileops.js";
@@ -746,13 +745,9 @@ export const BuiltinTools: z.infer = {
const base64 = buffer.toString('base64');
- // Resolve model config from DI container
- const modelConfigRepo = container.resolve('modelConfigRepo');
- const modelConfig = await modelConfigRepo.getConfig();
- const provider = await isSignedIn()
- ? await getGatewayProvider()
- : createProvider(modelConfig.provider);
- const model = provider.languageModel(modelConfig.model);
+ const { model: modelId, provider: providerName } = await getDefaultModelAndProvider();
+ const providerConfig = await resolveProviderConfig(providerName);
+ const model = createProvider(providerConfig).languageModel(modelId);
const userPrompt = prompt || 'Convert this file to well-structured markdown.';
diff --git a/apps/x/packages/core/src/application/lib/message-queue.ts b/apps/x/packages/core/src/application/lib/message-queue.ts
index d60b51b1..b3d2affa 100644
--- a/apps/x/packages/core/src/application/lib/message-queue.ts
+++ b/apps/x/packages/core/src/application/lib/message-queue.ts
@@ -4,6 +4,9 @@ import z from "zod";
export type UserMessageContentType = z.infer;
export type VoiceOutputMode = 'summary' | 'full';
+export type MiddlePaneContext =
+ | { kind: 'note'; path: string; content: string }
+ | { kind: 'browser'; url: string; title: string };
type EnqueuedMessage = {
messageId: string;
@@ -11,10 +14,11 @@ type EnqueuedMessage = {
voiceInput?: boolean;
voiceOutput?: VoiceOutputMode;
searchEnabled?: boolean;
+ middlePaneContext?: MiddlePaneContext;
};
export interface IMessageQueue {
- enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean): Promise;
+ enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext): Promise;
dequeue(runId: string): Promise;
}
@@ -30,7 +34,7 @@ export class InMemoryMessageQueue implements IMessageQueue {
this.idGenerator = idGenerator;
}
- async enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean): Promise {
+ async enqueue(runId: string, message: UserMessageContentType, voiceInput?: boolean, voiceOutput?: VoiceOutputMode, searchEnabled?: boolean, middlePaneContext?: MiddlePaneContext): Promise {
if (!this.store[runId]) {
this.store[runId] = [];
}
@@ -41,6 +45,7 @@ export class InMemoryMessageQueue implements IMessageQueue {
voiceInput,
voiceOutput,
searchEnabled,
+ middlePaneContext,
});
return id;
}
diff --git a/apps/x/packages/core/src/auth/oauth-client.ts b/apps/x/packages/core/src/auth/oauth-client.ts
index ccabab19..045ab920 100644
--- a/apps/x/packages/core/src/auth/oauth-client.ts
+++ b/apps/x/packages/core/src/auth/oauth-client.ts
@@ -216,12 +216,15 @@ export async function refreshTokens(
return tokens;
}
+const EXPIRY_MARGIN_SECONDS = 60;
+
/**
- * Check if tokens are expired
+ * Check if tokens are expired. Treats tokens as expired EXPIRY_MARGIN_SECONDS
+ * before the real expiry to absorb clock skew and in-flight request latency.
*/
export function isTokenExpired(tokens: OAuthTokens): boolean {
const now = Math.floor(Date.now() / 1000);
- return tokens.expires_at <= now;
+ return tokens.expires_at <= now + EXPIRY_MARGIN_SECONDS;
}
/**
diff --git a/apps/x/packages/core/src/auth/tokens.ts b/apps/x/packages/core/src/auth/tokens.ts
index 8a30bf9f..fe3afe0f 100644
--- a/apps/x/packages/core/src/auth/tokens.ts
+++ b/apps/x/packages/core/src/auth/tokens.ts
@@ -3,18 +3,12 @@ import { IOAuthRepo } from './repo.js';
import { IClientRegistrationRepo } from './client-repo.js';
import { getProviderConfig } from './providers.js';
import * as oauthClient from './oauth-client.js';
+import { OAuthTokens } from './types.js';
-export async function getAccessToken(): Promise {
- const oauthRepo = container.resolve('oauthRepo');
- const { tokens } = await oauthRepo.read('rowboat');
- if (!tokens) {
- throw new Error('Not signed into Rowboat');
- }
-
- if (!oauthClient.isTokenExpired(tokens)) {
- return tokens.access_token;
- }
+let refreshInFlight: Promise | null = null;
+async function performRefresh(tokens: OAuthTokens): Promise {
+ console.log("Refreshing rowboat access token");
if (!tokens.refresh_token) {
throw new Error('Rowboat token expired and no refresh token available. Please sign in again.');
}
@@ -40,7 +34,29 @@ export async function getAccessToken(): Promise {
tokens.refresh_token,
tokens.scopes,
);
+
+ const oauthRepo = container.resolve('oauthRepo');
await oauthRepo.upsert('rowboat', { tokens: refreshed });
+ return refreshed;
+}
+
+export async function getAccessToken(): Promise {
+ const oauthRepo = container.resolve('oauthRepo');
+ const { tokens } = await oauthRepo.read('rowboat');
+ if (!tokens) {
+ throw new Error('Not signed into Rowboat');
+ }
+
+ if (!oauthClient.isTokenExpired(tokens)) {
+ return tokens.access_token;
+ }
+
+ if (!refreshInFlight) {
+ refreshInFlight = performRefresh(tokens).finally(() => {
+ refreshInFlight = null;
+ });
+ }
+ const refreshed = await refreshInFlight;
return refreshed.access_token;
}
diff --git a/apps/x/packages/core/src/knowledge/agent_notes.ts b/apps/x/packages/core/src/knowledge/agent_notes.ts
index 16307bb5..359976dd 100644
--- a/apps/x/packages/core/src/knowledge/agent_notes.ts
+++ b/apps/x/packages/core/src/knowledge/agent_notes.ts
@@ -3,6 +3,7 @@ import path from 'path';
import { google } from 'googleapis';
import { WorkDir } from '../config/config.js';
import { createRun, createMessage } from '../runs/runs.js';
+import { getKgModel } from '../models/defaults.js';
import { waitForRunCompletion } from '../agents/utils.js';
import { serviceLogger } from '../services/service_logger.js';
import { loadUserConfig, updateUserEmail } from '../config/user_config.js';
@@ -305,7 +306,7 @@ async function processAgentNotes(): Promise {
const timestamp = new Date().toISOString();
const message = `Current timestamp: ${timestamp}\n\nProcess the following source material and update the Agent Notes folder accordingly.\n\n${messageParts.join('\n\n')}`;
- const agentRun = await createRun({ agentId: AGENT_ID });
+ const agentRun = await createRun({ agentId: AGENT_ID, model: await getKgModel() });
await createMessage(agentRun.id, message);
await waitForRunCompletion(agentRun.id);
diff --git a/apps/x/packages/core/src/knowledge/build_graph.ts b/apps/x/packages/core/src/knowledge/build_graph.ts
index 06fd1194..60c0572e 100644
--- a/apps/x/packages/core/src/knowledge/build_graph.ts
+++ b/apps/x/packages/core/src/knowledge/build_graph.ts
@@ -25,6 +25,12 @@ import { getTagDefinitions } from './tag_system.js';
const NOTES_OUTPUT_DIR = path.join(WorkDir, 'knowledge');
const NOTE_CREATION_AGENT = 'note_creation';
+const SUGGESTED_TOPICS_REL_PATH = 'suggested-topics.md';
+const SUGGESTED_TOPICS_PATH = path.join(WorkDir, 'suggested-topics.md');
+const LEGACY_SUGGESTED_TOPICS_REL_PATH = 'config/suggested-topics.md';
+const LEGACY_SUGGESTED_TOPICS_PATH = path.join(WorkDir, 'config', 'suggested-topics.md');
+const LEGACY_SUGGESTED_TOPICS_KNOWLEDGE_REL_PATH = 'knowledge/Notes/Suggested Topics.md';
+const LEGACY_SUGGESTED_TOPICS_KNOWLEDGE_PATH = path.join(WorkDir, 'knowledge', 'Notes', 'Suggested Topics.md');
// Configuration for the graph builder service
const SYNC_INTERVAL_MS = 15 * 1000; // 15 seconds
@@ -32,6 +38,7 @@ const SOURCE_FOLDERS = [
'gmail_sync',
path.join('knowledge', 'Meetings', 'fireflies'),
path.join('knowledge', 'Meetings', 'granola'),
+ path.join('knowledge', 'Meetings', 'rowboat'),
];
// Voice memos are now created directly in knowledge/Voice Memos//
@@ -88,6 +95,49 @@ function extractPathFromToolInput(input: string): string | null {
}
}
+function ensureSuggestedTopicsFileLocation(): string {
+ if (fs.existsSync(SUGGESTED_TOPICS_PATH)) {
+ return SUGGESTED_TOPICS_PATH;
+ }
+
+ const legacyCandidates: Array<{ absPath: string; relPath: string }> = [
+ { absPath: LEGACY_SUGGESTED_TOPICS_PATH, relPath: LEGACY_SUGGESTED_TOPICS_REL_PATH },
+ { absPath: LEGACY_SUGGESTED_TOPICS_KNOWLEDGE_PATH, relPath: LEGACY_SUGGESTED_TOPICS_KNOWLEDGE_REL_PATH },
+ ];
+
+ for (const legacy of legacyCandidates) {
+ if (!fs.existsSync(legacy.absPath)) {
+ continue;
+ }
+
+ try {
+ fs.renameSync(legacy.absPath, SUGGESTED_TOPICS_PATH);
+ console.log(`[buildGraph] Moved suggested topics file from ${legacy.relPath} to ${SUGGESTED_TOPICS_REL_PATH}`);
+ return SUGGESTED_TOPICS_PATH;
+ } catch (error) {
+ console.error(`[buildGraph] Failed to move suggested topics file from ${legacy.relPath} to ${SUGGESTED_TOPICS_REL_PATH}:`, error);
+ return legacy.absPath;
+ }
+ }
+
+ return SUGGESTED_TOPICS_PATH;
+}
+
+function readSuggestedTopicsFile(): string {
+ try {
+ const suggestedTopicsPath = ensureSuggestedTopicsFileLocation();
+ if (!fs.existsSync(suggestedTopicsPath)) {
+ return '_No existing suggested topics file._';
+ }
+
+ const content = fs.readFileSync(suggestedTopicsPath, 'utf-8').trim();
+ return content.length > 0 ? content : '_Existing suggested topics file is empty._';
+ } catch (error) {
+ console.error(`[buildGraph] Error reading suggested topics file:`, error);
+ return '_Failed to read existing suggested topics file._';
+ }
+}
+
/**
* Get unprocessed voice memo files from knowledge/Voice Memos/
* Voice memos are created directly in this directory by the UI.
@@ -203,6 +253,7 @@ async function createNotesFromBatch(
const run = await createRun({
agentId: NOTE_CREATION_AGENT,
});
+ const suggestedTopicsContent = readSuggestedTopicsFile();
// Build message with index and all files in the batch
let message = `Process the following ${files.length} source files and create/update obsidian notes.\n\n`;
@@ -210,8 +261,9 @@ async function createNotesFromBatch(
message += `- Use the KNOWLEDGE BASE INDEX below to resolve entities - DO NOT grep/search for existing notes\n`;
message += `- Extract entities (people, organizations, projects, topics) from ALL files below\n`;
message += `- Create or update notes in "knowledge" directory (workspace-relative paths like "knowledge/People/Name.md")\n`;
+ message += `- You may also create or update "${SUGGESTED_TOPICS_REL_PATH}" to maintain curated suggested-topic cards\n`;
message += `- If the same entity appears in multiple files, merge the information into a single note\n`;
- message += `- Use workspace tools to read existing notes (when you need full content) and write updates\n`;
+ message += `- Use workspace tools to read existing notes or "${SUGGESTED_TOPICS_REL_PATH}" (when you need full content) and write updates\n`;
message += `- Follow the note templates and guidelines in your instructions\n\n`;
// Add the knowledge base index
@@ -219,6 +271,11 @@ async function createNotesFromBatch(
message += knowledgeIndex;
message += `\n---\n\n`;
+ message += `# Current Suggested Topics File\n\n`;
+ message += `Path: ${SUGGESTED_TOPICS_REL_PATH}\n\n`;
+ message += suggestedTopicsContent;
+ message += `\n\n---\n\n`;
+
// Add each file's content
message += `# Source Files to Process\n\n`;
files.forEach((file, idx) => {
diff --git a/apps/x/packages/core/src/knowledge/ensure_daily_note.ts b/apps/x/packages/core/src/knowledge/ensure_daily_note.ts
index 55383a6b..ac54d029 100644
--- a/apps/x/packages/core/src/knowledge/ensure_daily_note.ts
+++ b/apps/x/packages/core/src/knowledge/ensure_daily_note.ts
@@ -1,44 +1,157 @@
import path from 'path';
import fs from 'fs';
+import { stringify as stringifyYaml } from 'yaml';
+import { TrackBlockSchema } from '@x/shared/dist/track-block.js';
import { WorkDir } from '../config/config.js';
+import z from 'zod';
const KNOWLEDGE_DIR = path.join(WorkDir, 'knowledge');
const DAILY_NOTE_PATH = path.join(KNOWLEDGE_DIR, 'Today.md');
-const TARGET_ID = 'dailybrief';
+
+interface Section {
+ heading: string;
+ track: z.infer;
+}
+
+const SECTIONS: Section[] = [
+ {
+ heading: '## ⏱ Up Next',
+ track: {
+ trackId: 'up-next',
+ instruction:
+`Write 1-3 sentences of plain markdown giving the user a shoulder-tap about what's next on their calendar today.
+
+This section refreshes on calendar changes, not on a clock tick — do NOT promise live minute countdowns. Frame urgency in buckets based on the event's start time relative to now:
+- Start time is in the past or within roughly half an hour → imminent: name the meeting and say it's starting soon (e.g. "Standup is starting — join link in the Calendar section below.").
+- Start time is later this morning or this afternoon → upcoming: name the meeting and roughly when (e.g. "Design review later this morning." / "1:1 with Sam this afternoon.").
+- Start time is several hours out or nothing before then → focus block: frame the gap (e.g. "Next up is the all-hands at 3pm — good long focus block until then.").
+
+Use the event's start time of day ("at 3pm", "this afternoon") rather than a countdown ("in 40 minutes"). Countdowns go stale between syncs.
+
+Data: read today's events from calendar_sync/ (workspace-readdir, then workspace-readFile each .json file). Filter to events whose start datetime is today and hasn't ended yet — for finding the next event, pick the earliest upcoming one; if all have passed, treat as clear.
+
+If you find quick context in knowledge/ that's genuinely useful, add one short clause ("Ramnique pushed the OAuth PR yesterday — might come up"). Use workspace-grep / workspace-readFile conservatively; don't stall on deep research.
+
+If nothing remains today, output exactly: Clear for the rest of the day.
+
+Plain markdown prose only — no calendar block, no email block, no headings.`,
+ eventMatchCriteria:
+`Calendar event changes affecting today — new meetings, reschedules, cancellations, meetings starting soon. Skip changes to events on other days.`,
+ active: true,
+ },
+ },
+ {
+ heading: '## 📅 Calendar',
+ track: {
+ trackId: 'calendar',
+ instruction:
+`Emit today's meetings as a calendar block titled "Today's Meetings".
+
+Data: read calendar_sync/ via workspace-readdir, then workspace-readFile each .json event file. Filter to events occurring today. After 10am local time, drop meetings that have already ended — only include meetings that haven't ended yet.
+
+This section refreshes on calendar changes, not on a clock tick — the "drop ended meetings" rule applies on each refresh, so an ended meeting disappears the next time any calendar event changes (not exactly on the clock hour). That's fine.
+
+Always emit the calendar block, even when there are no remaining events (in that case use events: [] and showJoinButton: false). Set showJoinButton: true whenever any event has a conferenceLink.
+
+After the block, you MAY add one short markdown line per event giving useful prep context pulled from knowledge/ ("Design review: last week we agreed to revisit the type-picker UX."). Keep it tight — one line each, only when meaningful. Skip routine/recurring meetings.`,
+ eventMatchCriteria:
+`Calendar event changes affecting today — additions, updates, cancellations, reschedules.`,
+ active: true,
+ },
+ },
+ {
+ heading: '## 📧 Emails',
+ track: {
+ trackId: 'emails',
+ instruction:
+`Maintain a digest of email threads worth the user's attention today, rendered as zero or more email blocks (one per thread).
+
+Event-driven path (primary): the agent message will include a "Gmail sync update" digest payload describing one or more freshly-synced threads from a single sync run. The digest lists each thread with its subject, sender, date, threadId, and body. Iterate over every thread in the payload and decide per thread whether it warrants surfacing. Skip marketing, auto-notifications, closed-out threads, and other low-signal mail. For threads that are attention-worthy, integrate them into the existing digest: add a new email block for a new threadId, or update the existing block if the threadId is already shown. If NONE of the threads in the payload are attention-worthy, skip the update — do NOT call update-track-content. Emit at most one update-track-content call that covers the full set of changes from this event.
+
+Manual path (fallback): with no event payload, scan gmail_sync/ via workspace-readdir (skip sync_state.json and attachments/). Read threads with workspace-readFile. Prioritize threads whose frontmatter action field is "reply" or "respond", plus other high-signal recent threads.
+
+Each email block should include threadId, subject, from, date, summary, and latest_email. For threads that need a reply, add a draft_response written in the user's voice — direct, informal, no fluff. For FYI threads, omit draft_response.
+
+If there is genuinely nothing to surface, output the single line: No new emails.
+
+Do NOT re-list threads the user has already seen unless their state changed (new reply, status flip).`,
+ eventMatchCriteria:
+`New or updated email threads that may need the user's attention today — drafts to send, replies to write, urgent requests, time-sensitive info. Skip marketing, newsletters, auto-notifications, and chatter on closed threads.`,
+ active: true,
+ },
+ },
+ {
+ heading: '## 📰 What You Missed',
+ track: {
+ trackId: 'what-you-missed',
+ instruction:
+`Short markdown summary of what happened yesterday that matters this morning.
+
+Data sources:
+- knowledge/Meetings///meeting-.md — use workspace-readdir with recursive: true on knowledge/Meetings, filter for folders matching yesterday's date (compute yesterday from the current local date), read each matching file. Pull out: decisions made, action items assigned, blockers raised, commitments.
+- gmail_sync/ — skim for threads from yesterday that went unresolved or still need a reply.
+
+Skip recurring/routine events (standups, weekly syncs) unless something unusual happened in them.
+
+Write concise markdown — a few bullets or a short paragraph, whichever reads better. Lead with anything that shifts the user's priorities today.
+
+If nothing notable happened, output exactly: Quiet day yesterday — nothing to flag.
+
+Do NOT manufacture content to fill the section.`,
+ active: true,
+ schedule: {
+ type: 'cron',
+ expression: '0 7 * * *',
+ },
+ },
+ },
+ {
+ heading: '## ✅ Today\'s Priorities',
+ track: {
+ trackId: 'priorities',
+ instruction:
+`Ranked markdown list of the real, actionable items the user should focus on today.
+
+Data sources:
+- Yesterday's meeting notes under knowledge/Meetings/// — action items assigned to the user are often the most important source.
+- knowledge/ — use workspace-grep for "- [ ]" checkboxes, explicit action items, deadlines, follow-ups.
+- Optional: workspace-readFile on knowledge/Today.md for the current "What You Missed" section — useful for alignment.
+
+Rules:
+- Do NOT list calendar events as tasks — they're already in the Calendar section.
+- Do NOT list trivial admin (filing small invoices, archiving spam).
+- Rank by importance. Lead with the most critical item. Note time-sensitivity when it exists ("needs to go out before the 3pm review").
+- Add a brief reason for each item when it's not self-evident.
+
+If nothing genuinely needs attention, output exactly: No pressing tasks today — good day to make progress on bigger items.
+
+Do NOT invent busywork.`,
+ active: true,
+ schedule: {
+ type: 'cron',
+ expression: '30 7 * * *',
+ },
+ },
+ },
+];
function buildDailyNoteContent(): string {
- const now = new Date();
- const startDate = now.toISOString();
- const endDate = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000).toISOString();
-
- const instruction = 'Create a daily brief for me';
-
- const taskBlock = JSON.stringify({
- instruction,
- schedule: {
- type: 'cron',
- expression: '*/15 * * * *',
- startDate,
- endDate,
- },
- 'schedule-label': 'runs every 15 minutes',
- targetId: TARGET_ID,
- });
-
- return [
- '---',
- 'live_note: true',
- '---',
- '# Today',
- '',
- '```task',
- taskBlock,
- '```',
- '',
- ``,
- ``,
- '',
- ].join('\n');
+ const parts: string[] = ['# Today', ''];
+ for (const { heading, track } of SECTIONS) {
+ const yaml = stringifyYaml(track, { lineWidth: 0, blockQuote: 'literal' }).trimEnd();
+ parts.push(
+ heading,
+ '',
+ '```track',
+ yaml,
+ '```',
+ '',
+ ``,
+ ``,
+ '',
+ );
+ }
+ return parts.join('\n');
}
export function ensureDailyNote(): void {
diff --git a/apps/x/packages/core/src/knowledge/file-lock.ts b/apps/x/packages/core/src/knowledge/file-lock.ts
new file mode 100644
index 00000000..157188cb
--- /dev/null
+++ b/apps/x/packages/core/src/knowledge/file-lock.ts
@@ -0,0 +1,18 @@
+const locks = new Map>();
+
+export async function withFileLock(absPath: string, fn: () => Promise): Promise {
+ const prev = locks.get(absPath) ?? Promise.resolve();
+ let release!: () => void;
+ const gate = new Promise((r) => { release = r; });
+ const myTail = prev.then(() => gate);
+ locks.set(absPath, myTail);
+ try {
+ await prev;
+ return await fn();
+ } finally {
+ release();
+ if (locks.get(absPath) === myTail) {
+ locks.delete(absPath);
+ }
+ }
+}
diff --git a/apps/x/packages/core/src/knowledge/inline_task_agent.ts b/apps/x/packages/core/src/knowledge/inline_task_agent.ts
index d25ff74b..fd90875b 100644
--- a/apps/x/packages/core/src/knowledge/inline_task_agent.ts
+++ b/apps/x/packages/core/src/knowledge/inline_task_agent.ts
@@ -13,7 +13,6 @@ export function getRaw(): string {
const defaultEndISO = defaultEnd.toISOString();
return `---
-model: gpt-5.2
tools:
${toolEntries}
---
diff --git a/apps/x/packages/core/src/knowledge/inline_tasks.ts b/apps/x/packages/core/src/knowledge/inline_tasks.ts
index 01d22352..953f86bd 100644
--- a/apps/x/packages/core/src/knowledge/inline_tasks.ts
+++ b/apps/x/packages/core/src/knowledge/inline_tasks.ts
@@ -4,6 +4,7 @@ import { CronExpressionParser } from 'cron-parser';
import { generateText } from 'ai';
import { WorkDir } from '../config/config.js';
import { createRun, createMessage, fetchRun } from '../runs/runs.js';
+import { getKgModel } from '../models/defaults.js';
import container from '../di/container.js';
import type { IModelConfigRepo } from '../models/repo.js';
import { createProvider } from '../models/models.js';
@@ -467,7 +468,7 @@ async function processInlineTasks(): Promise {
console.log(`[InlineTasks] Running task: "${task.instruction.slice(0, 80)}..."`);
try {
- const run = await createRun({ agentId: INLINE_TASK_AGENT });
+ const run = await createRun({ agentId: INLINE_TASK_AGENT, model: await getKgModel() });
const message = [
`Execute the following instruction from the note "${relativePath}":`,
@@ -547,7 +548,7 @@ export async function processRowboatInstruction(
scheduleLabel: string | null;
response: string | null;
}> {
- const run = await createRun({ agentId: INLINE_TASK_AGENT });
+ const run = await createRun({ agentId: INLINE_TASK_AGENT, model: await getKgModel() });
const message = [
`Process the following @rowboat instruction from the note "${notePath}":`,
diff --git a/apps/x/packages/core/src/knowledge/label_emails.ts b/apps/x/packages/core/src/knowledge/label_emails.ts
index 98b10c2f..95b6217b 100644
--- a/apps/x/packages/core/src/knowledge/label_emails.ts
+++ b/apps/x/packages/core/src/knowledge/label_emails.ts
@@ -2,6 +2,7 @@ import fs from 'fs';
import path from 'path';
import { WorkDir } from '../config/config.js';
import { createRun, createMessage } from '../runs/runs.js';
+import { getKgModel } from '../models/defaults.js';
import { bus } from '../runs/bus.js';
import { waitForRunCompletion } from '../agents/utils.js';
import { serviceLogger } from '../services/service_logger.js';
@@ -71,6 +72,7 @@ async function labelEmailBatch(
): Promise<{ runId: string; filesEdited: Set }> {
const run = await createRun({
agentId: LABELING_AGENT,
+ model: await getKgModel(),
});
let message = `Label the following ${files.length} email files by prepending YAML frontmatter.\n\n`;
diff --git a/apps/x/packages/core/src/knowledge/labeling_agent.ts b/apps/x/packages/core/src/knowledge/labeling_agent.ts
index d28649b1..8842891a 100644
--- a/apps/x/packages/core/src/knowledge/labeling_agent.ts
+++ b/apps/x/packages/core/src/knowledge/labeling_agent.ts
@@ -2,7 +2,6 @@ import { renderTagSystemForEmails } from './tag_system.js';
export function getRaw(): string {
return `---
-model: gpt-5.2
tools:
workspace-readFile:
type: builtin
diff --git a/apps/x/packages/core/src/knowledge/note_creation.ts b/apps/x/packages/core/src/knowledge/note_creation.ts
index 1d8aa32d..0a4d8981 100644
--- a/apps/x/packages/core/src/knowledge/note_creation.ts
+++ b/apps/x/packages/core/src/knowledge/note_creation.ts
@@ -3,7 +3,6 @@ import { renderNoteEffectRules } from './tag_system.js';
export function getRaw(): string {
return `---
-model: gpt-5.2
tools:
workspace-writeFile:
type: builtin
@@ -485,9 +484,9 @@ RESOLVED (use canonical name with absolute path):
- "Acme", "Acme Corp", "@acme.com" → [[Organizations/Acme Corp]]
- "the pilot", "the integration" → [[Projects/Acme Integration]]
-NEW ENTITIES (create notes if source passes filters):
+NEW ENTITIES (create notes or suggestion cards if source passes filters):
- "Jennifer" (CTO, Acme Corp) → Create [[People/Jennifer]] or [[People/Jennifer (Acme Corp)]]
-- "SOC 2" → Create [[Topics/Security Compliance]]
+- "SOC 2" → Add or update a suggestion card in \`suggested-topics.md\` with category \`Topics\`
AMBIGUOUS (flag or skip):
- "Mike" (no context) → Mention in activity only, don't create note
@@ -508,8 +507,8 @@ For entities not resolved to existing notes, determine if they warrant new notes
**CREATE a note for people who are:**
- External (not @user.domain)
-- Attendees in meetings
-- Email correspondents (emails that reach this step already passed label-based filtering)
+- People you directly interacted with in meetings
+- Email correspondents directly participating in the thread (emails that reach this step already passed label-based filtering)
- Decision makers or contacts at customers, prospects, or partners
- Investors or potential investors
- Candidates you are interviewing
@@ -521,6 +520,7 @@ For entities not resolved to existing notes, determine if they warrant new notes
- Large group meeting attendees you didn't interact with
- Internal colleagues (@user.domain)
- Assistants handling only logistics
+- People mentioned only as third parties ("we work with X", "I can introduce you to Y") when there has been no direct interaction yet
### Role Inference
@@ -579,31 +579,155 @@ For people who don't warrant their own note, add to Organization note's Contacts
- Sarah Lee — Support, handled wire transfer issue
\`\`\`
+### Direct Interaction Test (People and Organizations)
+
+For **new canonical People and Organizations notes**, require **direct interaction**, not just mention.
+
+**Direct interaction = YES**
+- The person sent the email, replied in the thread, or was directly addressed as part of the active exchange
+- The person participated in the meeting, and there is evidence the user actually interacted with them or the meeting centered on them
+- The organization is directly represented in the exchange by participants/senders and is part of an active first-degree relationship with the user or team
+- The user is directly evaluating, selling to, buying from, partnering with, interviewing, or coordinating with that person or organization
+
+**Direct interaction = NO**
+- Someone else mentions them in passing
+- A sender says they work with someone at another company
+- A sender offers to introduce the user to someone
+- A company is referenced as a customer, partner, employer, competitor, or example, but nobody from that company is directly involved in the interaction
+- The source only establishes a second-degree relationship, not a direct one
+
+**Canonical note rule:**
+- For **new People/Organizations**, create the canonical note only if both are true:
+ 1. There is **direct interaction**
+ 2. The entity clears the **weekly importance test**
+
+If an entity seems strategically relevant but fails the direct interaction test, do **not** auto-create a canonical note. At most, create a suggestion card in \`suggested-topics.md\`.
+
+### Weekly Importance Test (People and Organizations only)
+
+For **People** and **Organizations**, the final gate for **creating a new canonical note** is an importance test:
+
+**Ask:** _"If I were the user, would I realistically need to look at this note on a weekly basis over the near term?"_
+
+This test is mainly for **People** and **Organizations**. **Do NOT use it as the decision rule for Topic or Project suggestions.**
+
+**Strong YES signals:**
+- Active customer, prospect, investor, partner, candidate, advisor, or strategic vendor relationship
+- Repeated interaction or a likely ongoing cadence
+- Decision-maker, owner, blocker, evaluator, or approver in an active process
+- Material relevance to launch, sales, fundraising, hiring, compliance, product delivery, or another current priority
+- The user would benefit from a durable reference note instead of repeatedly reopening raw emails or meeting transcripts
+
+**Strong NO signals:**
+- One-off logistics, scheduling, or transactional contact
+- Assistant, support rep, recruiter, or vendor rep with no ongoing strategic role
+- Incidental attendee mentioned once with no leverage on current work
+- Passing mention with no evidence of an ongoing relationship
+
+**Borderline signals:**
+- Seems potentially important, but there isn't enough evidence yet that the user will need a weekly reference note
+- Might become important soon, but the role, relationship, or repeated relevance is still unclear
+- Important enough to track, but only through second-degree mention or an offered introduction rather than direct interaction
+
+**Outcome rules for new People/Organizations:**
+- **Clear YES + direct interaction** → Create/update the canonical \`People/\` or \`Organizations/\` note
+- **Borderline or no direct interaction, but still strategically relevant** → Do **not** create the canonical note yet; instead create or update a card in \`suggested-topics.md\`
+- **Clear NO** → Skip note creation and do not add a suggestion unless the source strongly suggests near-term strategic relevance
+
+**When a canonical note already exists:**
+- Update the existing note even if the current source is weaker; the importance test is mainly for deciding whether to create a **new** People/Organization note
+- If a previously tentative person/org is now clearly important enough for a canonical note, create/update the note and remove any tentative suggestion card for that exact entity from \`suggested-topics.md\`
+
## Organizations
**CREATE a note if:**
-- Someone from that org attended a meeting
-- They're a customer, prospect, investor, or partner
-- Someone from that org sent relevant personalized correspondence
+- There is direct interaction with that org in the source
+- They're a customer, prospect, investor, or partner in a direct first-degree interaction
+- Someone from that org sent relevant personalized correspondence or joined a meeting you actually had with them
+- They pass the weekly importance test above
**DO NOT create for:**
- Tool/service providers mentioned in passing
- One-time transactional vendors
- Consumer service companies
+- Organizations only referenced through third-party mention or offered introductions
## Projects
-**CREATE a note if:**
+**If a project note already exists:** update it.
+
+**If no project note exists:** do **not** create a new canonical note in \`knowledge/Projects/\`.
+
+Instead, create or update a **suggestion card** in \`suggested-topics.md\` if the project is strong enough:
- Discussed substantively in a meeting or email thread
- Has a goal and timeline
- Involves multiple interactions
+Otherwise skip it.
+
+Projects do **not** use the weekly importance test above. For **new** projects, the default output is a suggestion card, not a canonical note.
+
## Topics
-**CREATE a note if:**
+**If a topic note already exists:** update it.
+
+**If no topic note exists:** do **not** create a new canonical note in \`knowledge/Topics/\`.
+
+Instead, create or update a **suggestion card** in \`suggested-topics.md\` if the topic is strong enough:
- Recurring theme discussed
- Will come up again across conversations
+Otherwise skip it.
+
+Topics do **not** use the weekly importance test above. For **new** topics, the default output is a suggestion card, not a canonical note.
+
+## Suggested Topics Curation
+
+Also maintain \`suggested-topics.md\` as a **curated shortlist** of things worth exploring next.
+
+Despite the filename, \`suggested-topics.md\` can contain cards for **People, Organizations, Topics, or Projects**.
+
+There are **two reasons** to add or update a suggestion card:
+
+1. **High-quality Topic/Project cards**
+ - Use these for topics or projects that are timely, high-leverage, strategically important, or clearly worth exploring now
+ - These are not a dump of every topic/project note. Be selective
+ - For **new** topics and projects, cards are the default output from this pipeline
+
+2. **Tentative People/Organization cards**
+ - Use these when a person or organization seems important enough to track, but you are **not 100% sure** they clear the weekly-importance test for a canonical note yet
+ - The card should capture why they might matter and what still needs verification
+
+**Do NOT add cards for:**
+- Low-signal administrative or transactional entities
+- Stale or completed items with no near-term relevance
+- People/organizations that already have a clearly established canonical note, unless the card is about a distinct project/topic exploration rather than the entity itself
+
+**Card guidance:**
+- For **Topics/Projects**, use category \`Topics\` or \`Projects\`
+- For tentative **People/Organizations**, use category \`People\` or \`Organizations\`
+- Title should be concise and canonical when possible
+- Description should explain why it matters **now**
+- For tentative People/Organizations, description should also mention what is still uncertain or what the user should verify
+
+**Curation rules:**
+- Maintain a **high-quality set**, not an ever-growing backlog
+- Deduplicate by normalized title
+- Prefer current, actionable, recurring, or strategically important items
+- Keep only the strongest **8-12 cards total**
+- Preserve good existing cards unless the new source clearly supersedes them
+- Remove stale cards that are no longer relevant
+- If a tentative People/Organization card later becomes clearly important and you create a canonical note, remove the tentative card
+
+**File format for \`suggested-topics.md\`:**
+\`\`\`suggestedtopic
+{"title":"Security Compliance","description":"Summarize the current compliance posture, blockers, and customer implications.","category":"Topics"}
+\`\`\`
+
+The file should start with \`# Suggested Topics\` followed by one or more blocks in that format.
+
+If the file does not exist, create it. If it exists, update it in place or rewrite the full file so the final result is clean, deduped, and curated.
+
---
# Step 6: Extract Content
@@ -824,7 +948,7 @@ If new info contradicts existing:
# Step 9: Write Updates
-## 9a: Create and Update Notes
+## 9a: Create and Update Notes and Suggested Topic Cards
**IMPORTANT: Write sequentially, one file at a time.**
- Generate content for exactly one note.
@@ -852,6 +976,12 @@ workspace-edit({
})
\`\`\`
+**For \`suggested-topics.md\`:**
+- Use workspace-relative path \`suggested-topics.md\`
+- Read the current file if you need the latest content
+- Use \`workspace-writeFile\` to create or rewrite the file when that is simpler and cleaner
+- Use \`workspace-edit\` for small targeted edits only if that keeps the file deduped and readable
+
## 9b: Apply State Changes
For each state change identified in Step 7, update the relevant fields.
@@ -867,8 +997,9 @@ If you discovered new name variants during resolution, add them to Aliases field
- Be concise: one line per activity entry
- Note state changes with \`[Field → value]\` in activity
- Escape quotes properly in shell commands
-- Write only one file per response (no multi-file write batches)
+- Write only one file per response (notes and \`suggested-topics.md\` follow the same rule)
- **Always set \`Last update\`** in the Info section to the YYYY-MM-DD date of the source email or meeting. When updating an existing note, update this field to the new source event's date.
+- Keep \`suggested-topics.md\` curated, deduped, and capped to the strongest 8-12 cards
---
@@ -957,8 +1088,12 @@ Before completing, verify:
**Filtering:**
- [ ] Excluded self (user.name, user.email, @user.domain)
- [ ] Applied relevance test to each person
+- [ ] Applied the direct interaction test to new People/Organizations
+- [ ] Applied the weekly importance test to new People/Organizations
- [ ] Transactional contacts in Org Contacts, not People notes
- [ ] Source correctly classified (process vs skip)
+- [ ] Third-party mentions did not become new canonical People/Organizations notes
+- [ ] Borderline People/Organizations became suggestion cards instead of canonical notes
**Content Quality:**
- [ ] Summaries describe relationship, not communication method
@@ -978,8 +1113,11 @@ Before completing, verify:
- [ ] All entity mentions use \`[[Folder/Name]]\` absolute links
- [ ] Activity entries are reverse chronological
- [ ] No duplicate activity entries
+- [ ] \`suggested-topics.md\` stays deduped and curated
+- [ ] High-quality Topics/Projects were added to suggested topics only when timely and useful
+- [ ] New Topics/Projects were not auto-created as canonical notes
- [ ] Dates are YYYY-MM-DD
- [ ] Bidirectional links are consistent
- [ ] New notes in correct folders
`;
-}
\ No newline at end of file
+}
diff --git a/apps/x/packages/core/src/knowledge/note_tagging_agent.ts b/apps/x/packages/core/src/knowledge/note_tagging_agent.ts
index 0dc581f1..8e9e3320 100644
--- a/apps/x/packages/core/src/knowledge/note_tagging_agent.ts
+++ b/apps/x/packages/core/src/knowledge/note_tagging_agent.ts
@@ -2,7 +2,6 @@ import { renderTagSystemForNotes } from './tag_system.js';
export function getRaw(): string {
return `---
-model: gpt-5.2
tools:
workspace-readFile:
type: builtin
diff --git a/apps/x/packages/core/src/knowledge/summarize_meeting.ts b/apps/x/packages/core/src/knowledge/summarize_meeting.ts
index 30e3c5d4..c7e7a71f 100644
--- a/apps/x/packages/core/src/knowledge/summarize_meeting.ts
+++ b/apps/x/packages/core/src/knowledge/summarize_meeting.ts
@@ -1,11 +1,8 @@
import fs from 'fs';
import path from 'path';
import { generateText } from 'ai';
-import container from '../di/container.js';
-import type { IModelConfigRepo } from '../models/repo.js';
import { createProvider } from '../models/models.js';
-import { isSignedIn } from '../account/account.js';
-import { getGatewayProvider } from '../models/gateway.js';
+import { getDefaultModelAndProvider, getMeetingNotesModel, resolveProviderConfig } from '../models/defaults.js';
import { WorkDir } from '../config/config.js';
const CALENDAR_SYNC_DIR = path.join(WorkDir, 'calendar_sync');
@@ -138,15 +135,10 @@ function loadCalendarEventContext(calendarEventJson: string): string {
}
export async function summarizeMeeting(transcript: string, meetingStartTime?: string, calendarEventJson?: string): Promise {
- const repo = container.resolve('modelConfigRepo');
- const config = await repo.getConfig();
- const signedIn = await isSignedIn();
- const provider = signedIn
- ? await getGatewayProvider()
- : createProvider(config.provider);
- const modelId = config.meetingNotesModel
- || (signedIn ? "gpt-5.4" : config.model);
- const model = provider.languageModel(modelId);
+ const modelId = await getMeetingNotesModel();
+ const { provider: providerName } = await getDefaultModelAndProvider();
+ const providerConfig = await resolveProviderConfig(providerName);
+ const model = createProvider(providerConfig).languageModel(modelId);
// If a specific calendar event was linked, use it directly.
// Otherwise fall back to scanning events within ±3 hours.
diff --git a/apps/x/packages/core/src/knowledge/sync_gmail.ts b/apps/x/packages/core/src/knowledge/sync_gmail.ts
index d00557a0..2aa48944 100644
--- a/apps/x/packages/core/src/knowledge/sync_gmail.ts
+++ b/apps/x/packages/core/src/knowledge/sync_gmail.ts
@@ -15,8 +15,52 @@ import { createEvent } from './track/events.js';
const SYNC_DIR = path.join(WorkDir, 'gmail_sync');
const SYNC_INTERVAL_MS = 5 * 60 * 1000; // Check every 5 minutes
const REQUIRED_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly';
+const MAX_THREADS_IN_DIGEST = 10;
const nhm = new NodeHtmlMarkdown();
+interface SyncedThread {
+ threadId: string;
+ markdown: string;
+}
+
+function summarizeGmailSync(threads: SyncedThread[]): string {
+ const lines: string[] = [
+ `# Gmail sync update`,
+ ``,
+ `${threads.length} new/updated thread${threads.length === 1 ? '' : 's'}.`,
+ ``,
+ ];
+
+ const shown = threads.slice(0, MAX_THREADS_IN_DIGEST);
+ const hidden = threads.length - shown.length;
+
+ if (shown.length > 0) {
+ lines.push(`## Threads`, ``);
+ for (const { markdown } of shown) {
+ lines.push(markdown.trimEnd(), ``, `---`, ``);
+ }
+ if (hidden > 0) {
+ lines.push(`_…and ${hidden} more thread(s) omitted from digest._`, ``);
+ }
+ }
+
+ return lines.join('\n');
+}
+
+async function publishGmailSyncEvent(threads: SyncedThread[]): Promise {
+ if (threads.length === 0) return;
+ try {
+ await createEvent({
+ source: 'gmail',
+ type: 'email.synced',
+ createdAt: new Date().toISOString(),
+ payload: summarizeGmailSync(threads),
+ });
+ } catch (err) {
+ console.error('[Gmail] Failed to publish sync event:', err);
+ }
+}
+
// --- Wake Signal for Immediate Sync Trigger ---
let wakeResolve: (() => void) | null = null;
@@ -113,14 +157,14 @@ async function saveAttachment(gmail: gmail.Gmail, userId: string, msgId: string,
// --- Sync Logic ---
-async function processThread(auth: OAuth2Client, threadId: string, syncDir: string, attachmentsDir: string) {
+async function processThread(auth: OAuth2Client, threadId: string, syncDir: string, attachmentsDir: string): Promise {
const gmail = google.gmail({ version: 'v1', auth });
try {
const res = await gmail.users.threads.get({ userId: 'me', id: threadId });
const thread = res.data;
const messages = thread.messages;
- if (!messages || messages.length === 0) return;
+ if (!messages || messages.length === 0) return null;
// Subject from first message
const firstHeader = messages[0].payload?.headers;
@@ -173,15 +217,11 @@ async function processThread(auth: OAuth2Client, threadId: string, syncDir: stri
fs.writeFileSync(path.join(syncDir, `${threadId}.md`), mdContent);
console.log(`Synced Thread: ${subject} (${threadId})`);
- await createEvent({
- source: 'gmail',
- type: 'email.synced',
- createdAt: new Date().toISOString(),
- payload: mdContent,
- });
+ return { threadId, markdown: mdContent };
} catch (error) {
console.error(`Error processing thread ${threadId}:`, error);
+ return null;
}
}
@@ -262,10 +302,14 @@ async function fullSync(auth: OAuth2Client, syncDir: string, attachmentsDir: str
truncated: limitedThreads.truncated,
});
+ const synced: SyncedThread[] = [];
for (const threadId of threadIds) {
- await processThread(auth, threadId, syncDir, attachmentsDir);
+ const result = await processThread(auth, threadId, syncDir, attachmentsDir);
+ if (result) synced.push(result);
}
+ await publishGmailSyncEvent(synced);
+
saveState(currentHistoryId, stateFile);
await serviceLogger.log({
type: 'run_complete',
@@ -365,10 +409,14 @@ async function partialSync(auth: OAuth2Client, startHistoryId: string, syncDir:
truncated: limitedThreads.truncated,
});
+ const synced: SyncedThread[] = [];
for (const tid of threadIdList) {
- await processThread(auth, tid, syncDir, attachmentsDir);
+ const result = await processThread(auth, tid, syncDir, attachmentsDir);
+ if (result) synced.push(result);
}
+ await publishGmailSyncEvent(synced);
+
const profile = await gmail.users.getProfile({ userId: 'me' });
saveState(profile.data.historyId!, stateFile);
await serviceLogger.log({
@@ -565,7 +613,12 @@ function extractBodyFromPayload(payload: Record): string {
return '';
}
-async function processThreadComposio(connectedAccountId: string, threadId: string, syncDir: string): Promise {
+interface ComposioThreadResult {
+ synced: SyncedThread | null;
+ newestIsoPlusOne: string | null;
+}
+
+async function processThreadComposio(connectedAccountId: string, threadId: string, syncDir: string): Promise {
let threadResult;
try {
threadResult = await executeAction(
@@ -579,40 +632,34 @@ async function processThreadComposio(connectedAccountId: string, threadId: strin
);
} catch (error) {
console.warn(`[Gmail] Skipping thread ${threadId} (fetch failed):`, error instanceof Error ? error.message : error);
- return null;
+ return { synced: null, newestIsoPlusOne: null };
}
if (!threadResult.successful || !threadResult.data) {
console.error(`[Gmail] Failed to fetch thread ${threadId}:`, threadResult.error);
- return null;
+ return { synced: null, newestIsoPlusOne: null };
}
const data = threadResult.data as Record;
const messages = data.messages as Array> | undefined;
let newestDate: Date | null = null;
+ let mdContent: string;
+ let subjectForLog: string;
if (!messages || messages.length === 0) {
const parsed = parseMessageData(data);
- const mdContent = `# ${parsed.subject}\n\n` +
+ mdContent = `# ${parsed.subject}\n\n` +
`**Thread ID:** ${threadId}\n` +
`**Message Count:** 1\n\n---\n\n` +
`### From: ${parsed.from}\n` +
`**Date:** ${parsed.date}\n\n` +
`${parsed.body}\n\n---\n\n`;
-
- fs.writeFileSync(path.join(syncDir, `${cleanFilename(threadId)}.md`), mdContent);
- console.log(`[Gmail] Synced Thread: ${parsed.subject} (${threadId})`);
- await createEvent({
- source: 'gmail',
- type: 'email.synced',
- createdAt: new Date().toISOString(),
- payload: mdContent,
- });
+ subjectForLog = parsed.subject;
newestDate = tryParseDate(parsed.date);
} else {
const firstParsed = parseMessageData(messages[0]);
- let mdContent = `# ${firstParsed.subject}\n\n`;
+ mdContent = `# ${firstParsed.subject}\n\n`;
mdContent += `**Thread ID:** ${threadId}\n`;
mdContent += `**Message Count:** ${messages.length}\n\n---\n\n`;
@@ -628,19 +675,14 @@ async function processThreadComposio(connectedAccountId: string, threadId: strin
newestDate = msgDate;
}
}
-
- fs.writeFileSync(path.join(syncDir, `${cleanFilename(threadId)}.md`), mdContent);
- console.log(`[Gmail] Synced Thread: ${firstParsed.subject} (${threadId})`);
- await createEvent({
- source: 'gmail',
- type: 'email.synced',
- createdAt: new Date().toISOString(),
- payload: mdContent,
- });
+ subjectForLog = firstParsed.subject;
}
- if (!newestDate) return null;
- return new Date(newestDate.getTime() + 1000).toISOString();
+ fs.writeFileSync(path.join(syncDir, `${cleanFilename(threadId)}.md`), mdContent);
+ console.log(`[Gmail] Synced Thread: ${subjectForLog} (${threadId})`);
+
+ const newestIsoPlusOne = newestDate ? new Date(newestDate.getTime() + 1000).toISOString() : null;
+ return { synced: { threadId, markdown: mdContent }, newestIsoPlusOne };
}
async function performSyncComposio() {
@@ -751,19 +793,22 @@ async function performSyncComposio() {
let highWaterMark: string | null = state?.last_sync ?? null;
let processedCount = 0;
+ const synced: SyncedThread[] = [];
for (const threadId of allThreadIds) {
// Re-check connection in case user disconnected mid-sync
if (!composioAccountsRepo.isConnected('gmail')) {
console.log('[Gmail] Account disconnected during sync. Stopping.');
- return;
+ break;
}
try {
- const newestInThread = await processThreadComposio(connectedAccountId, threadId, SYNC_DIR);
+ const result = await processThreadComposio(connectedAccountId, threadId, SYNC_DIR);
processedCount++;
- if (newestInThread) {
- if (!highWaterMark || new Date(newestInThread) > new Date(highWaterMark)) {
- highWaterMark = newestInThread;
+ if (result.synced) synced.push(result.synced);
+
+ if (result.newestIsoPlusOne) {
+ if (!highWaterMark || new Date(result.newestIsoPlusOne) > new Date(highWaterMark)) {
+ highWaterMark = result.newestIsoPlusOne;
}
saveComposioState(STATE_FILE, highWaterMark);
}
@@ -772,6 +817,8 @@ async function performSyncComposio() {
}
}
+ await publishGmailSyncEvent(synced);
+
await serviceLogger.log({
type: 'run_complete',
service: run!.service,
diff --git a/apps/x/packages/core/src/knowledge/tag_notes.ts b/apps/x/packages/core/src/knowledge/tag_notes.ts
index 8fdabb86..2d074ab7 100644
--- a/apps/x/packages/core/src/knowledge/tag_notes.ts
+++ b/apps/x/packages/core/src/knowledge/tag_notes.ts
@@ -2,6 +2,7 @@ import fs from 'fs';
import path from 'path';
import { WorkDir } from '../config/config.js';
import { createRun, createMessage } from '../runs/runs.js';
+import { getKgModel } from '../models/defaults.js';
import { bus } from '../runs/bus.js';
import { waitForRunCompletion } from '../agents/utils.js';
import { serviceLogger } from '../services/service_logger.js';
@@ -84,6 +85,7 @@ async function tagNoteBatch(
): Promise<{ runId: string; filesEdited: Set }> {
const run = await createRun({
agentId: NOTE_TAGGING_AGENT,
+ model: await getKgModel(),
});
let message = `Tag the following ${files.length} knowledge notes by prepending YAML frontmatter with appropriate tags.\n\n`;
diff --git a/apps/x/packages/core/src/knowledge/track/fileops.ts b/apps/x/packages/core/src/knowledge/track/fileops.ts
index bc741936..bd731823 100644
--- a/apps/x/packages/core/src/knowledge/track/fileops.ts
+++ b/apps/x/packages/core/src/knowledge/track/fileops.ts
@@ -5,6 +5,7 @@ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { WorkDir } from '../../config/config.js';
import { TrackBlockSchema } from '@x/shared/dist/track-block.js';
import { TrackStateSchema } from './types.js';
+import { withFileLock } from '../file-lock.js';
const KNOWLEDGE_DIR = path.join(WorkDir, 'knowledge');
@@ -81,42 +82,46 @@ export async function fetchYaml(filePath: string, trackId: string): Promise {
- let content = await fs.readFile(absPath(filePath), 'utf-8');
- const openTag = ``;
- const closeTag = ``;
- const openIdx = content.indexOf(openTag);
- const closeIdx = content.indexOf(closeTag);
- if (openIdx !== -1 && closeIdx !== -1 && closeIdx > openIdx) {
- content = content.slice(0, openIdx + openTag.length) + '\n' + newContent + '\n' + content.slice(closeIdx);
- } else {
- const block = await fetch(filePath, trackId);
- if (!block) {
- throw new Error(`Track ${trackId} not found in ${filePath}`);
+ return withFileLock(absPath(filePath), async () => {
+ let content = await fs.readFile(absPath(filePath), 'utf-8');
+ const openTag = ``;
+ const closeTag = ``;
+ const openIdx = content.indexOf(openTag);
+ const closeIdx = content.indexOf(closeTag);
+ if (openIdx !== -1 && closeIdx !== -1 && closeIdx > openIdx) {
+ content = content.slice(0, openIdx + openTag.length) + '\n' + newContent + '\n' + content.slice(closeIdx);
+ } else {
+ const block = await fetch(filePath, trackId);
+ if (!block) {
+ throw new Error(`Track ${trackId} not found in ${filePath}`);
+ }
+ const lines = content.split('\n');
+ const insertAt = Math.min(block.fenceEnd + 1, lines.length);
+ const contentFence = [openTag, newContent, closeTag];
+ lines.splice(insertAt, 0, ...contentFence);
+ content = lines.join('\n');
}
- const lines = content.split('\n');
- const insertAt = Math.min(block.fenceEnd + 1, lines.length);
- const contentFence = [openTag, newContent, closeTag];
- lines.splice(insertAt, 0, ...contentFence);
- content = lines.join('\n');
- }
- await fs.writeFile(absPath(filePath), content, 'utf-8');
+ await fs.writeFile(absPath(filePath), content, 'utf-8');
+ });
}
export async function updateTrackBlock(filepath: string, trackId: string, updates: Partial>): Promise {
- const block = await fetch(filepath, trackId);
- if (!block) {
- throw new Error(`Track ${trackId} not found in ${filepath}`);
- }
- block.track = { ...block.track, ...updates };
+ return withFileLock(absPath(filepath), async () => {
+ const block = await fetch(filepath, trackId);
+ if (!block) {
+ throw new Error(`Track ${trackId} not found in ${filepath}`);
+ }
+ block.track = { ...block.track, ...updates };
- // read file contents
- let content = await fs.readFile(absPath(filepath), 'utf-8');
- const lines = content.split('\n');
- const yaml = stringifyYaml(block.track).trimEnd();
- const yamlLines = yaml ? yaml.split('\n') : [];
- lines.splice(block.fenceStart, block.fenceEnd - block.fenceStart + 1, '```track', ...yamlLines, '```');
- content = lines.join('\n');
- await fs.writeFile(absPath(filepath), content, 'utf-8');
+ // read file contents
+ let content = await fs.readFile(absPath(filepath), 'utf-8');
+ const lines = content.split('\n');
+ const yaml = stringifyYaml(block.track).trimEnd();
+ const yamlLines = yaml ? yaml.split('\n') : [];
+ lines.splice(block.fenceStart, block.fenceEnd - block.fenceStart + 1, '```track', ...yamlLines, '```');
+ content = lines.join('\n');
+ await fs.writeFile(absPath(filepath), content, 'utf-8');
+ });
}
/**
@@ -127,64 +132,68 @@ export async function updateTrackBlock(filepath: string, trackId: string, update
* otherwise the write is rejected.
*/
export async function replaceTrackBlockYaml(filePath: string, trackId: string, newYaml: string): Promise {
- const block = await fetch(filePath, trackId);
- if (!block) {
- throw new Error(`Track ${trackId} not found in ${filePath}`);
- }
- const parsed = TrackBlockSchema.safeParse(parseYaml(newYaml));
- if (!parsed.success) {
- throw new Error(`Invalid track YAML: ${parsed.error.message}`);
- }
- if (parsed.data.trackId !== trackId) {
- throw new Error(`trackId cannot be changed (was "${trackId}", got "${parsed.data.trackId}")`);
- }
+ return withFileLock(absPath(filePath), async () => {
+ const block = await fetch(filePath, trackId);
+ if (!block) {
+ throw new Error(`Track ${trackId} not found in ${filePath}`);
+ }
+ const parsed = TrackBlockSchema.safeParse(parseYaml(newYaml));
+ if (!parsed.success) {
+ throw new Error(`Invalid track YAML: ${parsed.error.message}`);
+ }
+ if (parsed.data.trackId !== trackId) {
+ throw new Error(`trackId cannot be changed (was "${trackId}", got "${parsed.data.trackId}")`);
+ }
- const content = await fs.readFile(absPath(filePath), 'utf-8');
- const lines = content.split('\n');
- const yamlLines = newYaml.trimEnd().split('\n');
- lines.splice(block.fenceStart, block.fenceEnd - block.fenceStart + 1, '```track', ...yamlLines, '```');
- await fs.writeFile(absPath(filePath), lines.join('\n'), 'utf-8');
+ const content = await fs.readFile(absPath(filePath), 'utf-8');
+ const lines = content.split('\n');
+ const yamlLines = newYaml.trimEnd().split('\n');
+ lines.splice(block.fenceStart, block.fenceEnd - block.fenceStart + 1, '```track', ...yamlLines, '```');
+ await fs.writeFile(absPath(filePath), lines.join('\n'), 'utf-8');
+ });
}
/**
* Remove a track block and its sibling target region from the file.
*/
export async function deleteTrackBlock(filePath: string, trackId: string): Promise {
- const block = await fetch(filePath, trackId);
- if (!block) {
- // Already gone — treat as success.
- return;
- }
-
- const content = await fs.readFile(absPath(filePath), 'utf-8');
- const lines = content.split('\n');
- const openTag = ``;
- const closeTag = ``;
-
- // Find target region (may not exist)
- let targetStart = -1;
- let targetEnd = -1;
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].includes(openTag)) { targetStart = i; }
- if (targetStart !== -1 && lines[i].includes(closeTag)) { targetEnd = i; break; }
- }
-
- // Build a list of [start, end] ranges to remove, sorted descending so
- // indices stay valid as we splice.
- const ranges: Array<[number, number]> = [];
- ranges.push([block.fenceStart, block.fenceEnd]);
- if (targetStart !== -1 && targetEnd !== -1 && targetEnd >= targetStart) {
- ranges.push([targetStart, targetEnd]);
- }
- ranges.sort((a, b) => b[0] - a[0]);
-
- for (const [start, end] of ranges) {
- lines.splice(start, end - start + 1);
- // Also drop a trailing blank line if the removal left two in a row.
- if (start < lines.length && lines[start].trim() === '' && start > 0 && lines[start - 1].trim() === '') {
- lines.splice(start, 1);
+ return withFileLock(absPath(filePath), async () => {
+ const block = await fetch(filePath, trackId);
+ if (!block) {
+ // Already gone — treat as success.
+ return;
}
- }
- await fs.writeFile(absPath(filePath), lines.join('\n'), 'utf-8');
+ const content = await fs.readFile(absPath(filePath), 'utf-8');
+ const lines = content.split('\n');
+ const openTag = ``;
+ const closeTag = ``;
+
+ // Find target region (may not exist)
+ let targetStart = -1;
+ let targetEnd = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(openTag)) { targetStart = i; }
+ if (targetStart !== -1 && lines[i].includes(closeTag)) { targetEnd = i; break; }
+ }
+
+ // Build a list of [start, end] ranges to remove, sorted descending so
+ // indices stay valid as we splice.
+ const ranges: Array<[number, number]> = [];
+ ranges.push([block.fenceStart, block.fenceEnd]);
+ if (targetStart !== -1 && targetEnd !== -1 && targetEnd >= targetStart) {
+ ranges.push([targetStart, targetEnd]);
+ }
+ ranges.sort((a, b) => b[0] - a[0]);
+
+ for (const [start, end] of ranges) {
+ lines.splice(start, end - start + 1);
+ // Also drop a trailing blank line if the removal left two in a row.
+ if (start < lines.length && lines[start].trim() === '' && start > 0 && lines[start - 1].trim() === '') {
+ lines.splice(start, 1);
+ }
+ }
+
+ await fs.writeFile(absPath(filePath), lines.join('\n'), 'utf-8');
+ });
}
\ No newline at end of file
diff --git a/apps/x/packages/core/src/knowledge/track/routing.ts b/apps/x/packages/core/src/knowledge/track/routing.ts
index f876106e..6f8f3824 100644
--- a/apps/x/packages/core/src/knowledge/track/routing.ts
+++ b/apps/x/packages/core/src/knowledge/track/routing.ts
@@ -1,11 +1,8 @@
import { generateObject } from 'ai';
import { trackBlock, PrefixLogger } from '@x/shared';
import type { KnowledgeEvent } from '@x/shared/dist/track-block.js';
-import container from '../../di/container.js';
-import type { IModelConfigRepo } from '../../models/repo.js';
import { createProvider } from '../../models/models.js';
-import { isSignedIn } from '../../account/account.js';
-import { getGatewayProvider } from '../../models/gateway.js';
+import { getDefaultModelAndProvider, getTrackBlockModel, resolveProviderConfig } from '../../models/defaults.js';
const log = new PrefixLogger('TrackRouting');
@@ -37,15 +34,10 @@ Rules:
- For each candidate, return BOTH trackId and filePath exactly as given. trackIds are not globally unique.`;
async function resolveModel() {
- const repo = container.resolve('modelConfigRepo');
- const config = await repo.getConfig();
- const signedIn = await isSignedIn();
- const provider = signedIn
- ? await getGatewayProvider()
- : createProvider(config.provider);
- const modelId = config.knowledgeGraphModel
- || (signedIn ? 'gpt-5.4' : config.model);
- return provider.languageModel(modelId);
+ const model = await getTrackBlockModel();
+ const { provider } = await getDefaultModelAndProvider();
+ const config = await resolveProviderConfig(provider);
+ return createProvider(config).languageModel(model);
}
function buildRoutingPrompt(event: KnowledgeEvent, batch: ParsedTrack[]): string {
diff --git a/apps/x/packages/core/src/knowledge/track/run-agent.ts b/apps/x/packages/core/src/knowledge/track/run-agent.ts
index 9edc7c4f..d93366f3 100644
--- a/apps/x/packages/core/src/knowledge/track/run-agent.ts
+++ b/apps/x/packages/core/src/knowledge/track/run-agent.ts
@@ -3,50 +3,301 @@ import { Agent, ToolAttachment } from '@x/shared/dist/agent.js';
import { BuiltinTools } from '../../application/lib/builtin-tools.js';
import { WorkDir } from '../../config/config.js';
-const TRACK_RUN_INSTRUCTIONS = `You are a track block runner — a background agent that updates a specific section of a knowledge note.
+const TRACK_RUN_INSTRUCTIONS = `You are a track block runner — a background agent that keeps a live section of a user's personal knowledge note up to date.
-You will receive a message containing a track instruction, the current content of the target region, and optionally some context. Your job is to follow the instruction and produce updated content.
+Your goal on each run: produce the most useful, up-to-date version of that section given the track's instruction. The user is maintaining a personal knowledge base and will glance at this output alongside many others — optimize for **information density and scannability**, not conversational prose.
# Background Mode
-You are running as a background task — there is no user present.
-- Do NOT ask clarifying questions — make reasonable assumptions
-- Be concise and action-oriented — just do the work
+You are running as a scheduled or event-triggered background task — **there is no user present** to clarify, approve, or watch.
+- Do NOT ask clarifying questions — make the most reasonable interpretation of the instruction and proceed.
+- Do NOT hedge or preamble ("I'll now...", "Let me..."). Just do the work.
+- Do NOT produce chat-style output. The user sees only the content you write into the target region plus your final summary line.
+
+# Message Anatomy
+
+Every run message has this shape:
+
+ Update track **** in \`\`.
+
+ **Time:** ()
+
+ **Instruction:**
+
+
+ **Current content:**
+
+
+ Use \`update-track-content\` with filePath=\`\` and trackId=\`\`.
+
+For **manual** runs, an optional trailing block may appear:
+
+ **Context:**
+
+
+Apply context for this run only — it is not a permanent edit to the instruction.
+
+For **event-triggered** runs, a trailing block appears instead:
+
+ **Trigger:** Event match (a Pass 1 routing classifier flagged this track as potentially relevant)
+ **Event match criteria for this track:**
+ **Event payload:**
+ **Decision:** ... skip if not relevant ...
+
+On event runs you are the Pass 2 judge — see "The No-Update Decision" below.
+
+# What Good Output Looks Like
+
+This is a personal knowledge tracker. The user scans many such blocks across their notes. Write for a reader who wants the answer to "what's current / what changed?" in the fewest words that carry real information.
+
+- **Data-forward.** Tables, bullet lists, one-line statuses. Not paragraphs.
+- **Format follows the instruction.** If the instruction specifies a shape ("3-column markdown table: Location | Local Time | Offset"), use exactly that shape. The instruction is authoritative — do not improvise a different layout.
+- **No decoration.** No adjectives like "polished", "beautiful". No framing prose ("Here's your update:"). No emoji unless the instruction asks.
+- **No commentary or caveats** unless the data itself is genuinely uncertain in a way the user needs to know.
+- **No self-reference.** Do not write "I updated this at X" — the system records timestamps separately.
+
+If the instruction does not specify a format, pick the tightest shape that fits: a single line for a single metric, a small table for 2+ parallel items, a short bulleted list for a digest, or one of the **rich block types below** when the data has a natural visual form (events → \`calendar\`, time series → \`chart\`, relationships → \`mermaid\`, etc.).
+
+# Output Block Types
+
+The note renderer turns specially-tagged fenced code blocks into styled UI: tables, charts, calendars, embeds, and more. Reach for these when the data has structure that benefits from a visual treatment; stay with plain markdown when prose, a markdown table, or bullets carry the meaning just as well. Pick **at most one block per output region** unless the instruction asks for a multi-section layout — and follow the exact fence language and shape, since anything unparseable renders as a small "Invalid X block" error card.
+
+Do **not** emit \`track\` or \`task\` blocks — those are user-authored input mechanisms, not agent outputs.
+
+## \`table\` — tabular data (JSON)
+
+Use for: scoreboards, leaderboards, comparisons, multi-row status digests.
+
+\`\`\`table
+{
+ "title": "Top stories on Hacker News",
+ "columns": ["Rank", "Title", "Points", "Comments"],
+ "data": [
+ {"Rank": 1, "Title": "Show HN: ...", "Points": 842, "Comments": 312},
+ {"Rank": 2, "Title": "...", "Points": 530, "Comments": 144}
+ ]
+}
+\`\`\`
+
+Required: \`columns\` (string[]), \`data\` (array of objects keyed by column name). Optional: \`title\`.
+
+## \`chart\` — line / bar / pie chart (JSON)
+
+Use for: time series, categorical breakdowns, share-of-total. Skip if a single sentence carries the meaning.
+
+\`\`\`chart
+{
+ "chart": "line",
+ "title": "USD/INR — last 7 days",
+ "x": "date",
+ "y": "rate",
+ "data": [
+ {"date": "2026-04-13", "rate": 83.41},
+ {"date": "2026-04-14", "rate": 83.38}
+ ]
+}
+\`\`\`
+
+Required: \`chart\` ("line" | "bar" | "pie"), \`x\` (field name on each row), \`y\` (field name on each row), and **either** \`data\` (inline array of objects) **or** \`source\` (workspace path to a JSON-array file). Optional: \`title\`.
+
+## \`mermaid\` — diagrams (raw Mermaid source)
+
+Use for: relationship maps, flowcharts, sequence diagrams, gantt charts, mind maps.
+
+\`\`\`mermaid
+graph LR
+ A[Project Alpha] --> B[Sarah Chen]
+ A --> C[Acme Corp]
+ B --> D[Q3 Launch]
+\`\`\`
+
+Body is plain Mermaid source — no JSON wrapper.
+
+## \`calendar\` — list of events (JSON)
+
+Use for: upcoming meetings, agenda digests, day/week views.
+
+\`\`\`calendar
+{
+ "title": "Today",
+ "events": [
+ {
+ "summary": "1:1 with Sarah",
+ "start": {"dateTime": "2026-04-20T10:00:00-07:00"},
+ "end": {"dateTime": "2026-04-20T10:30:00-07:00"},
+ "location": "Zoom",
+ "conferenceLink": "https://zoom.us/j/..."
+ }
+ ]
+}
+\`\`\`
+
+Required: \`events\` (array). Each event optionally has \`summary\`, \`start\`/\`end\` (object with \`dateTime\` ISO string OR \`date\` "YYYY-MM-DD" for all-day), \`location\`, \`htmlLink\`, \`conferenceLink\`, \`source\`. Optional top-level: \`title\`, \`showJoinButton\` (bool).
+
+## \`email\` — single email or thread digest (JSON)
+
+Use for: surfacing one important thread — latest message body, summary of prior context, optional draft reply.
+
+\`\`\`email
+{
+ "subject": "Q3 launch readiness",
+ "from": "sarah@acme.com",
+ "date": "2026-04-19T16:42:00Z",
+ "summary": "Sarah confirms timeline; flagged blocker on infra capacity.",
+ "latest_email": "Hey — quick update on Q3...\\n\\nThanks,\\nSarah"
+}
+\`\`\`
+
+Required: \`latest_email\` (string). Optional: \`threadId\`, \`summary\`, \`subject\`, \`from\`, \`to\`, \`date\`, \`past_summary\`, \`draft_response\`, \`response_mode\` ("inline" | "assistant" | "both").
+
+For digests of **many** threads, prefer a \`table\` (Subject | From | Snippet) — \`email\` is for one thread at a time.
+
+## \`image\` — single image (JSON)
+
+Use for: charts, screenshots, photos you have a URL or workspace path for.
+
+\`\`\`image
+{
+ "src": "https://example.com/forecast.png",
+ "alt": "Weather forecast",
+ "caption": "Bay Area · April 20"
+}
+\`\`\`
+
+Required: \`src\` (URL or workspace path). Optional: \`alt\`, \`caption\`.
+
+## \`embed\` — YouTube / Figma embed (JSON)
+
+Use for: linking to a video or design that should render inline.
+
+\`\`\`embed
+{
+ "provider": "youtube",
+ "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ "caption": "Latest demo"
+}
+\`\`\`
+
+Required: \`provider\` ("youtube" | "figma" | "generic"), \`url\`. Optional: \`caption\`. The renderer rewrites known URLs to their embed form.
+
+## \`iframe\` — arbitrary embedded webpage (JSON)
+
+Use for: live dashboards, status pages, trackers — anything that has its own webpage and benefits from being live, not snapshotted.
+
+\`\`\`iframe
+{
+ "url": "https://status.example.com",
+ "title": "Service status",
+ "height": 600
+}
+\`\`\`
+
+Required: \`url\` (must be \`https://\` or \`http://localhost\`). Optional: \`title\`, \`caption\`, \`height\` (240–1600), \`allow\` (Permissions-Policy string).
+
+## \`transcript\` — long transcript (JSON)
+
+Use for: meeting transcripts, voice-note dumps — bodies that benefit from a collapsible UI.
+
+\`\`\`transcript
+{"transcript": "[00:00] Speaker A: Welcome everyone..."}
+\`\`\`
+
+Required: \`transcript\` (string).
+
+## \`prompt\` — starter Copilot prompt (YAML)
+
+Use for: end-of-output "next step" cards. The user clicks **Run** and the chat sidebar opens with the underlying instruction submitted to Copilot, with this note attached as a file mention.
+
+\`\`\`prompt
+label: Draft replies to today's emails
+instruction: |
+ For each unanswered email in the digest above, draft a 2-line reply
+ in my voice and present them as a checklist for me to approve.
+\`\`\`
+
+Required: \`label\` (short title shown on the card), \`instruction\` (the longer prompt). Note: this block uses **YAML**, not JSON.
+
+# Interpreting the Instruction
+
+The instruction was authored in a prior conversation you cannot see. Treat it as a **self-contained spec**. If ambiguous, pick what a reasonable user of a knowledge tracker would expect:
+- "Top 5" is a target — fewer is acceptable if that's all that exists.
+- "Current" means as of now (use the **Time** block).
+- Unspecified units → standard for the domain (USD for US markets, metric for scientific, the user's locale if inferable from the timezone).
+- Unspecified sources → your best reliable source (web-search for public data, workspace for user data).
+
+Do **not** invent parts of the instruction the user did not write ("also include a fun fact", "summarize trends") — these are decoration.
+
+# Current Content Handling
+
+The **Current content** block shows what lives in the target region right now. Three cases:
+
+1. **"(empty — first run)"** — produce the content from scratch.
+2. **Content that matches the instruction's format** — this is a previous run's output. Usually produce a fresh complete replacement. Only preserve parts of it if the instruction says to **accumulate** (e.g., "maintain a running log of..."), or if discarding would lose information the instruction intended to keep.
+3. **Content that does NOT match the instruction's format** — the instruction may have changed, or the user edited the block by hand. Regenerate fresh to the current instruction. Do not try to patch.
+
+You always write a **complete** replacement, not a diff.
+
+# The No-Update Decision
+
+You may finish a run without calling \`update-track-content\`. Two legitimate cases:
+
+1. **Event-triggered run, event is not actually relevant.** The Pass 1 classifier is liberal by design. On closer reading, if the event does not genuinely add or change information that should be in this track, skip the update.
+2. **Scheduled/manual run, no meaningful change.** If you fetch fresh data and the result would be identical to the current content, you may skip the write. The system will record "no update" automatically.
+
+When skipping, still end with a summary line (see "Final Summary" below) so the system records *why*.
+
+# Writing the Result
+
+Call \`update-track-content\` **at most once per run**:
+- Pass \`filePath\` and \`trackId\` exactly as given in the message.
+- Pass the **complete** new content as \`content\` — the entire replacement for the target region.
+- Do **not** include the track-target HTML comments (\`\`) — the tool manages those.
+- Do **not** modify the track's YAML configuration or any other part of the note. Your surface area is the target region only.
+
+# Tools
+
+You have the full workspace toolkit. Quick reference for common cases:
+
+- **\`web-search\`** — the public web (news, prices, status pages, documentation). Use when the instruction needs information beyond the workspace.
+- **\`workspace-readFile\`, \`workspace-grep\`, \`workspace-glob\`, \`workspace-readdir\`** — read and search the user's knowledge graph and synced data.
+- **\`parseFile\`, \`LLMParse\`** — parse PDFs, spreadsheets, Word docs if a track aggregates from attached files.
+- **\`composio-*\`, \`listMcpTools\`, \`executeMcpTool\`** — user-connected integrations (Gmail, Calendar, etc.). Prefer these when a track needs structured data from a connected service the user has authorized.
+- **\`browser-control\`** — only when a required source has no API / search alternative and requires JS rendering.
# The Knowledge Graph
-The knowledge graph is stored as plain markdown in \`${WorkDir}/knowledge/\` (inside the workspace). It's organized into:
-- **People/** — Notes on individuals
-- **Organizations/** — Notes on companies
-- **Projects/** — Notes on initiatives
-- **Topics/** — Notes on recurring themes
+The user's knowledge graph is plain markdown in \`${WorkDir}/knowledge/\`, organized into:
+- **People/** — individuals
+- **Organizations/** — companies
+- **Projects/** — initiatives
+- **Topics/** — recurring themes
-Use workspace tools to search and read the knowledge graph for context.
+Synced external data often sits alongside under \`gmail_sync/\`, \`calendar_sync/\`, \`granola_sync/\`, \`fireflies_sync/\` — consult these when an instruction references emails, meetings, or calendar events.
-# How to Access the Knowledge Graph
-
-**CRITICAL:** Always include \`knowledge/\` in paths.
+**CRITICAL:** Always include the folder prefix in paths. Never pass an empty path or the workspace root.
- \`workspace-grep({ pattern: "Acme", path: "knowledge/" })\`
- \`workspace-readFile("knowledge/People/Sarah Chen.md")\`
-- \`workspace-readdir("knowledge/People")\`
+- \`workspace-readdir("gmail_sync/")\`
-**NEVER** use an empty path or root path.
+# Failure & Fallback
-# How to Write Your Result
+If you cannot complete the instruction (network failure, missing data source, unparseable response, disconnected integration):
+- Do **not** fabricate or speculate.
+- Do **not** write partial or placeholder content into the target region — leave existing content intact by not calling \`update-track-content\`.
+- Explain the failure in the summary line.
-Use the \`update-track-content\` tool to write your result. The message will tell you the file path and track ID.
+# Final Summary
-- Produce the COMPLETE replacement content (not a diff)
-- Preserve existing content that's still relevant
-- Write in a clear, concise style appropriate for personal notes
+End your response with **one line** (1-2 short sentences). The system stores this as \`lastRunSummary\` and surfaces it in the UI.
-# Web Search
+State the action and the substance. Good examples:
+- "Updated — 3 new HN stories, top is 'Show HN: …' at 842 pts."
+- "Updated — USD/INR 83.42 as of 14:05 IST."
+- "No change — status page shows all operational."
+- "Skipped — event was a calendar invite unrelated to Q3 planning."
+- "Failed — web-search returned no results for the query."
-You have access to \`web-search\` for tracks that need external information (news, trends, current events). Use it when the track instruction requires information beyond the knowledge graph.
-
-# After You're Done
-
-End your response with a brief summary of what you did (1-2 sentences).
+Avoid: "I updated the track.", "Done!", "Here is the update:". The summary is a data point, not a sign-off.
`;
export function buildTrackRunAgent(): z.infer {
diff --git a/apps/x/packages/core/src/knowledge/track/runner.ts b/apps/x/packages/core/src/knowledge/track/runner.ts
index 5ee90024..1eec3da1 100644
--- a/apps/x/packages/core/src/knowledge/track/runner.ts
+++ b/apps/x/packages/core/src/knowledge/track/runner.ts
@@ -1,6 +1,7 @@
import z from 'zod';
import { fetchAll, updateTrackBlock } from './fileops.js';
import { createRun, createMessage } from '../../runs/runs.js';
+import { getTrackBlockModel } from '../../models/defaults.js';
import { extractAgentResponse, waitForRunCompletion } from '../../agents/utils.js';
import { trackBus } from './bus.js';
import type { TrackStateSchema } from './types.js';
@@ -101,8 +102,15 @@ export async function triggerTrackUpdate(
const contentBefore = track.content;
- // Emit start event — runId is set after agent run is created
- const agentRun = await createRun({ agentId: 'track-run' });
+ // Per-track model/provider overrides win when set; otherwise fall back
+ // to the configured trackBlockModel default and the run-creation
+ // provider default (signed-in: rowboat; BYOK: active provider).
+ const model = track.track.model ?? await getTrackBlockModel();
+ const agentRun = await createRun({
+ agentId: 'track-run',
+ model,
+ ...(track.track.provider ? { provider: track.track.provider } : {}),
+ });
// Set lastRunAt and lastRunId immediately (before agent executes) so
// the scheduler's next poll won't re-trigger this track.
diff --git a/apps/x/packages/core/src/local-sites/server.ts b/apps/x/packages/core/src/local-sites/server.ts
new file mode 100644
index 00000000..f1fb4c7e
--- /dev/null
+++ b/apps/x/packages/core/src/local-sites/server.ts
@@ -0,0 +1,606 @@
+import fs from 'node:fs';
+import fsp from 'node:fs/promises';
+import path from 'node:path';
+import type { Server } from 'node:http';
+import chokidar, { type FSWatcher } from 'chokidar';
+import express from 'express';
+import { WorkDir } from '../config/config.js';
+import { LOCAL_SITE_SCAFFOLD } from './templates.js';
+
+export const LOCAL_SITES_PORT = 3210;
+export const LOCAL_SITES_BASE_URL = `http://localhost:${LOCAL_SITES_PORT}`;
+
+const LOCAL_SITES_DIR = path.join(WorkDir, 'sites');
+const SITE_SLUG_RE = /^[a-z0-9][a-z0-9-_]*$/i;
+const IFRAME_HEIGHT_MESSAGE = 'rowboat:iframe-height';
+const SITE_RELOAD_MESSAGE = 'rowboat:site-changed';
+const SITE_EVENTS_PATH = '__rowboat_events';
+const SITE_RELOAD_DEBOUNCE_MS = 140;
+const SITE_EVENTS_RETRY_MS = 1000;
+const SITE_EVENTS_HEARTBEAT_MS = 15000;
+const TEXT_EXTENSIONS = new Set([
+ '.css',
+ '.html',
+ '.js',
+ '.json',
+ '.map',
+ '.mjs',
+ '.svg',
+ '.txt',
+ '.xml',
+]);
+const MIME_TYPES: Record = {
+ '.css': 'text/css; charset=utf-8',
+ '.gif': 'image/gif',
+ '.html': 'text/html; charset=utf-8',
+ '.ico': 'image/x-icon',
+ '.jpeg': 'image/jpeg',
+ '.jpg': 'image/jpeg',
+ '.js': 'application/javascript; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.map': 'application/json; charset=utf-8',
+ '.mjs': 'application/javascript; charset=utf-8',
+ '.png': 'image/png',
+ '.svg': 'image/svg+xml; charset=utf-8',
+ '.txt': 'text/plain; charset=utf-8',
+ '.wasm': 'application/wasm',
+ '.webp': 'image/webp',
+ '.xml': 'application/xml; charset=utf-8',
+};
+const IFRAME_AUTOSIZE_BOOTSTRAP = String.raw``;
+
+let localSitesServer: Server | null = null;
+let startPromise: Promise | null = null;
+let localSitesWatcher: FSWatcher | null = null;
+const siteEventClients = new Map>();
+const siteReloadTimers = new Map();
+
+function isSafeSiteSlug(siteSlug: string): boolean {
+ return SITE_SLUG_RE.test(siteSlug);
+}
+
+function resolveSiteDir(siteSlug: string): string | null {
+ if (!isSafeSiteSlug(siteSlug)) return null;
+ return path.join(LOCAL_SITES_DIR, siteSlug);
+}
+
+function resolveRequestedPath(siteDir: string, requestPath: string): string | null {
+ const candidate = requestPath === '/' ? '/index.html' : requestPath;
+ const normalized = path.posix.normalize(candidate);
+ const relativePath = normalized.replace(/^\/+/, '');
+
+ if (!relativePath || relativePath === '.' || relativePath.startsWith('..') || relativePath.includes('\0')) {
+ return null;
+ }
+
+ const absolutePath = path.resolve(siteDir, relativePath);
+ if (!absolutePath.startsWith(siteDir + path.sep) && absolutePath !== siteDir) {
+ return null;
+ }
+
+ return absolutePath;
+}
+
+function getRequestPath(req: express.Request): string {
+ const rawPath = req.url.split('?')[0] || '/';
+ return rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
+}
+
+function listLocalSites(): Array<{ slug: string; url: string }> {
+ if (!fs.existsSync(LOCAL_SITES_DIR)) return [];
+
+ return fs.readdirSync(LOCAL_SITES_DIR, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory() && isSafeSiteSlug(entry.name))
+ .map((entry) => ({
+ slug: entry.name,
+ url: `${LOCAL_SITES_BASE_URL}/sites/${entry.name}/`,
+ }))
+ .sort((a, b) => a.slug.localeCompare(b.slug));
+}
+
+function isPathInsideRoot(rootPath: string, candidatePath: string): boolean {
+ return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
+}
+
+async function writeIfMissing(filePath: string, content: string): Promise {
+ try {
+ await fsp.access(filePath);
+ } catch {
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
+ await fsp.writeFile(filePath, content, 'utf8');
+ }
+}
+
+async function ensureLocalSiteScaffold(): Promise {
+ await fsp.mkdir(LOCAL_SITES_DIR, { recursive: true });
+
+ await Promise.all(
+ Object.entries(LOCAL_SITE_SCAFFOLD).map(([relativePath, content]) =>
+ writeIfMissing(path.join(LOCAL_SITES_DIR, relativePath), content),
+ ),
+ );
+}
+
+function injectIframeAutosizeBootstrap(html: string): string {
+ const bootstrap = IFRAME_AUTOSIZE_BOOTSTRAP
+ .replace('__ROWBOAT_IFRAME_HEIGHT_MESSAGE__', IFRAME_HEIGHT_MESSAGE)
+ .replace('__ROWBOAT_SITE_CHANGED_MESSAGE__', SITE_RELOAD_MESSAGE)
+ .replace('__ROWBOAT_SITE_EVENTS_PATH__', SITE_EVENTS_PATH)
+ if (/<\/body>/i.test(html)) {
+ return html.replace(/<\/body>/i, `${bootstrap}\n