@cortex-agent/server 2026.5.19-3 → 2026.5.22-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/defaults/config/thread-templates.json +65 -39
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
- package/defaults/prompts/directives/coder-reviewer.md +9 -4
- package/defaults/prompts/directives/coder.md +10 -2
- package/dist/core/gateway-generator.js +26 -4
- package/dist/core/log.js +61 -12
- package/dist/core/profile-generator.js +4 -3
- package/dist/core/status-format.js +1 -1
- package/dist/core/task-parser.d.ts +1 -1
- package/dist/core/task-parser.js +13 -6
- package/dist/core/types/thread-types.d.ts +4 -2
- package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
- package/dist/domain/costs/codex-usage-monitor.js +2 -2
- package/dist/domain/costs/cost-tracker.d.ts +2 -0
- package/dist/domain/costs/cost-tracker.js +4 -20
- package/dist/domain/costs/rate-limit-throttle.js +1 -4
- package/dist/domain/mcp/tools/context.d.ts +4 -2
- package/dist/domain/mcp/tools/context.js +7 -5
- package/dist/domain/mcp/tools/schedule.d.ts +1 -1
- package/dist/domain/mcp/tools/schedule.js +24 -20
- package/dist/domain/memory/index-regen.js +8 -5
- package/dist/domain/monitor/disk-monitor.js +1 -6
- package/dist/domain/projects/index.d.ts +2 -0
- package/dist/domain/projects/index.js +3 -0
- package/dist/domain/projects/project-store.d.ts +54 -0
- package/dist/domain/projects/project-store.js +194 -0
- package/dist/domain/projects/project-types.d.ts +11 -0
- package/dist/domain/projects/project-types.js +5 -0
- package/dist/domain/remote/client-hot-reload.d.ts +1 -0
- package/dist/domain/remote/client-hot-reload.js +284 -53
- package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
- package/dist/domain/scheduling/jobs/_shared.js +6 -5
- package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
- package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
- package/dist/domain/scheduling/jobs/sync-public.js +34 -0
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
- package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
- package/dist/domain/scheduling/jobs/task-archive.js +2 -2
- package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
- package/dist/domain/scheduling/runner.d.ts +1 -0
- package/dist/domain/scheduling/runner.js +2 -0
- package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
- package/dist/domain/scheduling/schedule-cli.js +14 -14
- package/dist/domain/scheduling/schedule-command.js +45 -36
- package/dist/domain/scheduling/scheduler.d.ts +1 -1
- package/dist/domain/scheduling/scheduler.js +12 -11
- package/dist/domain/sessions/session-hooks.d.ts +10 -11
- package/dist/domain/sessions/session-hooks.js +26 -27
- package/dist/domain/sessions/session-registry.d.ts +10 -5
- package/dist/domain/sessions/session-registry.js +24 -9
- package/dist/domain/tasks/pending-tracker.js +8 -9
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +189 -29
- package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
- package/dist/domain/threads/hook-runner.js +12 -7
- package/dist/domain/threads/runner.d.ts +3 -3
- package/dist/domain/threads/runner.js +30 -28
- package/dist/domain/threads/state-machine.d.ts +3 -0
- package/dist/domain/threads/state-machine.js +4 -0
- package/dist/entry/app.js +30 -9
- package/dist/entry/cli.js +19 -4
- package/dist/entry/daemon.js +28 -2
- package/dist/entry/startup-notify.js +8 -6
- package/dist/orchestration/agent-runner.js +19 -13
- package/dist/orchestration/durable-helpers.js +3 -2
- package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
- package/dist/orchestration/interactions/ask-user-question.js +5 -4
- package/dist/orchestration/interactions/interaction-handlers.js +8 -5
- package/dist/orchestration/interactions/plan-handler.js +3 -3
- package/dist/orchestration/lifecycle.js +43 -38
- package/dist/orchestration/routing/commands/cancel.js +9 -8
- package/dist/orchestration/routing/commands/channel.js +32 -26
- package/dist/orchestration/routing/commands/cost.js +5 -3
- package/dist/orchestration/routing/commands/device.js +2 -1
- package/dist/orchestration/routing/commands/dispatch.js +8 -7
- package/dist/orchestration/routing/commands/index.js +7 -4
- package/dist/orchestration/routing/commands/mode.js +24 -18
- package/dist/orchestration/routing/commands/nvtop.js +14 -12
- package/dist/orchestration/routing/commands/orient.js +2 -1
- package/dist/orchestration/routing/commands/schedule.js +2 -1
- package/dist/orchestration/routing/commands/sendfile.js +12 -9
- package/dist/orchestration/routing/commands/session.js +12 -10
- package/dist/orchestration/routing/commands/status.js +2 -2
- package/dist/orchestration/routing/commands/tail.js +10 -6
- package/dist/orchestration/routing/commands/task.js +5 -4
- package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
- package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
- package/dist/orchestration/status-helpers.d.ts +4 -5
- package/dist/orchestration/status-helpers.js +7 -8
- package/dist/orchestration/thread-executor.js +21 -12
- package/dist/platform/adapter.d.ts +13 -9
- package/dist/platform/adapter.js +1 -1
- package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
- package/dist/platform/adapters/feishu-output-stream.js +114 -0
- package/dist/platform/adapters/feishu.d.ts +16 -7
- package/dist/platform/adapters/feishu.js +64 -18
- package/dist/platform/adapters/index.d.ts +4 -1
- package/dist/platform/adapters/index.js +1 -1
- package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
- package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
- package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
- package/dist/platform/adapters/slack-project-conduits.js +40 -0
- package/dist/platform/adapters/slack.d.ts +18 -8
- package/dist/platform/adapters/slack.js +82 -24
- package/dist/platform/index.d.ts +3 -2
- package/dist/platform/index.js +1 -1
- package/dist/platform/output-stream-chunk.d.ts +6 -0
- package/dist/platform/output-stream-chunk.js +45 -0
- package/dist/platform/output-stream-helpers.d.ts +6 -0
- package/dist/platform/output-stream-helpers.js +11 -0
- package/dist/platform/output-stream.d.ts +28 -0
- package/dist/platform/output-stream.js +4 -0
- package/dist/platform/testing.d.ts +41 -8
- package/dist/platform/testing.js +93 -11
- package/dist/platform/tool-trace.d.ts +9 -8
- package/dist/platform/tool-trace.js +19 -17
- package/dist/platform/types.d.ts +21 -1
- package/dist/platform/types.js +17 -1
- package/dist/store/channel-repo.d.ts +6 -0
- package/dist/store/channel-repo.js +9 -0
- package/dist/store/json-repository.js +12 -1
- package/dist/store/outbound-queue.d.ts +5 -4
- package/dist/store/outbound-queue.js +9 -6
- package/dist/store/schedule-repo.d.ts +9 -5
- package/dist/store/schedule-repo.js +59 -14
- package/dist/store/session-registry-repo.d.ts +36 -7
- package/dist/store/session-registry-repo.js +186 -25
- package/dist/store/thread-repo.d.ts +1 -0
- package/dist/store/thread-repo.js +8 -0
- package/package.json +1 -1
- package/dist/platform/virtual-message.d.ts +0 -68
|
@@ -7,11 +7,10 @@ import { createLogger } from '../../../core/log.js';
|
|
|
7
7
|
import * as executionRegistry from '../../executions/registry.js';
|
|
8
8
|
const log = createLogger('scheduled-task');
|
|
9
9
|
import * as pendingTaskTracker from '../../tasks/pending-tracker.js';
|
|
10
|
-
import {
|
|
11
|
-
import { sessionRepo } from '../../../store/session-repo.js';
|
|
10
|
+
import { sessionStore } from '../../../store/session-registry-repo.js';
|
|
12
11
|
import { threadStore } from '../../../store/thread-repo.js';
|
|
13
|
-
import { getActiveProfile,
|
|
14
|
-
import {
|
|
12
|
+
import { getActiveProfile, getDefaultAgent } from '../../agents/index.js';
|
|
13
|
+
import { projectStore } from '../../projects/index.js';
|
|
15
14
|
import { normalizeSkillCommandPrefix } from '../../memory/skill-scanner.js';
|
|
16
15
|
import { isValidDispatchPrompt, hasRunningExecutionForSchedule } from '../../tasks/dispatcher.js';
|
|
17
16
|
import { allConfigsRateLimited } from '../../agents/facade.js';
|
|
@@ -38,8 +37,8 @@ function passScheduledGuards(schedKey, scheduleTaskId) {
|
|
|
38
37
|
}
|
|
39
38
|
return true;
|
|
40
39
|
}
|
|
41
|
-
export function runScheduledTask({ message,
|
|
42
|
-
const schedKey = `sched:${scheduleTaskId ||
|
|
40
|
+
export function runScheduledTask({ message, projectId, scheduleTaskId, profileName, target, fallback }) {
|
|
41
|
+
const schedKey = `sched:${scheduleTaskId || projectId}`;
|
|
43
42
|
if (!passScheduledGuards(schedKey, scheduleTaskId))
|
|
44
43
|
return;
|
|
45
44
|
const normalizedMessage = normalizeSkillCommandPrefix(message);
|
|
@@ -47,7 +46,7 @@ export function runScheduledTask({ message, channel, scheduleTaskId, profileName
|
|
|
47
46
|
log.info('Auto-prefixed skill command:', normalizedMessage.substring(0, 80));
|
|
48
47
|
}
|
|
49
48
|
if (!isValidDispatchPrompt(normalizedMessage)) {
|
|
50
|
-
log.warn(`Guard dropped null/empty prompt for schedule ${scheduleTaskId} (
|
|
49
|
+
log.warn(`Guard dropped null/empty prompt for schedule ${scheduleTaskId} (project=${projectId}, profile=${profileName}): "${message?.substring(0, 60) || String(message)}"`);
|
|
51
50
|
return;
|
|
52
51
|
}
|
|
53
52
|
if (allConfigsRateLimited(profileName)) {
|
|
@@ -56,57 +55,57 @@ export function runScheduledTask({ message, channel, scheduleTaskId, profileName
|
|
|
56
55
|
}
|
|
57
56
|
scheduledTaskActive.set(schedKey, true);
|
|
58
57
|
ctx.bus.publish({ type: 'llm.active-count-delta', delta: 1 });
|
|
59
|
-
runScheduledTaskAsync({ normalizedMessage, message,
|
|
58
|
+
runScheduledTaskAsync({ normalizedMessage, message, projectId, scheduleTaskId, profileName, target, fallback }).finally(() => {
|
|
60
59
|
scheduledTaskActive.delete(schedKey);
|
|
61
60
|
ctx.bus.publish({ type: 'llm.active-count-delta', delta: -1 });
|
|
62
61
|
});
|
|
63
62
|
}
|
|
64
63
|
// --- Plan resolution ---
|
|
65
|
-
async function resolveDispatchPlan(
|
|
66
|
-
const
|
|
67
|
-
return planScheduledDispatch({
|
|
64
|
+
async function resolveDispatchPlan(projectId, target, fallback) {
|
|
65
|
+
const plan = await planScheduledDispatch({
|
|
68
66
|
target,
|
|
69
67
|
fallback,
|
|
70
|
-
fallbackChannel:
|
|
68
|
+
fallbackChannel: projectId,
|
|
71
69
|
lookups: {
|
|
72
|
-
|
|
73
|
-
getChannelSession: (ch) => sessionRepo.getSessionAsync(ch, backend),
|
|
74
|
-
lookupSession: (name) => sessionRegistryRepo.lookupSession(name),
|
|
70
|
+
lookupSession: (name) => sessionStore.lookupSession(name),
|
|
75
71
|
getThread: (id) => threadStore.get(id),
|
|
76
72
|
},
|
|
77
73
|
});
|
|
74
|
+
return plan;
|
|
78
75
|
}
|
|
79
76
|
// --- Async implementation ---
|
|
80
|
-
async function runScheduledTaskAsync({ normalizedMessage, message,
|
|
77
|
+
async function runScheduledTaskAsync({ normalizedMessage, message, projectId, scheduleTaskId, profileName, target, fallback }) {
|
|
81
78
|
const startTime = Date.now();
|
|
82
|
-
const
|
|
83
|
-
|
|
79
|
+
const plan = await resolveDispatchPlan(projectId, target, fallback);
|
|
80
|
+
// Build the project-report destination for all outbound messages from this scheduled run.
|
|
81
|
+
const projectReportDest = { type: 'project-report', projectId, trigger: 'scheduled', sessionId: '' };
|
|
82
|
+
const effectiveProfile = profileName || getActiveProfile(projectId) || 'default';
|
|
83
|
+
const sessionName = await sessionStore.generateSessionName();
|
|
84
84
|
const adapter = ctx.adapter;
|
|
85
|
-
const plan = await resolveDispatchPlan(channel, target, fallback);
|
|
86
85
|
// Skip plans short-circuit before posting the processing status, so they don't pollute Slack.
|
|
87
86
|
if (plan.kind === 'skip') {
|
|
88
87
|
log.info(`Skipping schedule ${scheduleTaskId}: ${plan.reason}`);
|
|
89
88
|
try {
|
|
90
|
-
await adapter.postMessage(
|
|
89
|
+
await adapter.postMessage(projectReportDest, { text: `:fast_forward: Scheduled task skipped — ${plan.reason}` });
|
|
91
90
|
}
|
|
92
91
|
catch { }
|
|
93
92
|
return;
|
|
94
93
|
}
|
|
95
94
|
let statusMsg = null;
|
|
96
95
|
try {
|
|
97
|
-
statusMsg = await adapter.postMessage(
|
|
96
|
+
statusMsg = await adapter.postMessage(projectReportDest, { text: buildUserProcessingMessage({ startTime, profileName: effectiveProfile, sessionName }) });
|
|
98
97
|
}
|
|
99
98
|
catch (e) {
|
|
100
99
|
log.error('Failed to post status message:', e.message);
|
|
101
100
|
}
|
|
102
101
|
try {
|
|
103
|
-
const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName });
|
|
102
|
+
const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId });
|
|
104
103
|
const result = threadResult.lastAgentResult;
|
|
105
|
-
await maybeNotifyCodexLowUsage({ adapter,
|
|
104
|
+
await maybeNotifyCodexLowUsage({ adapter, result });
|
|
106
105
|
if (result?.rateLimited) {
|
|
107
106
|
const { elapsedStr } = computeElapsed(startTime);
|
|
108
107
|
if (statusMsg) {
|
|
109
|
-
const text = `:warning: ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr}
|
|
108
|
+
const text = `:warning: ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
|
|
110
109
|
const queue = getOutboundQueue();
|
|
111
110
|
if (queue) {
|
|
112
111
|
await durableUpdate(queue, adapter, statusMsg, { text });
|
|
@@ -117,8 +116,8 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
|
|
|
117
116
|
}
|
|
118
117
|
}
|
|
119
118
|
else {
|
|
120
|
-
await finalizeThreadSuccess(adapter,
|
|
121
|
-
startTime, sessionName, result, threadResult, project:
|
|
119
|
+
await finalizeThreadSuccess(adapter, projectId, statusMsg, {
|
|
120
|
+
startTime, sessionName, result, threadResult, project: projectId, trigger: 'scheduled',
|
|
122
121
|
label: message?.substring(0, 60) || null, sessionKind: 'scheduled', statusPrefix: 'Done',
|
|
123
122
|
});
|
|
124
123
|
}
|
|
@@ -127,7 +126,7 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
|
|
|
127
126
|
const { elapsedStr } = computeElapsed(startTime);
|
|
128
127
|
const queue = getOutboundQueue();
|
|
129
128
|
if (statusMsg) {
|
|
130
|
-
const text = `:x: ${buildSessionTag(sessionName, null)}Error (${elapsedStr}
|
|
129
|
+
const text = `:x: ${buildSessionTag(sessionName, null)}Error (${elapsedStr})`;
|
|
131
130
|
if (queue) {
|
|
132
131
|
await durableUpdate(queue, adapter, statusMsg, { text });
|
|
133
132
|
}
|
|
@@ -137,21 +136,22 @@ async function runScheduledTaskAsync({ normalizedMessage, message, channel, sche
|
|
|
137
136
|
}
|
|
138
137
|
try {
|
|
139
138
|
if (queue) {
|
|
140
|
-
await durablePost(queue, adapter,
|
|
139
|
+
await durablePost(queue, adapter, projectReportDest, { text: `Scheduled task error: ${error.message}` });
|
|
141
140
|
}
|
|
142
141
|
else {
|
|
143
|
-
await adapter.postMessage(
|
|
142
|
+
await adapter.postMessage(projectReportDest, { text: `Scheduled task error: ${error.message}` });
|
|
144
143
|
}
|
|
145
144
|
}
|
|
146
145
|
catch { }
|
|
147
146
|
}
|
|
148
147
|
}
|
|
149
|
-
function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName }) {
|
|
150
|
-
const project =
|
|
151
|
-
const onProgress = statusMsg ? buildProgressUpdater(ctx.adapter,
|
|
152
|
-
const icb = ctx.buildInteractiveCallbacks?.(
|
|
148
|
+
function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId }) {
|
|
149
|
+
const project = projectStore.resolveFromMessage(message)?.id ?? 'general';
|
|
150
|
+
const onProgress = statusMsg ? buildProgressUpdater(ctx.adapter, statusMsg, startTime, effectiveProfile, sessionName) : undefined;
|
|
151
|
+
const icb = ctx.buildInteractiveCallbacks?.(projectId, null);
|
|
153
152
|
const baseRunOpts = {
|
|
154
|
-
adapter: ctx.adapter, channel:
|
|
153
|
+
adapter: ctx.adapter, channel: projectId, threadTs: statusMsg?.messageId || null, statusMsg, startTime, onProgress,
|
|
154
|
+
destination: projectReportDest,
|
|
155
155
|
onToolUse: icb?.onToolUse ?? null, onPlanWritten: icb?.onPlanWritten ?? null, onAskUserQuestion: icb?.onAskUserQuestion ?? null,
|
|
156
156
|
};
|
|
157
157
|
if (plan.kind === 'continue-thread') {
|
|
@@ -164,10 +164,11 @@ function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effe
|
|
|
164
164
|
userMessage: normalizedMessage,
|
|
165
165
|
userMessageTs: `sched_${Date.now()}`,
|
|
166
166
|
platformThreadId: statusMsg?.messageId || null,
|
|
167
|
+
projectId: project,
|
|
167
168
|
});
|
|
168
169
|
// Default-thread metadata is unused by createDefaultThread today, so attach trigger / scheduleTaskId
|
|
169
170
|
// post-creation so executionRegistry rows still carry the schedule association.
|
|
170
|
-
threadStore.set({ ...thread, metadata: { scheduleTaskId, trigger: 'scheduled',
|
|
171
|
+
threadStore.set({ ...thread, metadata: { scheduleTaskId, trigger: 'scheduled', profileOverride: effectiveProfile } });
|
|
171
172
|
return runThreadExec(thread.id, { ...baseRunOpts, existingSessionId: plan.existingSessionId });
|
|
172
173
|
}
|
|
173
174
|
// plan.kind === 'fresh' — original scheduled-task semantics: scheduler template, fresh session.
|
|
@@ -175,7 +176,8 @@ function dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effe
|
|
|
175
176
|
templateName: 'scheduler',
|
|
176
177
|
userMessage: normalizedMessage,
|
|
177
178
|
userMessageTs: `sched_${Date.now()}`,
|
|
178
|
-
|
|
179
|
+
projectId: project,
|
|
180
|
+
metadata: { scheduleTaskId, trigger: 'scheduled', profileOverride: effectiveProfile },
|
|
179
181
|
});
|
|
180
182
|
return runThreadExec(thread.id, { ...baseRunOpts, existingSessionId: null });
|
|
181
183
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// input: sync-public script + PlatformAdapter
|
|
2
|
+
// output: sync-public job runner — registers as 'sync-public'
|
|
3
|
+
// pos: periodic fetch + cherry-pick from public/main to main (non-LLM programmatic work)
|
|
4
|
+
import { register, ctx } from '../job-registry.js';
|
|
5
|
+
import { execSync } from 'child_process';
|
|
6
|
+
const SYNC_SCRIPT = '/home/fangxin/Cortex/scripts/sync-pull-from-public.sh';
|
|
7
|
+
// Self-register
|
|
8
|
+
register('sync-public', async (payload) => {
|
|
9
|
+
const { channel } = payload;
|
|
10
|
+
const adapter = ctx.adapter;
|
|
11
|
+
try {
|
|
12
|
+
const output = execSync(`bash "${SYNC_SCRIPT}"`, {
|
|
13
|
+
timeout: 30_000,
|
|
14
|
+
encoding: 'utf-8',
|
|
15
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
16
|
+
});
|
|
17
|
+
const lines = output.trim().split('\n');
|
|
18
|
+
const lastLine = lines[lines.length - 1] || '';
|
|
19
|
+
if (lastLine.includes('0 failed') || lastLine.includes('everything in sync') || lastLine.includes('OK:') || lastLine.includes('SKIP:')) {
|
|
20
|
+
// Quiet success — no message needed unless there were actual syncs
|
|
21
|
+
const countLine = lines.find(l => l.includes('cherry-picked'));
|
|
22
|
+
if (countLine && !countLine.includes('0 cherry-picked')) {
|
|
23
|
+
await adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:arrows_counterclockwise: Public sync: ${countLine.trim()}` });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
await adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:warning: Public sync issue:\n\`\`\`\n${output.slice(-500)}\n\`\`\`` });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
const msg = err?.stderr || err?.message || String(err);
|
|
32
|
+
await adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:warning: Public sync error: ${msg.slice(0, 500)}` });
|
|
33
|
+
}
|
|
34
|
+
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ScheduleTarget, ScheduleTask } from '../../../store/schedule-repo.js';
|
|
2
2
|
import type { ThreadRecord } from '../../../core/types/thread-types.js';
|
|
3
|
-
import type {
|
|
3
|
+
import type { Session } from '../../../store/session-registry-repo.js';
|
|
4
4
|
/** What scheduled-task.ts should do at fire time. Each kind maps to one runtime branch:
|
|
5
5
|
* - fresh / default-thread → createDefaultThread + runThreadExec (default-path)
|
|
6
6
|
* - continue-thread → continueThread (resumes the existing thread's slot session)
|
|
@@ -22,19 +22,15 @@ export type DispatchPlan = {
|
|
|
22
22
|
reason: string;
|
|
23
23
|
};
|
|
24
24
|
export interface DispatchLookups {
|
|
25
|
-
/** Active thread (status running|waiting) for the channel, or null. */
|
|
26
|
-
findActiveThread(channel: string): ThreadRecord | null;
|
|
27
|
-
/** Channel-default sessionId (the one a fresh user message would resume), or undefined. */
|
|
28
|
-
getChannelSession(channel: string): Promise<string | undefined>;
|
|
29
25
|
/** Look up a cortex-XXXX session record. Null if it's been GC'd or never registered. */
|
|
30
|
-
lookupSession(sessionName: string): Promise<
|
|
26
|
+
lookupSession(sessionName: string): Promise<Session | null>;
|
|
31
27
|
/** Look up a thread record by id. Null if missing. */
|
|
32
28
|
getThread(threadId: string): ThreadRecord | null;
|
|
33
29
|
}
|
|
34
30
|
export interface DispatchPlanInput {
|
|
35
31
|
target: ScheduleTarget | undefined;
|
|
36
32
|
fallback: ScheduleTask['fallback'];
|
|
37
|
-
/** Channel to use when falling back to fresh — typically the schedule's own
|
|
33
|
+
/** Channel to use when falling back to fresh — typically the schedule's own resolved channel. */
|
|
38
34
|
fallbackChannel: string;
|
|
39
35
|
lookups: DispatchLookups;
|
|
40
36
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// input: ScheduleTarget + lookup callbacks (
|
|
1
|
+
// input: ScheduleTarget + lookup callbacks (session/thread stores)
|
|
2
2
|
// output: planScheduledDispatch — pure decision tree picking how to land a fired schedule
|
|
3
|
-
// pos: extracted from scheduled-task.ts so the
|
|
3
|
+
// pos: extracted from scheduled-task.ts so the target dispatch is unit-testable
|
|
4
4
|
// without spinning up the platform adapter, execution registry, or thread runner.
|
|
5
|
+
// Removed channel variant in M4; project replaces it as the default target kind.
|
|
5
6
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
6
7
|
function applyFallback(input, reason) {
|
|
7
8
|
const policy = input.fallback ?? 'fresh';
|
|
@@ -16,13 +17,10 @@ export async function planScheduledDispatch(input) {
|
|
|
16
17
|
if (target.kind === 'fresh') {
|
|
17
18
|
return { kind: 'fresh', channel: input.fallbackChannel };
|
|
18
19
|
}
|
|
19
|
-
if (target.kind === '
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
const sessionId = (await input.lookups.getChannelSession(target.channel)) ?? null;
|
|
25
|
-
return { kind: 'default-thread', channel: target.channel, existingSessionId: sessionId };
|
|
20
|
+
if (target.kind === 'project') {
|
|
21
|
+
// Always spawn a fresh session in the project channel.
|
|
22
|
+
// The scheduler resolves projectId → channel before calling runScheduledTask.
|
|
23
|
+
return { kind: 'fresh', channel: input.fallbackChannel };
|
|
26
24
|
}
|
|
27
25
|
if (target.kind === 'session') {
|
|
28
26
|
const record = await input.lookups.lookupSession(target.sessionName);
|
|
@@ -10,10 +10,10 @@ register('task-archive', async (payload) => {
|
|
|
10
10
|
const adapter = ctx.adapter;
|
|
11
11
|
if (results.archived.length > 0) {
|
|
12
12
|
const summary = results.archived.map((r) => `*${r.project}*: archived ${r.ids.length} tasks`).join('\n');
|
|
13
|
-
await adapter.postMessage(channel, { text: `:file_folder: Task auto-archive:\n${summary}` });
|
|
13
|
+
await adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:file_folder: Task auto-archive:\n${summary}` });
|
|
14
14
|
}
|
|
15
15
|
if (results.errors.length > 0) {
|
|
16
16
|
const errSummary = results.errors.join('\n');
|
|
17
|
-
await adapter.postMessage(channel, { text: `:warning: Task archiver errors:\n${errSummary}` });
|
|
17
|
+
await adapter.postMessage({ type: 'interactive-reply', conduit: channel }, { text: `:warning: Task archiver errors:\n${errSummary}` });
|
|
18
18
|
}
|
|
19
19
|
});
|
|
@@ -6,10 +6,9 @@ import { createLogger } from '../../../core/log.js';
|
|
|
6
6
|
import * as executionRegistry from '../../executions/registry.js';
|
|
7
7
|
const log = createLogger('task-dispatch');
|
|
8
8
|
import * as pendingTaskTracker from '../../tasks/pending-tracker.js';
|
|
9
|
-
import {
|
|
9
|
+
import { sessionStore } from '../../../store/session-registry-repo.js';
|
|
10
10
|
import { allConfigsRateLimited } from '../../agents/facade.js';
|
|
11
11
|
import { selectAndClaimTask, computeNextInterval, updateScheduleInterval } from '../../tasks/dispatcher.js';
|
|
12
|
-
import { channelRepo } from '../../../store/channel-repo.js';
|
|
13
12
|
import { taskMutator } from '../../tasks/mutator.js';
|
|
14
13
|
import { createThread } from '../../threads/index.js';
|
|
15
14
|
import { runThread as runThreadExec } from '../../threads/runner.js';
|
|
@@ -83,12 +82,11 @@ async function runDispatchAsync({ channel, scheduleTaskId, profileName }) {
|
|
|
83
82
|
}
|
|
84
83
|
async function executeDispatchTask({ selected, selectedTask, channel, scheduleTaskId, profileName, startTime }) {
|
|
85
84
|
const adapter = ctx.adapter;
|
|
86
|
-
const sessionName = await
|
|
85
|
+
const sessionName = await sessionStore.generateSessionName();
|
|
87
86
|
const effectiveProfile = profileName;
|
|
88
|
-
const effectiveChannel = (selectedTask.project && await channelRepo.getProjectChannel(selectedTask.project)) || channel;
|
|
89
87
|
let statusMsg = null;
|
|
90
88
|
try {
|
|
91
|
-
statusMsg = await adapter.postMessage(
|
|
89
|
+
statusMsg = await adapter.postMessage({ type: 'project-report', projectId: selectedTask.project || channel, trigger: 'task-dispatch', sessionId: '' }, {
|
|
92
90
|
text: `:satellite: Dispatching: [${selectedTask.project}] ${selectedTask.text.substring(0, 80)}... | ${sessionName} | ${effectiveProfile}`,
|
|
93
91
|
});
|
|
94
92
|
}
|
|
@@ -98,14 +96,16 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
98
96
|
await taskMutator.unclaim(selectedTask.id);
|
|
99
97
|
return { success: false, skipped: true, note: 'Task missing required [template:] tag' };
|
|
100
98
|
}
|
|
101
|
-
const thread = createThread(
|
|
99
|
+
const thread = createThread(channel, {
|
|
102
100
|
templateName: selected.template, userMessage: selected.prompt, userMessageTs: `dispatch_${Date.now()}`,
|
|
103
101
|
platformThreadId: statusMsg?.messageId ?? null,
|
|
104
|
-
|
|
102
|
+
projectId: selectedTask.project,
|
|
103
|
+
metadata: { scheduleTaskId, trigger: 'task-dispatch', profileOverride: effectiveProfile },
|
|
105
104
|
});
|
|
106
|
-
const icb = ctx.buildInteractiveCallbacks?.(
|
|
105
|
+
const icb = ctx.buildInteractiveCallbacks?.(channel, null);
|
|
107
106
|
const threadResult = await runThreadExec(thread.id, {
|
|
108
|
-
adapter, channel:
|
|
107
|
+
adapter, channel: channel, threadTs: statusMsg?.messageId || null, statusMsg, startTime, existingSessionId: null,
|
|
108
|
+
destination: { type: 'project-report', projectId: selectedTask.project || channel, trigger: 'task-dispatch', sessionId: '' },
|
|
109
109
|
onToolUse: icb?.onToolUse ?? null, onPlanWritten: icb?.onPlanWritten ?? null, onAskUserQuestion: icb?.onAskUserQuestion ?? null,
|
|
110
110
|
extraHooks: {
|
|
111
111
|
onEnd: {
|
|
@@ -120,7 +120,7 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
120
120
|
const { elapsedStr } = computeElapsed(startTime);
|
|
121
121
|
await taskMutator.unclaim(selectedTask.id);
|
|
122
122
|
if (statusMsg) {
|
|
123
|
-
const text = `:warning: [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr}
|
|
123
|
+
const text = `:warning: [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
|
|
124
124
|
const queue = getOutboundQueue();
|
|
125
125
|
if (queue) {
|
|
126
126
|
await durableUpdate(queue, adapter, statusMsg, { text });
|
|
@@ -131,7 +131,7 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
131
131
|
}
|
|
132
132
|
return { success: false, skipped: false, note: 'Rate limited — all fallbacks exhausted' };
|
|
133
133
|
}
|
|
134
|
-
await finalizeThreadSuccess(adapter,
|
|
134
|
+
await finalizeThreadSuccess(adapter, channel, statusMsg, {
|
|
135
135
|
startTime, sessionName, result, threadResult, project: selectedTask.project, trigger: 'task-dispatch',
|
|
136
136
|
label: selectedTask.text?.substring(0, 60) || null, sessionKind: 'scheduled',
|
|
137
137
|
statusPrefix: `Done: [${selectedTask.project}] ${selectedTask.text.substring(0, 80)}`,
|
|
@@ -151,7 +151,7 @@ async function handleDispatchError(error, selectedTask, channel) {
|
|
|
151
151
|
log.error(`Failed to unclaim task: ${e.message}`);
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
|
-
const errChannel =
|
|
154
|
+
const errChannel = channel;
|
|
155
155
|
let blocked = false;
|
|
156
156
|
let blockReason = null;
|
|
157
157
|
if (selectedTask?.task_hash) {
|
|
@@ -175,20 +175,22 @@ async function handleDispatchError(error, selectedTask, channel) {
|
|
|
175
175
|
const queue = getOutboundQueue();
|
|
176
176
|
if (blocked && selectedTask) {
|
|
177
177
|
const text = `:no_entry: Auto-blocked after ${DISPATCH_FAILURE_QUARANTINE_THRESHOLD} consecutive dispatch failures. Reason recorded in TASKS.yaml. Task: [${selectedTask.project}] ${String(selectedTask.text).substring(0, 80)}. Last error: ${error.message}. Unblock with \`cortex-task unblock --task-id ${selectedTask.id}\`.`;
|
|
178
|
+
const projDest = { type: 'project-report', projectId: selectedTask.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
|
|
178
179
|
if (queue) {
|
|
179
|
-
await durablePost(queue, adapter,
|
|
180
|
+
await durablePost(queue, adapter, projDest, { text });
|
|
180
181
|
}
|
|
181
182
|
else {
|
|
182
|
-
await adapter.postMessage(
|
|
183
|
+
await adapter.postMessage(projDest, { text });
|
|
183
184
|
}
|
|
184
185
|
}
|
|
185
186
|
else {
|
|
186
187
|
const text = `:x: Task dispatch error: ${error.message}`;
|
|
188
|
+
const projDest = { type: 'project-report', projectId: selectedTask?.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
|
|
187
189
|
if (queue) {
|
|
188
|
-
await durablePost(queue, adapter,
|
|
190
|
+
await durablePost(queue, adapter, projDest, { text });
|
|
189
191
|
}
|
|
190
192
|
else {
|
|
191
|
-
await adapter.postMessage(
|
|
193
|
+
await adapter.postMessage(projDest, { text });
|
|
192
194
|
}
|
|
193
195
|
}
|
|
194
196
|
}
|
|
@@ -2,6 +2,7 @@ import './jobs/scheduled-task.js';
|
|
|
2
2
|
import './jobs/task-dispatch.js';
|
|
3
3
|
import './jobs/memory-index-regen.js';
|
|
4
4
|
import './jobs/task-archive.js';
|
|
5
|
+
import './jobs/sync-public.js';
|
|
5
6
|
import { Scheduler } from './scheduler.js';
|
|
6
7
|
import type { EventBus } from '../../events/index.js';
|
|
7
8
|
import type { PlatformAdapter } from '../../platform/index.js';
|
|
@@ -8,6 +8,7 @@ import './jobs/scheduled-task.js';
|
|
|
8
8
|
import './jobs/task-dispatch.js';
|
|
9
9
|
import './jobs/memory-index-regen.js';
|
|
10
10
|
import './jobs/task-archive.js';
|
|
11
|
+
import './jobs/sync-public.js';
|
|
11
12
|
import { Scheduler } from './scheduler.js';
|
|
12
13
|
export function initScheduledRunner(adapter) { ctx.adapter = adapter; }
|
|
13
14
|
export function setSchedulerRef(s) { ctx.schedulerRef = s; }
|
|
@@ -17,6 +18,7 @@ export function createScheduler() {
|
|
|
17
18
|
const sched = new Scheduler(async (params) => { dispatch('scheduled-task', params); }, async (params) => { dispatch('task-dispatch', params); }, {
|
|
18
19
|
'memory-index-regen': async (params) => { dispatch('memory-index-regen', params); },
|
|
19
20
|
'task-archive': async (params) => { dispatch('task-archive', params); },
|
|
21
|
+
'sync-public': async (params) => { dispatch('sync-public', params); },
|
|
20
22
|
});
|
|
21
23
|
ctx.schedulerRef = sched;
|
|
22
24
|
return sched;
|
|
@@ -34,8 +34,8 @@ function parseUpdateArgs(args) {
|
|
|
34
34
|
patch.message = value;
|
|
35
35
|
else if (flag === '--profile')
|
|
36
36
|
patch.profile = value;
|
|
37
|
-
else if (flag === '--
|
|
38
|
-
patch.
|
|
37
|
+
else if (flag === '--project-id')
|
|
38
|
+
patch.projectId = value;
|
|
39
39
|
else if (flag === '--dispatch-type')
|
|
40
40
|
patch.dispatchType = value;
|
|
41
41
|
else if (flag === '--time')
|
|
@@ -70,7 +70,7 @@ function getScheduleHelp() {
|
|
|
70
70
|
options: [
|
|
71
71
|
{ flag: '--message <text>', description: 'Schedule message (for edit)' },
|
|
72
72
|
{ flag: '--profile <name>', description: 'Agent profile (for edit)' },
|
|
73
|
-
{ flag: '--
|
|
73
|
+
{ flag: '--project-id <id>', description: 'Project id (for edit)' },
|
|
74
74
|
{ flag: '--dispatch-type <type>', description: 'Dispatch type (for edit)' },
|
|
75
75
|
{ flag: '--time <HH:MM>', description: 'Time of day (for edit daily/weekly)' },
|
|
76
76
|
{ flag: '--day <day>', description: 'Day of week: sun-sat or 0-6 (for edit weekly)' },
|
|
@@ -152,7 +152,7 @@ async function runScheduleCli(args, options = {}) {
|
|
|
152
152
|
// Detect flag mode vs legacy positional mode
|
|
153
153
|
if (rest[0]?.startsWith('--')) {
|
|
154
154
|
// Flag mode: add --type interval --interval 30m --message "msg"
|
|
155
|
-
const addArgs = { type: null, interval: null, time: null, day: null, delay: null, message: null,
|
|
155
|
+
const addArgs = { type: null, interval: null, time: null, day: null, delay: null, message: null, projectId: options.projectId || 'general', profile: null };
|
|
156
156
|
for (let i = 0; i < rest.length; i += 2) {
|
|
157
157
|
const flag = rest[i], value = rest[i + 1];
|
|
158
158
|
if (!flag?.startsWith('--') || value == null)
|
|
@@ -169,8 +169,8 @@ async function runScheduleCli(args, options = {}) {
|
|
|
169
169
|
addArgs.delay = value;
|
|
170
170
|
else if (flag === '--message')
|
|
171
171
|
addArgs.message = value;
|
|
172
|
-
else if (flag === '--
|
|
173
|
-
addArgs.
|
|
172
|
+
else if (flag === '--project-id')
|
|
173
|
+
addArgs.projectId = value;
|
|
174
174
|
else if (flag === '--profile')
|
|
175
175
|
addArgs.profile = value;
|
|
176
176
|
else
|
|
@@ -186,12 +186,12 @@ async function runScheduleCli(args, options = {}) {
|
|
|
186
186
|
if (addArgs.type === 'interval') {
|
|
187
187
|
if (!addArgs.interval)
|
|
188
188
|
return fail('--interval is required for add --type interval');
|
|
189
|
-
return ok({ task: await scheduler.add('interval', { intervalMs: parseMaybeDuration(addArgs.interval), message: addArgs.message,
|
|
189
|
+
return ok({ task: await scheduler.add('interval', { intervalMs: parseMaybeDuration(addArgs.interval), message: addArgs.message, projectId: addArgs.projectId, profile: addArgs.profile }) });
|
|
190
190
|
}
|
|
191
191
|
if (addArgs.type === 'daily') {
|
|
192
192
|
if (!addArgs.time)
|
|
193
193
|
return fail('--time is required for add --type daily');
|
|
194
|
-
return ok({ task: await scheduler.add('daily', { time: addArgs.time, message: addArgs.message,
|
|
194
|
+
return ok({ task: await scheduler.add('daily', { time: addArgs.time, message: addArgs.message, projectId: addArgs.projectId, profile: addArgs.profile }) });
|
|
195
195
|
}
|
|
196
196
|
if (addArgs.type === 'weekly') {
|
|
197
197
|
if (!addArgs.day)
|
|
@@ -199,12 +199,12 @@ async function runScheduleCli(args, options = {}) {
|
|
|
199
199
|
if (!addArgs.time)
|
|
200
200
|
return fail('--time is required for add --type weekly');
|
|
201
201
|
const dayOfWeek = Number.isInteger(Number(addArgs.day)) ? Number(addArgs.day) : DAY_MAP[addArgs.day.toLowerCase()];
|
|
202
|
-
return ok({ task: await scheduler.add('weekly', { dayOfWeek, time: addArgs.time, message: addArgs.message,
|
|
202
|
+
return ok({ task: await scheduler.add('weekly', { dayOfWeek, time: addArgs.time, message: addArgs.message, projectId: addArgs.projectId, profile: addArgs.profile }) });
|
|
203
203
|
}
|
|
204
204
|
if (addArgs.type === 'once') {
|
|
205
205
|
if (!addArgs.delay)
|
|
206
206
|
return fail('--delay is required for add --type once');
|
|
207
|
-
return ok({ task: await scheduler.add('once', { delay: parseMaybeDuration(addArgs.delay), message: addArgs.message,
|
|
207
|
+
return ok({ task: await scheduler.add('once', { delay: parseMaybeDuration(addArgs.delay), message: addArgs.message, projectId: addArgs.projectId, profile: addArgs.profile }) });
|
|
208
208
|
}
|
|
209
209
|
return fail(`Unknown add type: '${addArgs.type}'. Valid types: interval, daily, weekly, once`);
|
|
210
210
|
}
|
|
@@ -216,7 +216,7 @@ async function runScheduleCli(args, options = {}) {
|
|
|
216
216
|
const err = assertValidMessage(message);
|
|
217
217
|
if (err)
|
|
218
218
|
return fail(err);
|
|
219
|
-
return ok({ task: await scheduler.add('interval', { intervalMs, message,
|
|
219
|
+
return ok({ task: await scheduler.add('interval', { intervalMs, message, projectId: options.projectId || 'general', profile: null }) });
|
|
220
220
|
}
|
|
221
221
|
if (type === 'daily') {
|
|
222
222
|
const time = rest[1];
|
|
@@ -224,7 +224,7 @@ async function runScheduleCli(args, options = {}) {
|
|
|
224
224
|
const err = assertValidMessage(message);
|
|
225
225
|
if (err)
|
|
226
226
|
return fail(err);
|
|
227
|
-
return ok({ task: await scheduler.add('daily', { time, message,
|
|
227
|
+
return ok({ task: await scheduler.add('daily', { time, message, projectId: options.projectId || 'general', profile: null }) });
|
|
228
228
|
}
|
|
229
229
|
if (type === 'weekly') {
|
|
230
230
|
const dayValue = rest[1];
|
|
@@ -234,7 +234,7 @@ async function runScheduleCli(args, options = {}) {
|
|
|
234
234
|
const err = assertValidMessage(message);
|
|
235
235
|
if (err)
|
|
236
236
|
return fail(err);
|
|
237
|
-
return ok({ task: await scheduler.add('weekly', { dayOfWeek, time, message,
|
|
237
|
+
return ok({ task: await scheduler.add('weekly', { dayOfWeek, time, message, projectId: options.projectId || 'general', profile: null }) });
|
|
238
238
|
}
|
|
239
239
|
if (type === 'once') {
|
|
240
240
|
const delay = parseMaybeDuration(rest[1]);
|
|
@@ -242,7 +242,7 @@ async function runScheduleCli(args, options = {}) {
|
|
|
242
242
|
const err = assertValidMessage(message);
|
|
243
243
|
if (err)
|
|
244
244
|
return fail(err);
|
|
245
|
-
return ok({ task: await scheduler.add('once', { delay, message,
|
|
245
|
+
return ok({ task: await scheduler.add('once', { delay, message, projectId: options.projectId || 'general', profile: null }) });
|
|
246
246
|
}
|
|
247
247
|
return fail(`Unknown add type: '${type}'. Valid types: interval, daily, weekly, once`);
|
|
248
248
|
}
|