mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
21 files changed
+649
-94
No files matched your search
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.9.6] - 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- ⏰ **Follow-up timers for chats.** Computer can now return to a chat at the right time to continue work, check again, or follow up.
|
||||
|
||||
### Changed
|
||||
|
||||
- ✨ **Clearer change reviews.** Changes in files are easier to spot, including larger edits.
|
||||
|
||||
## [0.9.5] - 2026-07-11
|
||||
|
||||
### Added
|
||||
|
||||
+11
@@ -71,6 +71,11 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
app.state.scheduler_task = asyncio.create_task(scheduler_worker_loop(app))
|
||||
|
||||
from cptr.utils.timers import recover_timers, timer_worker_loop
|
||||
|
||||
await recover_timers()
|
||||
app.state.timer_task = asyncio.create_task(timer_worker_loop(app))
|
||||
|
||||
# Start messaging bots
|
||||
from cptr.utils.bridge import BotManager
|
||||
|
||||
@@ -80,6 +85,12 @@ async def lifespan(app: FastAPI):
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
timer_task = getattr(app.state, "timer_task", None)
|
||||
if timer_task:
|
||||
timer_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await timer_task
|
||||
|
||||
scheduler_task = getattr(app.state, "scheduler_task", None)
|
||||
if scheduler_task:
|
||||
scheduler_task.cancel()
|
||||
|
||||
+3
-3
@@ -20,6 +20,7 @@ def _env_int(name: str, default: int) -> int:
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
# ── Data directory ──────────────────────────────────────────
|
||||
# Where cptr stores its database, config, and user data.
|
||||
# Default: ~/.cptr
|
||||
@@ -32,9 +33,7 @@ LOG_LEVEL = os.environ.get("CPTR_LOG_LEVEL", "INFO").upper()
|
||||
LOG_FORMAT = os.environ.get("CPTR_LOG_FORMAT", "text").lower()
|
||||
|
||||
AUDIT_LOG_LEVEL = os.environ.get("CPTR_AUDIT_LOG_LEVEL", "NONE").upper()
|
||||
AUDIT_LOG_PATH = Path(
|
||||
os.environ.get("CPTR_AUDIT_LOG_PATH", str(DATA_DIR / "logs" / "audit.jsonl"))
|
||||
)
|
||||
AUDIT_LOG_PATH = Path(os.environ.get("CPTR_AUDIT_LOG_PATH", str(DATA_DIR / "logs" / "audit.jsonl")))
|
||||
AUDIT_LOG_ROTATION = os.environ.get("CPTR_AUDIT_LOG_ROTATION", "10 MB")
|
||||
AUDIT_MAX_BODY_SIZE = _env_int("CPTR_AUDIT_MAX_BODY_SIZE", 2048)
|
||||
AUDIT_EXCLUDED_PATHS = [
|
||||
@@ -82,6 +81,7 @@ STREAM_WRITE_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_WRITE_TIMEOUT",
|
||||
|
||||
# ── Automation scheduler ────────────────────────────────────
|
||||
AUTOMATION_POLL_INTERVAL = int(os.environ.get("AUTOMATION_POLL_INTERVAL", "10"))
|
||||
TIMER_POLL_INTERVAL = int(os.environ.get("TIMER_POLL_INTERVAL", "1"))
|
||||
|
||||
# ── CORS ────────────────────────────────────────────────────
|
||||
# Socket.IO CORS allowed origins.
|
||||
|
||||
+20
-1
@@ -26,6 +26,16 @@ class EventDefinition:
|
||||
|
||||
|
||||
class EventDefinitions:
|
||||
CHAT_READ = EventDefinition(
|
||||
"chat.read",
|
||||
"The user explicitly marked a chat as read.",
|
||||
"Chat read",
|
||||
)
|
||||
CHAT_USER_MESSAGE = EventDefinition(
|
||||
"chat.user_message",
|
||||
"A user message was added to a chat.",
|
||||
"User message",
|
||||
)
|
||||
CHAT_FINISHED = EventDefinition(
|
||||
"chat.finished",
|
||||
"A chat run finished successfully.",
|
||||
@@ -191,7 +201,16 @@ class NotificationEventSink:
|
||||
await dispatch_notification_event(event)
|
||||
|
||||
|
||||
EVENT_SINKS = [NotificationEventSink()]
|
||||
class TimerEventSink:
|
||||
async def handle_event(self, event: Event) -> None:
|
||||
if event.event not in {EVENTS.CHAT_READ.name, EVENTS.CHAT_USER_MESSAGE.name}:
|
||||
return
|
||||
from cptr.utils.timers import cancel_timers_for_event
|
||||
|
||||
await cancel_timers_for_event(event)
|
||||
|
||||
|
||||
EVENT_SINKS = [TimerEventSink(), NotificationEventSink()]
|
||||
|
||||
|
||||
async def publish_event(
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
meta?: Record<string, any> | null;
|
||||
done: boolean;
|
||||
output: any[] | null;
|
||||
usage: Record<string, number> | null;
|
||||
@@ -35,6 +36,7 @@
|
||||
}
|
||||
let {
|
||||
content,
|
||||
meta = null,
|
||||
done,
|
||||
output,
|
||||
usage,
|
||||
|
||||
@@ -95,6 +95,7 @@
|
||||
onqueueedit?: (id: string) => void;
|
||||
onqueuedelete?: (id: string) => void;
|
||||
onsettingschange?: () => void;
|
||||
ontoolapprovalchange?: (mode: ToolApprovalMode) => void;
|
||||
}
|
||||
let {
|
||||
inputText = $bindable(),
|
||||
@@ -123,7 +124,8 @@
|
||||
onqueuesendnow,
|
||||
onqueueedit,
|
||||
onqueuedelete,
|
||||
onsettingschange
|
||||
onsettingschange,
|
||||
ontoolapprovalchange
|
||||
}: Props = $props();
|
||||
|
||||
let editorEl: HTMLDivElement | undefined = $state();
|
||||
@@ -1507,6 +1509,7 @@
|
||||
bind:planMode
|
||||
bind:requestParams
|
||||
onchange={onsettingschange}
|
||||
{ontoolapprovalchange}
|
||||
onfiles={(files) => {
|
||||
if (files) processFiles(Array.from(files));
|
||||
}}
|
||||
|
||||
@@ -35,7 +35,13 @@
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { currentWorkspace, openChatTab, streamingBehavior, widescreenMode } from '$lib/stores';
|
||||
import {
|
||||
currentWorkspace,
|
||||
openChatTab,
|
||||
streamingBehavior,
|
||||
toolApprovalMode as defaultToolApprovalMode,
|
||||
widescreenMode
|
||||
} from '$lib/stores';
|
||||
import { getPathDisplayName } from '$lib/utils/paths';
|
||||
import {
|
||||
ttsEnabled,
|
||||
@@ -663,7 +669,7 @@
|
||||
const dm = get(defaultModel);
|
||||
if (dm) selectedModel = dm;
|
||||
else if (models.length) selectedModel = models[0].id;
|
||||
toolApprovalMode = 'auto';
|
||||
toolApprovalMode = get(defaultToolApprovalMode);
|
||||
planMode = false;
|
||||
requestParams = {};
|
||||
voiceModeEnabled = false;
|
||||
@@ -1062,6 +1068,12 @@
|
||||
persistChatSettings();
|
||||
}
|
||||
|
||||
function handleToolApprovalModeChange(mode: ToolApprovalMode) {
|
||||
toolApprovalMode = mode;
|
||||
defaultToolApprovalMode.set(mode);
|
||||
persistChatSettings();
|
||||
}
|
||||
|
||||
function firstUserMessageTitle(): string {
|
||||
const message = allMessages.find((m) => m.role === 'user' && !isPendingHiddenMessage(m));
|
||||
return message ? message.content.replace(/\s+/g, ' ').trim().slice(0, 80) : '';
|
||||
@@ -1652,9 +1664,13 @@
|
||||
>
|
||||
{#if !isLanding}
|
||||
<div
|
||||
class="flex h-7 shrink-0 items-center gap-2 border-b border-gray-100 px-3 dark:border-white/6"
|
||||
class="relative z-30 -mb-12 flex h-7 shrink-0 items-center gap-2 px-3 dark:border-white/6"
|
||||
style="border-color: color-mix(in oklab, var(--app-fg) 8%, transparent);"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute inset-0 -bottom-10 -z-10 bg-linear-to-b from-white via-40% via-white/90 to-97% to-transparent dark:from-gray-900 dark:via-gray-900/90 dark:to-transparent"
|
||||
></div>
|
||||
<div
|
||||
class="min-w-0 flex-1 truncate text-[0.6875rem] font-medium text-gray-600 dark:text-gray-400"
|
||||
>
|
||||
@@ -1705,6 +1721,7 @@
|
||||
onsend={send}
|
||||
onplan={handlePlanCommand}
|
||||
onsettingschange={persistChatSettings}
|
||||
ontoolapprovalchange={handleToolApprovalModeChange}
|
||||
{queuedMessages}
|
||||
onqueuesendnow={handleQueueSendNow}
|
||||
onqueueedit={handleQueueEdit}
|
||||
@@ -1742,7 +1759,7 @@
|
||||
<div
|
||||
class="{$widescreenMode
|
||||
? 'max-w-full'
|
||||
: 'max-w-2xl'} mx-auto w-full px-4 pt-4 pb-16 flex flex-col gap-4"
|
||||
: 'max-w-2xl'} mx-auto w-full px-4 pt-16 pb-16 flex flex-col gap-4"
|
||||
>
|
||||
{#if hasHiddenMessages}
|
||||
<div bind:this={loadSentinelEl} class="h-1 w-full" aria-hidden="true"></div>
|
||||
@@ -1761,6 +1778,7 @@
|
||||
{:else}
|
||||
<AssistantMessage
|
||||
content={msg.content}
|
||||
meta={msg.meta}
|
||||
done={msg.done}
|
||||
output={msg.output}
|
||||
usage={msg.usage}
|
||||
@@ -1834,6 +1852,7 @@
|
||||
onfork={handleForkChat}
|
||||
onplan={handlePlanCommand}
|
||||
onsettingschange={persistChatSettings}
|
||||
ontoolapprovalchange={handleToolApprovalModeChange}
|
||||
onstatus={handleStatusCommand}
|
||||
onskillslist={handleSkillsListCommand}
|
||||
oncancel={handleCancel}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
planMode?: boolean;
|
||||
requestParams?: Record<string, unknown>;
|
||||
onchange?: () => void;
|
||||
ontoolapprovalchange?: (mode: ToolApprovalMode) => void;
|
||||
}
|
||||
let {
|
||||
onfiles,
|
||||
@@ -20,7 +21,8 @@
|
||||
toolApprovalMode = $bindable('auto'),
|
||||
planMode = $bindable(false),
|
||||
requestParams = $bindable({}),
|
||||
onchange
|
||||
onchange,
|
||||
ontoolapprovalchange
|
||||
}: Props = $props();
|
||||
|
||||
let open = $state(false);
|
||||
@@ -108,7 +110,8 @@
|
||||
|
||||
function selectMode(mode: ToolApprovalMode) {
|
||||
toolApprovalMode = mode;
|
||||
onchange?.();
|
||||
if (ontoolapprovalchange) ontoolapprovalchange(mode);
|
||||
else onchange?.();
|
||||
}
|
||||
|
||||
function triggerUpload() {
|
||||
|
||||
@@ -54,7 +54,9 @@
|
||||
let copied = $state(false);
|
||||
let textareaEl: HTMLTextAreaElement;
|
||||
let asyncExpanded = $state(false);
|
||||
let timerExpanded = $state(false);
|
||||
const isAsyncSubagentResult = $derived(meta?.async_subagent_result === true);
|
||||
const isTimer = $derived(meta?.internal === true && meta?.type === 'timer');
|
||||
const delegationId = $derived(meta?.delegation_id || '');
|
||||
const delegationIds = $derived(Array.isArray(meta?.delegation_ids) ? meta.delegation_ids : []);
|
||||
const delegationLabel = $derived(
|
||||
@@ -121,7 +123,33 @@
|
||||
</script>
|
||||
|
||||
<div class="group">
|
||||
{#if isAsyncSubagentResult}
|
||||
{#if isTimer}
|
||||
<div class="w-full min-w-0">
|
||||
<button
|
||||
type="button"
|
||||
class="w-full min-w-0 flex items-center gap-2 text-left text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
|
||||
aria-expanded={timerExpanded}
|
||||
onclick={() => (timerExpanded = !timerExpanded)}
|
||||
>
|
||||
<span class="text-[0.75rem] font-medium shrink-0">Timer</span>
|
||||
<span class="text-[0.75rem] truncate min-w-0 flex-1">{content}</span>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
size={12}
|
||||
class="text-gray-400 dark:text-gray-600 shrink-0 transition-transform duration-150 {timerExpanded
|
||||
? 'rotate-180'
|
||||
: ''}"
|
||||
/>
|
||||
</button>
|
||||
{#if timerExpanded}
|
||||
<div
|
||||
class="mt-2 ml-3 border-l border-gray-100 dark:border-white/8 pl-3 text-[0.78125rem] leading-relaxed text-gray-600 dark:text-gray-400 whitespace-pre-wrap break-words"
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if isAsyncSubagentResult}
|
||||
<div class="w-full min-w-0">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -110,11 +110,14 @@ export interface HomeState {
|
||||
splitDirection: SplitDirection;
|
||||
}
|
||||
|
||||
export type ToolApprovalMode = 'ask' | 'auto' | 'full';
|
||||
|
||||
export interface UserPreferences {
|
||||
theme?: Theme;
|
||||
appearance?: AppearancePreferences;
|
||||
sidebarOpen: boolean;
|
||||
sidebarWidth: number;
|
||||
toolApprovalMode?: ToolApprovalMode;
|
||||
locale: string;
|
||||
workspaceOrder?: string[]; // ordered paths for sidebar drag-reorder
|
||||
keybindings?: Record<string, string>; // user-customised keyboard shortcuts
|
||||
@@ -298,6 +301,7 @@ if (typeof window !== 'undefined') {
|
||||
}
|
||||
export const sidebarWidth = writable(220);
|
||||
export const theme = writable<Theme>('dark');
|
||||
export const toolApprovalMode = writable<ToolApprovalMode>('auto');
|
||||
export const appVersion = writable('');
|
||||
export const lastSeenVersion = writable('');
|
||||
export const latestVersion = writable('');
|
||||
@@ -422,6 +426,7 @@ function persistPreferences(): void {
|
||||
},
|
||||
sidebarOpen: get(sidebarOpen),
|
||||
sidebarWidth: get(sidebarWidth),
|
||||
toolApprovalMode: get(toolApprovalMode),
|
||||
locale: i18next.language,
|
||||
workspaceOrder: get(workspaceOrder),
|
||||
keybindings: get(keybindings),
|
||||
@@ -459,6 +464,9 @@ function subscribeForPersistence() {
|
||||
sidebarWidth.subscribe(() => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
toolApprovalMode.subscribe(() => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
workspaceOrder.subscribe(() => {
|
||||
if (get(stateLoaded)) persistPreferences();
|
||||
});
|
||||
@@ -500,6 +508,15 @@ export async function loadPreferences(): Promise<void> {
|
||||
themeConfig.set(sanitizeThemeConfig(appearance.themeConfig));
|
||||
if (prefs.sidebarOpen !== undefined) sidebarOpen.set(prefs.sidebarOpen as boolean);
|
||||
if (prefs.sidebarWidth !== undefined) sidebarWidth.set(prefs.sidebarWidth as number);
|
||||
if (
|
||||
prefs.toolApprovalMode === 'ask' ||
|
||||
prefs.toolApprovalMode === 'auto' ||
|
||||
prefs.toolApprovalMode === 'full'
|
||||
) {
|
||||
toolApprovalMode.set(prefs.toolApprovalMode);
|
||||
} else if (prefs.autoApproveTools !== undefined) {
|
||||
toolApprovalMode.set((prefs.autoApproveTools as boolean) ? 'full' : 'ask');
|
||||
}
|
||||
if (prefs.locale) changeLocale(prefs.locale as string);
|
||||
if (Array.isArray(prefs.workspaceOrder)) workspaceOrder.set(prefs.workspaceOrder as string[]);
|
||||
if (prefs.keybindings) loadKeybindings(prefs.keybindings as Record<string, string>);
|
||||
|
||||
@@ -9,6 +9,9 @@ export type DiffLineGroup<T extends { type: string }> = { type: T['type']; lines
|
||||
export type SplitDiffRow = { oldLine: InlineDiffLine | null; newLine: InlineDiffLine | null };
|
||||
export type DiffStats = { additions: number; deletions: number };
|
||||
|
||||
// GitHub Desktop uses the same cutoff for intraline highlighting.
|
||||
const MAX_INTRA_LINE_DIFF_STRING_LENGTH = 1024;
|
||||
|
||||
export function countDiffStats(files: DiffFile[]): DiffStats {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
@@ -105,11 +108,16 @@ export function withInlineDiffSegments(lines: NumberedDiffLine[]): InlineDiffLin
|
||||
|
||||
const removed = block.filter((item) => item.type === 'removed');
|
||||
const added = block.filter((item) => item.type === 'added');
|
||||
const canHighlightChanges = removed.length === added.length;
|
||||
const removedSegments = removed.map((item, index) =>
|
||||
segmentsForPair(item.content, added[index]?.content, 'removed')
|
||||
canHighlightChanges
|
||||
? segmentsForPair(item.content, added[index].content, 'removed')
|
||||
: unchangedSegments(item.content)
|
||||
);
|
||||
const addedSegments = added.map((item, index) =>
|
||||
segmentsForPair(removed[index]?.content, item.content, 'added')
|
||||
canHighlightChanges
|
||||
? segmentsForPair(removed[index].content, item.content, 'added')
|
||||
: unchangedSegments(item.content)
|
||||
);
|
||||
|
||||
for (const item of block) {
|
||||
@@ -162,15 +170,17 @@ export function splitDiffRows(lines: InlineDiffLine[]): SplitDiffRow[] {
|
||||
}
|
||||
|
||||
function segmentsForPair(
|
||||
oldText: string | undefined,
|
||||
newText: string | undefined,
|
||||
oldText: string,
|
||||
newText: string,
|
||||
side: 'removed' | 'added'
|
||||
): InlineDiffSegment[] {
|
||||
const text = side === 'removed' ? oldText : newText;
|
||||
if (text === undefined) return [];
|
||||
if (oldText === undefined || newText === undefined)
|
||||
return [{ text: text || ' ', changed: false }];
|
||||
if (oldText === newText) return [{ text: text || ' ', changed: false }];
|
||||
if (
|
||||
oldText === newText ||
|
||||
oldText.length >= MAX_INTRA_LINE_DIFF_STRING_LENGTH ||
|
||||
newText.length >= MAX_INTRA_LINE_DIFF_STRING_LENGTH
|
||||
)
|
||||
return unchangedSegments(text);
|
||||
|
||||
let prefix = 0;
|
||||
const maxPrefix = Math.min(oldText.length, newText.length);
|
||||
@@ -187,31 +197,16 @@ function segmentsForPair(
|
||||
newSuffix -= 1;
|
||||
}
|
||||
|
||||
const oldChangedLength = oldSuffix - prefix;
|
||||
const newChangedLength = newSuffix - prefix;
|
||||
const sharedLength = Math.max(
|
||||
oldText.length - oldChangedLength,
|
||||
newText.length - newChangedLength
|
||||
);
|
||||
const similarity = sharedLength / Math.max(oldText.length, newText.length, 1);
|
||||
const changedLength = side === 'removed' ? oldChangedLength : newChangedLength;
|
||||
if (similarity < 0.55 || changedLength / Math.max(text.length, 1) > 0.45) {
|
||||
return [{ text: text || ' ', changed: false }];
|
||||
}
|
||||
|
||||
const end = side === 'removed' ? oldSuffix : newSuffix;
|
||||
const changed = text.slice(prefix, end);
|
||||
const tokenStart = changed.search(/[A-Za-z0-9_$]/);
|
||||
if (tokenStart < 0) return [{ text: text || ' ', changed: false }];
|
||||
|
||||
const tokenEnd = changed.search(/[A-Za-z0-9_$][^A-Za-z0-9_$]*$/);
|
||||
const highlightStart = tokenStart >= 0 ? prefix + tokenStart : prefix;
|
||||
const highlightEnd = tokenEnd >= 0 ? prefix + tokenEnd + 1 : end;
|
||||
const segments = [
|
||||
{ text: text.slice(0, highlightStart), changed: false },
|
||||
{ text: text.slice(highlightStart, highlightEnd), changed: true },
|
||||
{ text: text.slice(highlightEnd), changed: false }
|
||||
{ text: text.slice(0, prefix), changed: false },
|
||||
{ text: text.slice(prefix, end), changed: true },
|
||||
{ text: text.slice(end), changed: false }
|
||||
].filter((segment) => segment.text.length > 0);
|
||||
|
||||
return segments.length ? segments : [{ text: ' ', changed: false }];
|
||||
return segments.length ? segments : unchangedSegments(text);
|
||||
}
|
||||
|
||||
function unchangedSegments(text: string): InlineDiffSegment[] {
|
||||
return [{ text: text || ' ', changed: false }];
|
||||
}
|
||||
@@ -5,7 +5,7 @@ from cptr.models.users import User, Auth, UserStates
|
||||
from cptr.models.workspaces import Workspace
|
||||
from cptr.models.config import Config
|
||||
from cptr.models.files import File
|
||||
from cptr.models.chats import Chat, ChatMessage
|
||||
from cptr.models.chats import Chat, ChatMessage, is_internal_chat
|
||||
from cptr.models.automations import Automation, AutomationRun
|
||||
|
||||
__all__ = [
|
||||
@@ -18,7 +18,7 @@ __all__ = [
|
||||
"File",
|
||||
"Chat",
|
||||
"ChatMessage",
|
||||
"is_internal_chat",
|
||||
"Automation",
|
||||
"AutomationRun",
|
||||
]
|
||||
|
||||
+88
-3
@@ -27,6 +27,12 @@ def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def is_internal_chat(meta: dict | None) -> bool:
|
||||
"""Whether a chat is harness-owned and should stay out of normal chat surfaces."""
|
||||
meta = meta or {}
|
||||
return bool(meta.get("internal") or meta.get("subagent"))
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
"""A chat conversation. Workspace association lives in the filesystem."""
|
||||
|
||||
@@ -59,6 +65,71 @@ class Chat(Base):
|
||||
result = await db.execute(select(Chat).where(Chat.id.in_(chat_ids)))
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def get_due_timers(now_ns: int, limit: int = 10) -> list[Chat]:
|
||||
"""Return pending internal timer chats whose due time has arrived."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(select(Chat).where(Chat.meta.is_not(None)))
|
||||
timers = [
|
||||
chat
|
||||
for chat in result.scalars().all()
|
||||
if (chat.meta or {}).get("internal") is True
|
||||
and (chat.meta or {}).get("type") == "timer"
|
||||
and (chat.meta or {}).get("timer_status") == "pending"
|
||||
and int((chat.meta or {}).get("timer_at") or 0) <= now_ns
|
||||
]
|
||||
timers.sort(key=lambda chat: int((chat.meta or {}).get("timer_at") or 0))
|
||||
return timers[:limit]
|
||||
|
||||
@staticmethod
|
||||
async def get_pending_timers(parent_chat_id: str) -> list[Chat]:
|
||||
"""Return pending timer children for a parent chat."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(select(Chat).where(Chat.meta.is_not(None)))
|
||||
return [
|
||||
chat
|
||||
for chat in result.scalars().all()
|
||||
if (chat.meta or {}).get("internal") is True
|
||||
and (chat.meta or {}).get("type") == "timer"
|
||||
and (chat.meta or {}).get("parent_chat_id") == parent_chat_id
|
||||
and (chat.meta or {}).get("timer_status") == "pending"
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
async def get_timers(status: str | None = None) -> list[Chat]:
|
||||
"""Return internal timer chats, optionally in one lifecycle state."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(select(Chat).where(Chat.meta.is_not(None)))
|
||||
return [
|
||||
chat
|
||||
for chat in result.scalars().all()
|
||||
if (chat.meta or {}).get("internal") is True
|
||||
and (chat.meta or {}).get("type") == "timer"
|
||||
and (status is None or (chat.meta or {}).get("timer_status") == status)
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
async def get_internal_descendants(parent_chat_id: str) -> list[Chat]:
|
||||
"""Return every internal child below a chat, including nested timers."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(select(Chat).where(Chat.meta.is_not(None)))
|
||||
candidates = list(result.scalars().all())
|
||||
children: list[Chat] = []
|
||||
parent_ids = {parent_chat_id}
|
||||
while parent_ids:
|
||||
found = [
|
||||
chat
|
||||
for chat in candidates
|
||||
if is_internal_chat(chat.meta)
|
||||
and (chat.meta or {}).get("parent_chat_id") in parent_ids
|
||||
]
|
||||
if not found:
|
||||
break
|
||||
children.extend(found)
|
||||
parent_ids = {chat.id for chat in found}
|
||||
candidates = [chat for chat in candidates if chat not in found]
|
||||
return children
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
user_id: str,
|
||||
@@ -147,6 +218,8 @@ class Chat(Base):
|
||||
.where(
|
||||
Chat.user_id == user_id,
|
||||
workspace.in_(paths),
|
||||
Chat.meta["internal"].as_boolean().is_not(True),
|
||||
Chat.meta["subagent"].as_boolean().is_not(True),
|
||||
Chat.updated_at > func.coalesce(Chat.last_read_at, 0),
|
||||
)
|
||||
.group_by(workspace)
|
||||
@@ -173,9 +246,21 @@ class Chat(Base):
|
||||
@staticmethod
|
||||
async def delete(chat_id: str) -> bool:
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(select(Chat).where(Chat.meta.is_not(None)))
|
||||
candidates = list(result.scalars().all())
|
||||
delete_ids = {chat_id}
|
||||
frontier = {chat_id}
|
||||
while frontier:
|
||||
frontier = {
|
||||
chat.id
|
||||
for chat in candidates
|
||||
if is_internal_chat(chat.meta)
|
||||
and (chat.meta or {}).get("parent_chat_id") in frontier
|
||||
}
|
||||
delete_ids.update(frontier)
|
||||
# Messages cascade via FK, but be explicit
|
||||
await db.execute(delete(ChatMessage).where(ChatMessage.chat_id == chat_id))
|
||||
result = await db.execute(delete(Chat).where(Chat.id == chat_id))
|
||||
await db.execute(delete(ChatMessage).where(ChatMessage.chat_id.in_(delete_ids)))
|
||||
result = await db.execute(delete(Chat).where(Chat.id.in_(delete_ids)))
|
||||
await db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
@@ -237,7 +322,7 @@ class Chat(Base):
|
||||
|
||||
def allowed(chat: Chat) -> bool:
|
||||
meta = chat.meta or {}
|
||||
if not include_subagents and meta.get("subagent"):
|
||||
if not include_subagents and is_internal_chat(meta):
|
||||
return False
|
||||
if workspace and meta.get("workspace") != workspace:
|
||||
return False
|
||||
|
||||
+28
-3
@@ -11,7 +11,7 @@ from typing import List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.models import Chat, ChatMessage, Config
|
||||
from cptr.models import Chat, ChatMessage, Config, is_internal_chat
|
||||
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.workspace import ensure_cptr_gitignored
|
||||
@@ -97,6 +97,8 @@ async def list_chats(
|
||||
continue
|
||||
|
||||
chat_meta = chat.meta if isinstance(chat.meta, dict) else {}
|
||||
if is_internal_chat(chat_meta):
|
||||
continue
|
||||
if chat.meta is not None and not isinstance(chat.meta, dict):
|
||||
log.warning(
|
||||
"chat.list.bad_meta workspace=%r chat_id=%s title=%r meta_type=%s",
|
||||
@@ -581,10 +583,14 @@ async def delete_chat(chat_id: str, request: Request):
|
||||
if not chat or chat.user_id != user_id:
|
||||
raise HTTPException(404, "chat not found")
|
||||
|
||||
# Remove the workspace chat file.
|
||||
# Remove the workspace chat file and durable internal children.
|
||||
workspace = chat.meta.get("workspace") if chat.meta else None
|
||||
chat_file = chat_directory(workspace) / f"{chat_id}.json"
|
||||
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
|
||||
for child in await Chat.get_internal_descendants(chat_id):
|
||||
child_workspace = (child.meta or {}).get("workspace")
|
||||
child_file = chat_directory(child_workspace) / f"{child.id}.json"
|
||||
await asyncio.to_thread(child_file.unlink, True)
|
||||
|
||||
await Chat.delete(chat_id)
|
||||
from cptr.socket.main import emit_to_user
|
||||
@@ -801,6 +807,18 @@ async def send_message(body: SendMessageRequest, request: Request):
|
||||
# Update chat pointer to new leaf while still holding the input lock.
|
||||
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
|
||||
|
||||
submitted_message = queued_msg or user_msg
|
||||
if submitted_message:
|
||||
from cptr.events import EVENTS, publish_event
|
||||
|
||||
await publish_event(
|
||||
EVENTS.CHAT_USER_MESSAGE,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat.id,
|
||||
subject_type="chat",
|
||||
source="chat",
|
||||
)
|
||||
|
||||
if queued_msg:
|
||||
await process_pending_chat_inputs(chat.id, user_id, workspace or "")
|
||||
return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True}
|
||||
@@ -1037,7 +1055,14 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
|
||||
result = await execute_tool(
|
||||
call["name"],
|
||||
call.get("arguments", {}),
|
||||
{"workspace": chat.meta.get("workspace", ""), "user_id": user_id, "model_id": model_id},
|
||||
{
|
||||
"workspace": chat.meta.get("workspace", ""),
|
||||
"user_id": user_id,
|
||||
"model_id": model_id,
|
||||
"chat_id": chat_id,
|
||||
"message_id": message_id,
|
||||
"call_id": body.call_id,
|
||||
},
|
||||
)
|
||||
call["status"] = "completed"
|
||||
output.append(
|
||||
|
||||
@@ -89,6 +89,15 @@ async def on_chat_read(sid, data):
|
||||
|
||||
last_read_at = now_ms()
|
||||
if await Chat.update_last_read_at(chat_id, user_id, last_read_at):
|
||||
from cptr.events import EVENTS, publish_event
|
||||
|
||||
await publish_event(
|
||||
EVENTS.CHAT_READ,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="socket",
|
||||
)
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
workspace = (chat.meta or {}).get("workspace", "") if chat else ""
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
|
||||
@@ -194,6 +194,7 @@ async def _inject_completion(record: dict[str, Any]) -> None:
|
||||
from cptr.utils.chat_task import get_pending_input_lock, start_task
|
||||
|
||||
assistant_msg = None
|
||||
direct_timer_completion = False
|
||||
async with get_pending_input_lock(parent_chat_id):
|
||||
all_msgs = await ChatMessage.get_all_by_chat(parent_chat_id)
|
||||
active = any(m.role == "assistant" and not m.done for m in all_msgs)
|
||||
@@ -208,29 +209,55 @@ async def _inject_completion(record: dict[str, Any]) -> None:
|
||||
if active:
|
||||
meta["async_subagent_pending"] = True
|
||||
|
||||
user_msg = await ChatMessage.create(
|
||||
chat_id=parent_chat_id,
|
||||
role="user",
|
||||
content=content,
|
||||
parent_id=parent_id,
|
||||
model=model_id,
|
||||
meta=meta,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
|
||||
if not active:
|
||||
if record.get("timer_chat_id") and not active:
|
||||
direct_timer_completion = True
|
||||
meta["timer_completion"] = True
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=parent_chat_id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=user_msg.id,
|
||||
content=record.get("summary") or "Timer completed.",
|
||||
parent_id=parent_id,
|
||||
model=model_id,
|
||||
done=False,
|
||||
done=True,
|
||||
meta=meta,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(parent_chat_id, assistant_msg.id, now_ms())
|
||||
else:
|
||||
user_msg = await ChatMessage.create(
|
||||
chat_id=parent_chat_id,
|
||||
role="user",
|
||||
content=content,
|
||||
parent_id=parent_id,
|
||||
model=model_id,
|
||||
meta=meta,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
|
||||
if not active:
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=parent_chat_id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=user_msg.id,
|
||||
model=model_id,
|
||||
done=False,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(parent_chat_id, assistant_msg.id, now_ms())
|
||||
|
||||
await export_chat_to_file(parent_chat_id)
|
||||
if direct_timer_completion:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"chat_id": parent_chat_id,
|
||||
"message_id": assistant_msg.id,
|
||||
"pending_inputs_processed": True,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
if not assistant_msg:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
|
||||
@@ -23,7 +23,7 @@ from cptr.utils.skills import (
|
||||
load_skill,
|
||||
)
|
||||
from cptr.utils.summarize import summarize_messages
|
||||
from cptr.models import Chat, ChatMessage, Config
|
||||
from cptr.models import Chat, ChatMessage, Config, is_internal_chat
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.ai import (
|
||||
ChatCompletionForm,
|
||||
@@ -1936,7 +1936,7 @@ async def run_chat_task(
|
||||
tools = [t for t in tools if t["name"] != "view_skill"]
|
||||
|
||||
# Strip delegate_task from sub-agent chats (depth limit = 1)
|
||||
if chat_obj and (chat_obj.meta or {}).get("subagent"):
|
||||
if chat_obj and is_internal_chat(chat_obj.meta):
|
||||
tools = [t for t in tools if t["name"] not in {"delegate_task", "update_memory"}]
|
||||
|
||||
# Parse $skill-name mentions from the user message to auto-activate skills
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Durable one-shot timers backed by dormant internal child chats."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from cptr.env import TIMER_POLL_INTERVAL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_RELATIVE_TIME = re.compile(
|
||||
r"^(?:\+|in\s+)?(\d+)\s*(s|sec(?:onds?)?|m|min(?:utes?)?|h|hours?|d|days?)$"
|
||||
)
|
||||
_RFC3339_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
|
||||
_TIME_UNITS_NS = {
|
||||
"s": 1_000_000_000,
|
||||
"m": 60 * 1_000_000_000,
|
||||
"h": 60 * 60 * 1_000_000_000,
|
||||
"d": 24 * 60 * 60 * 1_000_000_000,
|
||||
}
|
||||
_manager_lock = asyncio.Lock()
|
||||
|
||||
|
||||
def parse_timer_at(value: str) -> int:
|
||||
"""Normalize a relative offset or timezone-aware RFC 3339 timestamp."""
|
||||
raw = value.strip()
|
||||
now = time.time_ns()
|
||||
relative = _RELATIVE_TIME.fullmatch(raw.lower())
|
||||
if relative:
|
||||
count = int(relative.group(1))
|
||||
if count <= 0:
|
||||
raise ValueError("at must be in the future.")
|
||||
return now + count * _TIME_UNITS_NS[relative.group(2)[0]]
|
||||
|
||||
if not _RFC3339_TIME.fullmatch(raw):
|
||||
raise ValueError(
|
||||
"at must be a relative time such as 10s or in 10 seconds, "
|
||||
"or an RFC 3339 timestamp with a timezone."
|
||||
)
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
"at must be a relative time such as 10s or in 10 seconds, "
|
||||
"or an RFC 3339 timestamp with a timezone."
|
||||
) from exc
|
||||
if parsed.tzinfo is None or parsed.utcoffset() is None:
|
||||
raise ValueError("absolute at values must include an explicit timezone.")
|
||||
|
||||
due_at = int(parsed.timestamp() * 1_000_000_000)
|
||||
if due_at <= now:
|
||||
raise ValueError("at must be in the future.")
|
||||
return due_at
|
||||
|
||||
|
||||
async def cancel_timers_for_event(event) -> None:
|
||||
"""Cancel matching dormant children after a committed parent-chat event."""
|
||||
subject = event.subject or {}
|
||||
if subject.get("type") != "chat" or not subject.get("id"):
|
||||
return
|
||||
|
||||
from cptr.models import Chat
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
async with _manager_lock:
|
||||
timers = await Chat.get_pending_timers(str(subject["id"]))
|
||||
for timer in timers:
|
||||
meta = dict(timer.meta or {})
|
||||
if event.event not in (meta.get("cancel_on") or []):
|
||||
continue
|
||||
meta.update(
|
||||
{
|
||||
"timer_status": "cancelled",
|
||||
"timer_cancelled_at": time.time_ns(),
|
||||
"timer_cancelled_by": event.event,
|
||||
}
|
||||
)
|
||||
await Chat.update_meta(timer.id, meta, now_ms())
|
||||
|
||||
|
||||
async def _set_timer_status(chat_id: str, status: str, **fields) -> None:
|
||||
from cptr.models import Chat
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return
|
||||
meta = dict(chat.meta or {})
|
||||
meta["timer_status"] = status
|
||||
meta.update(fields)
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
|
||||
|
||||
async def _launch_timer(timer, app) -> None:
|
||||
from cptr.models import Chat, ChatMessage
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
from cptr.utils.chat_task import get_pending_input_lock, start_task
|
||||
from cptr.utils.config import now_ms
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
async with _manager_lock:
|
||||
timer = await Chat.get_by_id(timer.id)
|
||||
if not timer:
|
||||
return
|
||||
meta = dict(timer.meta or {})
|
||||
if meta.get("timer_status") != "pending" or int(meta.get("timer_at") or 0) > time.time_ns():
|
||||
return
|
||||
|
||||
parent = await Chat.get_by_id(meta.get("parent_chat_id", ""))
|
||||
if not parent:
|
||||
await _set_timer_status(timer.id, "error", timer_error="parent chat no longer exists")
|
||||
return
|
||||
|
||||
task_message = await ChatMessage.get_by_id(timer.current_message_id)
|
||||
if not task_message:
|
||||
await _set_timer_status(timer.id, "error", timer_error="timer task message is missing")
|
||||
return
|
||||
|
||||
async with get_pending_input_lock(parent.id):
|
||||
parent_messages = await ChatMessage.get_all_by_chat(parent.id)
|
||||
active = any(
|
||||
message.role == "assistant" and not message.done for message in parent_messages
|
||||
)
|
||||
if active:
|
||||
return
|
||||
|
||||
try:
|
||||
target = await resolve_model_target(meta["timer_model_id"], app.state)
|
||||
except Exception as exc: # model configuration can change while a timer waits
|
||||
await _set_timer_status(timer.id, "error", timer_error=f"model unavailable: {exc}")
|
||||
return
|
||||
|
||||
done_assistants = [
|
||||
message
|
||||
for message in parent_messages
|
||||
if message.role == "assistant" and message.done
|
||||
]
|
||||
parent_id = (
|
||||
done_assistants[-1].id if done_assistants else meta.get("timer_parent_message_id")
|
||||
)
|
||||
prompt_msg = await ChatMessage.create(
|
||||
chat_id=parent.id,
|
||||
role="user",
|
||||
content=task_message.content,
|
||||
parent_id=parent_id,
|
||||
model=target.full_model_id,
|
||||
meta={"internal": True, "type": "timer"},
|
||||
created_at=now_ms(),
|
||||
)
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=parent.id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=prompt_msg.id,
|
||||
model=target.full_model_id,
|
||||
done=False,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(parent.id, assistant_msg.id, now_ms())
|
||||
|
||||
meta.update(
|
||||
{
|
||||
"timer_status": "completed",
|
||||
"timer_completed_at": time.time_ns(),
|
||||
}
|
||||
)
|
||||
await Chat.update_meta(timer.id, meta, now_ms())
|
||||
|
||||
await export_chat_to_file(timer.id)
|
||||
await export_chat_to_file(parent.id)
|
||||
|
||||
await emit_to_user(
|
||||
timer.user_id,
|
||||
{
|
||||
"chat_id": parent.id,
|
||||
"message_id": assistant_msg.id,
|
||||
"pending_inputs_processed": True,
|
||||
},
|
||||
)
|
||||
start_task(
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=parent.id,
|
||||
user_id=timer.user_id,
|
||||
workspace=meta.get("workspace", ""),
|
||||
target=target,
|
||||
)
|
||||
|
||||
|
||||
async def timer_worker_loop(app) -> None:
|
||||
"""Poll durable pending timers and wake their parent chats."""
|
||||
from cptr.models import Chat
|
||||
|
||||
logger.info("Timer worker started (poll interval: %ds)", TIMER_POLL_INTERVAL)
|
||||
while True:
|
||||
try:
|
||||
due = await Chat.get_due_timers(time.time_ns())
|
||||
for timer in due:
|
||||
await _launch_timer(timer, app)
|
||||
except Exception:
|
||||
logger.exception("Timer worker error")
|
||||
await asyncio.sleep(TIMER_POLL_INTERVAL)
|
||||
|
||||
|
||||
async def recover_timers() -> None:
|
||||
"""Do not replay work that was already launched before a process restart."""
|
||||
from cptr.models import Chat, ChatMessage
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
for timer in await Chat.get_timers("pending"):
|
||||
current = await ChatMessage.get_by_id(timer.current_message_id)
|
||||
if current and current.role == "assistant":
|
||||
await ChatMessage.delete(current.id)
|
||||
await Chat.update_current_message(timer.id, current.parent_id, now_ms())
|
||||
|
||||
for timer in await Chat.get_timers("running"):
|
||||
await _set_timer_status(
|
||||
timer.id,
|
||||
"error",
|
||||
timer_completed_at=time.time_ns(),
|
||||
timer_error="interrupted by restart",
|
||||
)
|
||||
+101
-25
@@ -1997,7 +1997,7 @@ async def search_chats(
|
||||
"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from cptr.models import Chat, ChatMessage
|
||||
from cptr.models import Chat, ChatMessage, is_internal_chat
|
||||
from cptr.utils.db import get_db
|
||||
|
||||
user_id = __context__.get("user_id")
|
||||
@@ -2022,8 +2022,8 @@ async def search_chats(
|
||||
if not chat or chat.user_id != user_id:
|
||||
return None, "chat not found"
|
||||
meta = chat.meta or {}
|
||||
if not include_subagents and meta.get("subagent"):
|
||||
return None, "chat is a sub-agent chat"
|
||||
if not include_subagents and is_internal_chat(meta):
|
||||
return None, "chat is an internal chat"
|
||||
if workspace and meta.get("workspace") != workspace:
|
||||
return None, "chat is outside the current workspace"
|
||||
return chat, None
|
||||
@@ -2124,7 +2124,7 @@ async def search_chats(
|
||||
meta = chat.meta or {}
|
||||
if chat.id == current_chat_id:
|
||||
continue
|
||||
if not include_subagents and meta.get("subagent"):
|
||||
if not include_subagents and is_internal_chat(meta):
|
||||
continue
|
||||
if workspace and meta.get("workspace") != workspace:
|
||||
continue
|
||||
@@ -2299,14 +2299,13 @@ async def delegate_task(
|
||||
|
||||
delegation_id = reserve["delegation_id"]
|
||||
try:
|
||||
chat, assistant_msg = await _create_subagent_chat(
|
||||
chat, _, assistant_msg = await _create_subagent_chat(
|
||||
task=task,
|
||||
context=context,
|
||||
workspace=__context__["workspace"],
|
||||
model=__context__["model_id"],
|
||||
user_id=__context__["user_id"],
|
||||
parent_chat_id=__context__["chat_id"],
|
||||
config=config,
|
||||
delegation_id=delegation_id,
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -2369,6 +2368,75 @@ async def delegate_task(
|
||||
)
|
||||
|
||||
|
||||
async def timer(
|
||||
prompt: str,
|
||||
at: str,
|
||||
cancel_on: list[Literal["chat.read", "chat.user_message"]] | None = None,
|
||||
*,
|
||||
__context__: dict,
|
||||
) -> str:
|
||||
"""Set a one-shot timer for this chat.
|
||||
|
||||
Use it when time is the missing input: wait for a deployment, retry after
|
||||
backoff, revisit work after a deadline, or follow up after silence. When
|
||||
it fires, the agent receives `prompt` and the latest thread context; it may
|
||||
act, set another timer, or finish silently.
|
||||
|
||||
`at` is normally relative to now. Prefer `10s`, `5m`, `1h`, or `2d`; plain
|
||||
language such as `in 10 seconds` also works. Use an RFC 3339 timestamp
|
||||
with a timezone only for a real calendar deadline.
|
||||
|
||||
`cancel_on` prevents launch when `chat.read` or `chat.user_message`
|
||||
happens first in this chat. Omit it when timed work must run regardless.
|
||||
"""
|
||||
from cptr.utils.timers import parse_timer_at
|
||||
|
||||
if not prompt.strip():
|
||||
return "Error: prompt must not be empty."
|
||||
|
||||
try:
|
||||
due_at = parse_timer_at(at)
|
||||
except ValueError as exc:
|
||||
return f"Error: {exc}"
|
||||
|
||||
selected_events = cancel_on or []
|
||||
allowed_events = {"chat.read", "chat.user_message"}
|
||||
if any(event not in allowed_events for event in selected_events):
|
||||
return "Error: cancel_on accepts only chat.read and chat.user_message."
|
||||
selected_events = list(dict.fromkeys(selected_events))
|
||||
|
||||
full_model_id = __context__.get("full_model_id") or __context__["model_id"]
|
||||
chat, _, _ = await _create_subagent_chat(
|
||||
task=prompt,
|
||||
context="",
|
||||
workspace=__context__["workspace"],
|
||||
model=full_model_id,
|
||||
user_id=__context__["user_id"],
|
||||
parent_chat_id=__context__["chat_id"],
|
||||
child_type="timer",
|
||||
deferred=True,
|
||||
extra_meta={
|
||||
"timer_at": due_at,
|
||||
"cancel_on": selected_events,
|
||||
"timer_status": "pending",
|
||||
"timer_parent_message_id": __context__.get("message_id"),
|
||||
"timer_model_id": full_model_id,
|
||||
},
|
||||
)
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "set",
|
||||
"at": datetime.fromtimestamp(due_at / 1_000_000_000, timezone.utc)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z"),
|
||||
"cancel_on": selected_events,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def _create_subagent_chat(
|
||||
task: str,
|
||||
context: str,
|
||||
@@ -2376,8 +2444,11 @@ async def _create_subagent_chat(
|
||||
model: str,
|
||||
user_id: str,
|
||||
parent_chat_id: str,
|
||||
config: dict,
|
||||
delegation_id: str | None = None,
|
||||
*,
|
||||
child_type: str = "subagent",
|
||||
deferred: bool = False,
|
||||
extra_meta: dict | None = None,
|
||||
):
|
||||
"""Create the real chat/messages used by a sub-agent."""
|
||||
from cptr.models import Chat, ChatMessage
|
||||
@@ -2387,7 +2458,8 @@ async def _create_subagent_chat(
|
||||
user_content = f"{task}\n\n## Context\n{context}" if context else task
|
||||
meta = {
|
||||
"workspace": workspace,
|
||||
"subagent": True,
|
||||
"internal": True,
|
||||
"type": child_type,
|
||||
"parent_chat_id": parent_chat_id,
|
||||
"params": {
|
||||
"tool_approval_mode": "full", # auto-approve all tools
|
||||
@@ -2395,10 +2467,12 @@ async def _create_subagent_chat(
|
||||
}
|
||||
if delegation_id:
|
||||
meta["delegation_id"] = delegation_id
|
||||
if extra_meta:
|
||||
meta.update(extra_meta)
|
||||
|
||||
chat = await Chat.create(
|
||||
user_id=user_id,
|
||||
title=f"Sub-agent: {task[:60]}",
|
||||
title=f"{child_type.title()}: {task[:60]}",
|
||||
meta=meta,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
@@ -2410,19 +2484,22 @@ async def _create_subagent_chat(
|
||||
created_at=now_ms(),
|
||||
)
|
||||
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=chat.id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=user_msg.id,
|
||||
model=model,
|
||||
done=False,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
|
||||
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
|
||||
assistant_msg = None
|
||||
if deferred:
|
||||
await Chat.update_current_message(chat.id, user_msg.id, now_ms())
|
||||
else:
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=chat.id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=user_msg.id,
|
||||
model=model,
|
||||
done=False,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
|
||||
await export_chat_to_file(chat.id)
|
||||
return chat, assistant_msg
|
||||
return chat, user_msg, assistant_msg
|
||||
|
||||
|
||||
async def _run_existing_subagent_chat(
|
||||
@@ -2469,14 +2546,13 @@ async def _run_subagent_chat(
|
||||
config: dict,
|
||||
) -> str:
|
||||
"""Create a real chat and run the agent loop on it."""
|
||||
chat, assistant_msg = await _create_subagent_chat(
|
||||
chat, _, assistant_msg = await _create_subagent_chat(
|
||||
task=task,
|
||||
context=context,
|
||||
workspace=workspace,
|
||||
model=model,
|
||||
user_id=user_id,
|
||||
parent_chat_id=parent_chat_id,
|
||||
config=config,
|
||||
)
|
||||
return await _run_existing_subagent_chat(
|
||||
assistant_msg_id=assistant_msg.id,
|
||||
@@ -2491,6 +2567,7 @@ async def _run_subagent_chat(
|
||||
|
||||
SUBAGENT_TOOLS: dict[str, dict] = {
|
||||
"delegate_task": {"fn": delegate_task, "auto": True},
|
||||
"timer": {"fn": timer, "auto": False},
|
||||
}
|
||||
|
||||
# Combined lookup for execution and approval (always available regardless of config)
|
||||
@@ -2539,7 +2616,6 @@ GLOBAL_CHAT_DISABLED_TOOLS = {
|
||||
*BUILTIN_TOOL_GROUPS["browser"],
|
||||
*BUILTIN_TOOL_GROUPS["automations"],
|
||||
*BUILTIN_TOOL_GROUPS["images"],
|
||||
*BUILTIN_TOOL_GROUPS["subagents"],
|
||||
"manage_skill",
|
||||
}
|
||||
|
||||
@@ -2811,7 +2887,7 @@ def _parse_param_descriptions(docstring: str) -> dict[str, str]:
|
||||
def _fn_to_schema(name: str, fn) -> dict:
|
||||
"""Introspect function → {name, description, parameters} for LLM."""
|
||||
doc = inspect.getdoc(fn) or ""
|
||||
description = doc.split("\n")[0]
|
||||
description = doc if name == "timer" else doc.split("\n")[0]
|
||||
param_descs = _parse_param_descriptions(doc)
|
||||
hints = get_type_hints(fn)
|
||||
sig = inspect.signature(fn)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.9.5"
|
||||
version = "0.9.6"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
|
||||
Reference in new issue
Block a user