ocean-crew 0.0.0-stage → 0.4.0
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/LICENSE +21 -0
- package/README.md +156 -2
- package/THIRD_PARTY_NOTICES.md +159 -0
- package/client.js +31389 -0
- package/cordis.patch.yml +6 -0
- package/dist/host/chat/btw.js +436 -0
- package/dist/host/chat/channel.js +1241 -0
- package/dist/host/chat/chat-index.js +344 -0
- package/dist/host/chat/delivery.js +231 -0
- package/dist/host/chat/feed.js +165 -0
- package/dist/host/chat/handoffs.js +625 -0
- package/dist/host/chat/parts.js +2033 -0
- package/dist/host/chat/requests.js +155 -0
- package/dist/host/chat/resume.js +364 -0
- package/dist/host/chat/side.js +457 -0
- package/dist/host/chat/steer.js +346 -0
- package/dist/host/chat/turns.js +1457 -0
- package/dist/host/connectors/catalog.js +331 -0
- package/dist/host/connectors/gateway.js +339 -0
- package/dist/host/connectors/index.js +1235 -0
- package/dist/host/connectors/mail/index.js +912 -0
- package/dist/host/connectors/mail/presets.js +53 -0
- package/dist/host/connectors/mail/transport.js +519 -0
- package/dist/host/connectors/oauth.js +337 -0
- package/dist/host/core/constants.js +123 -0
- package/dist/host/core/diagnostics.js +310 -0
- package/dist/host/core/dsh-update.js +212 -0
- package/dist/host/core/events.js +16 -0
- package/dist/host/core/files.js +37 -0
- package/dist/host/core/folders.js +283 -0
- package/dist/host/core/home-lock.js +137 -0
- package/dist/host/core/links.js +52 -0
- package/dist/host/core/runtime.js +5 -0
- package/dist/host/core/store.js +662 -0
- package/dist/host/core/text.js +59 -0
- package/dist/host/core/thinking.js +60 -0
- package/dist/host/core/time-context.js +69 -0
- package/dist/host/core/update.js +466 -0
- package/dist/host/groups/calls.js +684 -0
- package/dist/host/groups/index.js +79 -0
- package/dist/host/groups/log.js +334 -0
- package/dist/host/groups/prompt.js +124 -0
- package/dist/host/groups/relay.js +489 -0
- package/dist/host/groups/round.js +992 -0
- package/dist/host/groups/tasks.js +217 -0
- package/dist/host/groups/tools.js +478 -0
- package/dist/host/groups/types.js +8 -0
- package/dist/host/im/format.js +228 -0
- package/dist/host/im/index.js +2461 -0
- package/dist/host/im/platforms/feishu.js +1134 -0
- package/dist/host/im/platforms/index.js +6 -0
- package/dist/host/im/platforms/media-type.js +70 -0
- package/dist/host/im/platforms/weixin.js +1117 -0
- package/dist/host/im/reaction.js +51 -0
- package/dist/host/im/supervisor.js +56 -0
- package/dist/host/team/agents.js +161 -0
- package/dist/host/team/models.js +427 -0
- package/dist/host/team/permissions.js +263 -0
- package/dist/host/team/privacy.js +108 -0
- package/dist/host/team/prompt.js +86 -0
- package/dist/host/team/providers.js +461 -0
- package/dist/host/team/roster.js +1011 -0
- package/dist/host/team/tools.js +1638 -0
- package/dist/host/work/approvals.js +290 -0
- package/dist/host/work/avatar-library.js +155 -0
- package/dist/host/work/avatar.js +132 -0
- package/dist/host/work/capabilities.js +862 -0
- package/dist/host/work/companion.js +306 -0
- package/dist/host/work/goal-skills.js +91 -0
- package/dist/host/work/goals.js +1337 -0
- package/dist/host/work/images.js +283 -0
- package/dist/host/work/learning.js +1021 -0
- package/dist/host/work/memory-pending.js +108 -0
- package/dist/host/work/memory.js +3237 -0
- package/dist/host/work/notify.js +146 -0
- package/dist/host/work/reset.js +43 -0
- package/dist/host/work/schedules.js +309 -0
- package/dist/host/work/secrets.js +702 -0
- package/dist/host/work/steward.js +166 -0
- package/dist/host/work/tts.js +192 -0
- package/dist/host/work/usage.js +84 -0
- package/dist/index.js +137 -0
- package/dist/shared/api.js +32 -0
- package/dist/shared/companion.js +110 -0
- package/dist/shared/config.js +3 -0
- package/dist/shared/coordination.js +6 -0
- package/dist/shared/group-replies.js +95 -0
- package/dist/shared/im-platforms.js +35 -0
- package/dist/shared/im.js +3 -0
- package/dist/shared/mentions.js +85 -0
- package/dist/shared/state.js +25 -0
- package/package.json +81 -5
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The low-interruption notification policy. One pure decision says whether a notice
|
|
2
|
+
// should be delivered now, held for a later time or dropped. It never sends, reads a
|
|
3
|
+
// clock or records anything: time, receipts and budget come from the caller, and only
|
|
4
|
+
// the delivery path may add a receipt after the transport accepts the notice.
|
|
5
|
+
//
|
|
6
|
+
// Precedence: duplicate -> pending action (always shown) -> the user's own result or
|
|
7
|
+
// subscribed change (budget-free; quiet hours defer) -> optional suggestion (value,
|
|
8
|
+
// rejection, frequency, quiet hours and budget). A decision is not a receipt.
|
|
9
|
+
/**
|
|
10
|
+
* Decide one notice. The same input always gives the same decision; the returned
|
|
11
|
+
* `dedupeKey` becomes a receipt only after the transport accepts the notice.
|
|
12
|
+
*/
|
|
13
|
+
export function decideNotification(input) {
|
|
14
|
+
const { now, event, preferences, quietHours, budget } = input;
|
|
15
|
+
const receipts = input.history?.receipts ?? [];
|
|
16
|
+
const dedupeKey = dedupeKeyOf(event);
|
|
17
|
+
if (receipts.some((receipt) => receipt.dedupeKey === dedupeKey))
|
|
18
|
+
return held("duplicate");
|
|
19
|
+
// A decision the user must make is never pressed down by quiet hours or budget:
|
|
20
|
+
// the work is blocked until the user acts, so hiding it only extends the block.
|
|
21
|
+
if (event.kind === "pending") {
|
|
22
|
+
if (event.items.length === 0)
|
|
23
|
+
return held("nothing_pending");
|
|
24
|
+
return delivered(event.kind, "pending_action", dedupeKey, false);
|
|
25
|
+
}
|
|
26
|
+
// The user asked for this result. Quiet hours may defer it, but budget and
|
|
27
|
+
// optional-suggestion preferences never suppress it.
|
|
28
|
+
if (event.kind === "requested_result") {
|
|
29
|
+
const deferred = quietUntil(now, quietHours);
|
|
30
|
+
if (deferred !== undefined)
|
|
31
|
+
return held("quiet_hours", deferred);
|
|
32
|
+
return delivered(event.kind, "requested_result", dedupeKey, false);
|
|
33
|
+
}
|
|
34
|
+
// A subscribed change is the content the user asked to watch. No change is either
|
|
35
|
+
// silence or an all-clear by agreement; both follow the normal quiet window.
|
|
36
|
+
if (event.kind === "subscribed_change") {
|
|
37
|
+
if (!event.changed && preferences.noChange === "silent")
|
|
38
|
+
return held("no_change_silent");
|
|
39
|
+
const deferred = quietUntil(now, quietHours);
|
|
40
|
+
if (deferred !== undefined)
|
|
41
|
+
return held("quiet_hours", deferred);
|
|
42
|
+
return delivered(event.kind, event.changed ? "subscribed_change" : "no_change_all_clear", dedupeKey, false);
|
|
43
|
+
}
|
|
44
|
+
// Proactive suggestions are the only notices the budget and feedback constrain.
|
|
45
|
+
const suggestions = preferences.suggestions;
|
|
46
|
+
if (suggestions === undefined)
|
|
47
|
+
return held("suggestions_off");
|
|
48
|
+
if (!(event.value >= suggestions.minValue))
|
|
49
|
+
return held("below_value");
|
|
50
|
+
const blockers = [];
|
|
51
|
+
const rejectedAt = input.history?.lastRejectedAt;
|
|
52
|
+
if (rejectedAt !== undefined) {
|
|
53
|
+
const until = rejectedAt + suggestions.rejectionCooldownMs;
|
|
54
|
+
if (until > now)
|
|
55
|
+
blockers.push({ reason: "recent_rejection", until });
|
|
56
|
+
}
|
|
57
|
+
const lastOptionalAt = lastOptionalReceiptAt(receipts);
|
|
58
|
+
if (lastOptionalAt !== undefined) {
|
|
59
|
+
const until = lastOptionalAt + suggestions.minGapMs;
|
|
60
|
+
if (until > now)
|
|
61
|
+
blockers.push({ reason: "frequency_limited", until });
|
|
62
|
+
}
|
|
63
|
+
if (quietHours !== undefined) {
|
|
64
|
+
const until = quietUntil(now, quietHours);
|
|
65
|
+
if (until !== undefined)
|
|
66
|
+
blockers.push({ reason: "quiet_hours", until });
|
|
67
|
+
}
|
|
68
|
+
if (budget !== undefined && budget.used >= budget.limit && budget.resetsAt > now) {
|
|
69
|
+
blockers.push({ reason: "budget_exhausted", until: budget.resetsAt });
|
|
70
|
+
}
|
|
71
|
+
const first = blockers[0];
|
|
72
|
+
if (first !== undefined) {
|
|
73
|
+
// Hold until every active constraint is over, not just the named reason.
|
|
74
|
+
const until = Math.max(...blockers.map((blocker) => blocker.until));
|
|
75
|
+
return held(first.reason, until);
|
|
76
|
+
}
|
|
77
|
+
return delivered(event.kind, "optional_suggestion", dedupeKey, true);
|
|
78
|
+
}
|
|
79
|
+
function delivered(kind, reason, dedupeKey, countsBudget) {
|
|
80
|
+
return { deliver: true, reason, kind, dedupeKey, countsBudget };
|
|
81
|
+
}
|
|
82
|
+
function held(reason, deferred) {
|
|
83
|
+
return deferred === undefined ? { deliver: false, reason } : { deliver: false, reason, deferred };
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A stable dedupe key. A real change is keyed by source version, so the same content
|
|
87
|
+
* reported under a new notice id is still a duplicate. An all-clear is keyed by the
|
|
88
|
+
* check's notice id: its source version does not change, and each check is a heartbeat.
|
|
89
|
+
*/
|
|
90
|
+
function dedupeKeyOf(event) {
|
|
91
|
+
switch (event.kind) {
|
|
92
|
+
case "requested_result":
|
|
93
|
+
return `requested:${event.noticeId}`;
|
|
94
|
+
case "pending":
|
|
95
|
+
return `pending:${event.noticeId}`;
|
|
96
|
+
case "subscribed_change":
|
|
97
|
+
return event.changed
|
|
98
|
+
? `subscribed:${JSON.stringify([event.subscriptionId, event.sourceVersion])}`
|
|
99
|
+
: `all_clear:${event.noticeId}`;
|
|
100
|
+
case "optional_suggestion":
|
|
101
|
+
return `suggestion:${event.noticeId}`;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** When the last optional notice was accepted; only receipts count, never decisions. */
|
|
105
|
+
function lastOptionalReceiptAt(receipts) {
|
|
106
|
+
let latest;
|
|
107
|
+
for (const receipt of receipts) {
|
|
108
|
+
if (receipt.kind !== "optional_suggestion")
|
|
109
|
+
continue;
|
|
110
|
+
if (latest === undefined || receipt.acceptedAt > latest)
|
|
111
|
+
latest = receipt.acceptedAt;
|
|
112
|
+
}
|
|
113
|
+
return latest;
|
|
114
|
+
}
|
|
115
|
+
/** The minute after local midnight, with the host-supplied UTC offset. */
|
|
116
|
+
function localMinute(now, utcOffsetMinutes) {
|
|
117
|
+
const minute = Math.floor((now + utcOffsetMinutes * 60_000) / 60_000) % 1440;
|
|
118
|
+
return minute < 0 ? minute + 1440 : minute;
|
|
119
|
+
}
|
|
120
|
+
/** True while `now` falls inside the half-open daily quiet window. */
|
|
121
|
+
function isQuiet(now, quiet) {
|
|
122
|
+
// Equal bounds mean the user configured no window.
|
|
123
|
+
if (quiet.startMinute === quiet.endMinute)
|
|
124
|
+
return false;
|
|
125
|
+
const minute = localMinute(now, quiet.utcOffsetMinutes);
|
|
126
|
+
if (quiet.startMinute < quiet.endMinute) {
|
|
127
|
+
return minute >= quiet.startMinute && minute < quiet.endMinute;
|
|
128
|
+
}
|
|
129
|
+
return minute >= quiet.startMinute || minute < quiet.endMinute;
|
|
130
|
+
}
|
|
131
|
+
/** The epoch ms when the quiet window that contains `now` ends. */
|
|
132
|
+
function quietEndAt(now, quiet) {
|
|
133
|
+
const offsetMs = quiet.utcOffsetMinutes * 60_000;
|
|
134
|
+
const minute = localMinute(now, quiet.utcOffsetMinutes);
|
|
135
|
+
const minuteStart = Math.floor((now + offsetMs) / 60_000) * 60_000 - offsetMs;
|
|
136
|
+
if (quiet.startMinute < quiet.endMinute)
|
|
137
|
+
return minuteStart + (quiet.endMinute - minute) * 60_000;
|
|
138
|
+
if (minute >= quiet.startMinute)
|
|
139
|
+
return minuteStart + (1440 - minute + quiet.endMinute) * 60_000;
|
|
140
|
+
return minuteStart + (quiet.endMinute - minute) * 60_000;
|
|
141
|
+
}
|
|
142
|
+
function quietUntil(now, quiet) {
|
|
143
|
+
if (quiet === undefined || !isQuiet(now, quiet))
|
|
144
|
+
return undefined;
|
|
145
|
+
return quietEndAt(now, quiet);
|
|
146
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Reset: start the team over. The user's API keys, DSH Sessions and the team's
|
|
2
|
+
// workspace stay; the Bots, group chats, memory, learning, schedules, IM bindings and
|
|
3
|
+
// indexes go, and the first Main Bot is created again. Everything removed is copied to
|
|
4
|
+
// a backup folder first, so a reset can be undone by hand.
|
|
5
|
+
import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
/** The plugin data a reset replaces, besides `state.json`. */
|
|
8
|
+
const DATA = ["memory", "learning", "im", "chat-index.sqlite", "inflight.json", "scheduler-state.json"];
|
|
9
|
+
const stamp = () => new Date().toISOString().replace(/[:.]/g, "-");
|
|
10
|
+
const busy = (rt) => (rt.live?.size ?? 0) > 0 ||
|
|
11
|
+
(rt.roomProgress?.size ?? 0) > 0;
|
|
12
|
+
export function install(rt) {
|
|
13
|
+
const fail = (message, code) => Object.assign(new Error(message), { code });
|
|
14
|
+
async function resetTeam() {
|
|
15
|
+
const readOnly = rt.readOnly?.();
|
|
16
|
+
if (readOnly !== undefined)
|
|
17
|
+
throw fail(readOnly, "bot/read-only");
|
|
18
|
+
if (busy(rt))
|
|
19
|
+
throw fail("A turn is still running. Stop it, or wait for it to finish, and reset again.", "bot/busy");
|
|
20
|
+
const home = rt.home;
|
|
21
|
+
const name = `backups/reset-${stamp()}`;
|
|
22
|
+
const path = join(home, ...name.split("/"));
|
|
23
|
+
mkdirSync(path, { recursive: true });
|
|
24
|
+
const moved = [];
|
|
25
|
+
const take = (entry) => {
|
|
26
|
+
const source = join(home, entry);
|
|
27
|
+
if (!existsSync(source))
|
|
28
|
+
return;
|
|
29
|
+
cpSync(source, join(path, entry), { recursive: true, verbatimSymlinks: true });
|
|
30
|
+
moved.push(entry);
|
|
31
|
+
};
|
|
32
|
+
for (const entry of ["state.json", ...DATA])
|
|
33
|
+
take(entry);
|
|
34
|
+
// The team is cleared in one save, then the same bootstrap that creates the first
|
|
35
|
+
// Main Bot on a fresh install runs again.
|
|
36
|
+
await rt.clearTeam();
|
|
37
|
+
for (const entry of DATA)
|
|
38
|
+
rmSync(join(home, entry), { recursive: true, force: true });
|
|
39
|
+
await rt.bootstrap();
|
|
40
|
+
return { backup: name, path };
|
|
41
|
+
}
|
|
42
|
+
Object.assign(rt, { resetTeam });
|
|
43
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
const MAX_TITLE = 120;
|
|
2
|
+
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
3
|
+
const invalid = (message) => Object.assign(new Error(message), { code: "bot/invalid" });
|
|
4
|
+
/** What a group sees of a due reminder. */
|
|
5
|
+
export function reminderText(text) {
|
|
6
|
+
const prompts = [];
|
|
7
|
+
const one = /^reminder_prompt_json: (.*)$/m.exec(text);
|
|
8
|
+
const batch = /^reminders_json: (.*)$/m.exec(text);
|
|
9
|
+
try {
|
|
10
|
+
if (one)
|
|
11
|
+
prompts.push(JSON.parse(one[1]));
|
|
12
|
+
if (batch)
|
|
13
|
+
for (const entry of JSON.parse(batch[1]))
|
|
14
|
+
prompts.push(entry.reminder_prompt);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// A framing this module cannot read goes to the group as it came.
|
|
18
|
+
return text;
|
|
19
|
+
}
|
|
20
|
+
const lines = prompts.filter((prompt) => typeof prompt === "string" && prompt.trim() !== "");
|
|
21
|
+
return lines.length === 0 ? text : lines.map((prompt) => `[Scheduled task] ${prompt}`).join("\n");
|
|
22
|
+
}
|
|
23
|
+
// The create request that gives a stored record its timing again, for a move.
|
|
24
|
+
function requestOf(record) {
|
|
25
|
+
const base = { title: record.title, prompt: record.prompt };
|
|
26
|
+
if (record.kind === "after" || record.kind === "at")
|
|
27
|
+
return { ...base, at: record.scheduledAt };
|
|
28
|
+
if (record.kind === "every")
|
|
29
|
+
return { ...base, every_seconds: record.everySeconds };
|
|
30
|
+
if (record.kind === "daily")
|
|
31
|
+
return { ...base, daily: { time: record.time, time_zone: record.timeZone } };
|
|
32
|
+
if (record.kind === "weekly")
|
|
33
|
+
return { ...base, weekly: { time: record.time, time_zone: record.timeZone, weekdays: record.weekdays } };
|
|
34
|
+
if (record.kind === "cron")
|
|
35
|
+
return { ...base, cron: { expression: record.expression, time_zone: record.timeZone } };
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
// DSH 0.2.2 keeps tasks Host-wide, each with a delivery target, and changes them through
|
|
39
|
+
// edit(); DSH 0.2.1 keeps them by Session. Both are served.
|
|
40
|
+
const hostWide = (service) => typeof service.edit === "function";
|
|
41
|
+
// The existing Session a task delivers to; a task that opens new Sessions has none.
|
|
42
|
+
const sessionOf = (entry) => entry.target === undefined ? entry.sessionId : entry.target.kind === "session" ? entry.target.sessionId : undefined;
|
|
43
|
+
const TIMING_KINDS = { at: "at", every_seconds: "every", daily: "daily", weekly: "weekly" };
|
|
44
|
+
const OWN_TASK_TOOLS = ["schedule_edit", "schedule_view"];
|
|
45
|
+
// DSH 0.2.2's list page: 100 by default, at most 500.
|
|
46
|
+
const LIST_PAGE = 100;
|
|
47
|
+
const LIST_READ_LIMIT = 500;
|
|
48
|
+
const OTHER_TASK_REFUSAL = "This task belongs to another chat. A Bot reads and changes only the tasks of its own chat.";
|
|
49
|
+
const sameOwner = (a, b) => a !== undefined && b !== undefined && a.botId === b.botId && a.roomId === b.roomId;
|
|
50
|
+
const timingOf = (selector) => {
|
|
51
|
+
const [key] = Object.keys(selector);
|
|
52
|
+
return { kind: TIMING_KINDS[key], [key]: selector[key] };
|
|
53
|
+
};
|
|
54
|
+
// The timing selector the settings form asks for, as the schedule service's create request.
|
|
55
|
+
function selectorOf(when) {
|
|
56
|
+
const zone = typeof when?.timeZone === "string" && when.timeZone !== "" ? when.timeZone : "UTC";
|
|
57
|
+
switch (when?.kind) {
|
|
58
|
+
case "at": {
|
|
59
|
+
const at = new Date(String(when.at ?? ""));
|
|
60
|
+
if (Number.isNaN(at.getTime()))
|
|
61
|
+
throw invalid("Pick a date and time");
|
|
62
|
+
if (at.getTime() <= Date.now())
|
|
63
|
+
throw invalid("Pick a time in the future");
|
|
64
|
+
return { at: at.toISOString() };
|
|
65
|
+
}
|
|
66
|
+
case "daily":
|
|
67
|
+
if (!TIME.test(String(when.time)))
|
|
68
|
+
throw invalid("Pick a time of day");
|
|
69
|
+
return { daily: { time: `${when.time}:00`, time_zone: zone } };
|
|
70
|
+
case "weekly": {
|
|
71
|
+
if (!TIME.test(String(when.time)))
|
|
72
|
+
throw invalid("Pick a time of day");
|
|
73
|
+
const days = (Array.isArray(when.weekdays) ? when.weekdays : []).map((day) => Number(day));
|
|
74
|
+
const weekdays = [...new Set(days)]
|
|
75
|
+
.filter((day) => Number.isInteger(day) && day >= 1 && day <= 7)
|
|
76
|
+
.sort((a, b) => a - b);
|
|
77
|
+
if (weekdays.length === 0)
|
|
78
|
+
throw invalid("Pick at least one day");
|
|
79
|
+
return { weekly: { time: `${when.time}:00`, time_zone: zone, weekdays } };
|
|
80
|
+
}
|
|
81
|
+
case "every": {
|
|
82
|
+
const minutes = Number(when.minutes);
|
|
83
|
+
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 7 * 24 * 60)
|
|
84
|
+
throw invalid("Repeat every 1 minute to 7 days");
|
|
85
|
+
return { every_seconds: minutes * 60 };
|
|
86
|
+
}
|
|
87
|
+
default:
|
|
88
|
+
throw invalid("Pick when it runs");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
export function install(rt) {
|
|
92
|
+
const { ctx } = rt;
|
|
93
|
+
let service = null;
|
|
94
|
+
const attach = (sub) => {
|
|
95
|
+
const own = sub.schedule;
|
|
96
|
+
service = own;
|
|
97
|
+
sub.effect(() => () => {
|
|
98
|
+
if (service === own)
|
|
99
|
+
service = null;
|
|
100
|
+
}, "ocean-crew: schedule service");
|
|
101
|
+
};
|
|
102
|
+
if (typeof ctx.inject === "function")
|
|
103
|
+
ctx.inject(["schedule"], attach);
|
|
104
|
+
else if (ctx.get?.("schedule") !== undefined)
|
|
105
|
+
attach({
|
|
106
|
+
schedule: ctx.get("schedule"),
|
|
107
|
+
effect: (execute, label) => ctx.effect(execute, label),
|
|
108
|
+
});
|
|
109
|
+
// The Bot (and group chat) a task's Session speaks for, the group chat for a group's
|
|
110
|
+
// own Session, or nothing for a Session outside the team.
|
|
111
|
+
const ownerOf = (sessionId) => {
|
|
112
|
+
if (sessionId === undefined)
|
|
113
|
+
return undefined;
|
|
114
|
+
const chat = rt.chatOwners.get(sessionId);
|
|
115
|
+
if (chat !== undefined)
|
|
116
|
+
return { botId: chat };
|
|
117
|
+
const room = rt.roomOf(sessionId);
|
|
118
|
+
if (room !== undefined)
|
|
119
|
+
return { roomId: room.id };
|
|
120
|
+
return rt.groupOwners.get(sessionId) ?? rt.pastOwners.get(sessionId);
|
|
121
|
+
};
|
|
122
|
+
const known = (owner) => owner !== undefined &&
|
|
123
|
+
(owner.botId === undefined ? rt.roomOf(owner.roomId) !== undefined : rt.botOf(owner.botId) !== undefined);
|
|
124
|
+
async function schedulesView() {
|
|
125
|
+
if (service === null)
|
|
126
|
+
return { available: false, tasks: [] };
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
const tasks = [];
|
|
129
|
+
for (const entry of await service.catalog()) {
|
|
130
|
+
const sessionId = sessionOf(entry);
|
|
131
|
+
const owner = sessionId === undefined ? undefined : ownerOf(sessionId);
|
|
132
|
+
if (!known(owner))
|
|
133
|
+
continue;
|
|
134
|
+
// The state DSH derives for its own view: a task past its next firing reads
|
|
135
|
+
// overdue; a paused one stays paused; any other is finished. catalog() carries
|
|
136
|
+
// the status but not this state, so it is derived the same way here.
|
|
137
|
+
const state = entry.status === "active"
|
|
138
|
+
? now >= Date.parse(entry.scheduledAt)
|
|
139
|
+
? "overdue"
|
|
140
|
+
: "scheduled"
|
|
141
|
+
: entry.status === "paused"
|
|
142
|
+
? "paused"
|
|
143
|
+
: "finished";
|
|
144
|
+
tasks.push({ ...entry, sessionId, ...owner, state });
|
|
145
|
+
}
|
|
146
|
+
return { available: true, tasks };
|
|
147
|
+
}
|
|
148
|
+
const endpoints = {
|
|
149
|
+
schedules: () => schedulesView(),
|
|
150
|
+
async "schedule-create"(body) {
|
|
151
|
+
if (service === null)
|
|
152
|
+
throw invalid("Automation tasks are off in DSH");
|
|
153
|
+
const bot = rt.botOf(body.target);
|
|
154
|
+
const room = rt.roomOf(body.target);
|
|
155
|
+
if (bot === undefined && room === undefined)
|
|
156
|
+
throw invalid("No such Bot or group chat");
|
|
157
|
+
const title = String(body.title ?? "").trim();
|
|
158
|
+
const prompt = String(body.prompt ?? "").trim();
|
|
159
|
+
if (title === "")
|
|
160
|
+
throw invalid("Give the task a name");
|
|
161
|
+
if (title.length > MAX_TITLE)
|
|
162
|
+
throw invalid(`Keep the name under ${MAX_TITLE} characters`);
|
|
163
|
+
if (prompt === "")
|
|
164
|
+
throw invalid("Say what the Bot should do");
|
|
165
|
+
const sessionId = bot ? rt.chatOf(bot.id) : rt.sessionOfRoom(room);
|
|
166
|
+
const selector = selectorOf(body.when);
|
|
167
|
+
if (hostWide(service))
|
|
168
|
+
await service.create({ title, prompt, timing: timingOf(selector), target: { kind: "session", sessionId } });
|
|
169
|
+
else
|
|
170
|
+
await service.create(sessionId, { title, prompt, ...selector });
|
|
171
|
+
return schedulesView();
|
|
172
|
+
},
|
|
173
|
+
async "schedule-delete"(body) {
|
|
174
|
+
if (service === null)
|
|
175
|
+
throw invalid("Automation tasks are off in DSH");
|
|
176
|
+
if (ownerOf(body.sessionId) === undefined)
|
|
177
|
+
throw invalid("No such task");
|
|
178
|
+
if (hostWide(service)) {
|
|
179
|
+
// Ids are Host-wide here, so the task must still deliver to the team Session named.
|
|
180
|
+
const entry = (await service.catalog()).find((task) => task.id === body.id);
|
|
181
|
+
if (entry === undefined || sessionOf(entry) !== body.sessionId)
|
|
182
|
+
throw invalid("No such task");
|
|
183
|
+
await service.edit?.({ id: body.id, action: "delete" });
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
await service.delete?.({ sessionId: body.sessionId, id: body.id });
|
|
187
|
+
}
|
|
188
|
+
return schedulesView();
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
// the fresh Session before the old one goes, so a failure leaves it where it was.
|
|
192
|
+
async function moveSchedules(fromId, toId) {
|
|
193
|
+
if (service === null)
|
|
194
|
+
return;
|
|
195
|
+
// A Host-wide task changes its target in place and keeps its next firing; a paused
|
|
196
|
+
// one moves too, so it resumes in the Bot's current part.
|
|
197
|
+
if (hostWide(service)) {
|
|
198
|
+
for (const entry of await service.catalog()) {
|
|
199
|
+
if (entry.status === "ended" || sessionOf(entry) !== fromId)
|
|
200
|
+
continue;
|
|
201
|
+
await service.edit?.({
|
|
202
|
+
id: entry.id,
|
|
203
|
+
action: "update",
|
|
204
|
+
patch: { target: { kind: "session", sessionId: toId } },
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const records = (await service.list?.({ sessionId: fromId })) ?? [];
|
|
210
|
+
for (const record of records) {
|
|
211
|
+
const request = requestOf(record);
|
|
212
|
+
if (request === null || (request.at !== undefined && Date.parse(String(request.at)) <= Date.now()))
|
|
213
|
+
continue;
|
|
214
|
+
// A failed read or copy must prevent stopActivity from deleting an unmoved task.
|
|
215
|
+
// Equal requests can be separate tasks; copy each source record.
|
|
216
|
+
await service.create(toId, request);
|
|
217
|
+
try {
|
|
218
|
+
await service.delete?.({ sessionId: fromId, id: record.id });
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
// The copy is safe;
|
|
222
|
+
rt.warn("ocean-crew: earlier copy of task %s not removed: %s", record.title, error?.message ?? error);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// DSH 0.2.2's task ids are Host-wide, so a Bot's schedule tools reach only the tasks
|
|
227
|
+
// that deliver to its own chat, or to the same group place, in any of its parts.
|
|
228
|
+
ctx.on("tools/pre-execute", async (exec, next) => {
|
|
229
|
+
const decision = await next();
|
|
230
|
+
if (decision.kind !== "allow" || !OWN_TASK_TOOLS.includes(exec.name) || service === null || !hostWide(service))
|
|
231
|
+
return decision;
|
|
232
|
+
await rt.load();
|
|
233
|
+
const caller = exec.agent?.id;
|
|
234
|
+
if (!rt.isBotSession(caller))
|
|
235
|
+
return decision;
|
|
236
|
+
const entry = (await service.catalog()).find((task) => task.id === exec.arguments?.id);
|
|
237
|
+
// An unknown id gets DSH's own not-found result.
|
|
238
|
+
if (entry === undefined)
|
|
239
|
+
return decision;
|
|
240
|
+
const target = sessionOf(entry);
|
|
241
|
+
if (target !== undefined && sameOwner(ownerOf(caller), ownerOf(target)))
|
|
242
|
+
return decision;
|
|
243
|
+
return { kind: "deny", reason: OTHER_TASK_REFUSAL };
|
|
244
|
+
});
|
|
245
|
+
// schedule_list pages over every Host task and cannot filter by Session, and only the
|
|
246
|
+
// tool formats its items. So the tool is asked for the Host range that holds the
|
|
247
|
+
// caller's page (catalog() keeps list()'s order), and the other chats' tasks in that
|
|
248
|
+
// range are dropped. A page whose tasks span more than one Host page comes back short;
|
|
249
|
+
// total still counts all of the caller's tasks, so the next offset goes on.
|
|
250
|
+
ctx.on("tools/execute", async function listOwnSchedules(exec, next) {
|
|
251
|
+
if (exec.name !== "schedule_list" || service === null || !hostWide(service))
|
|
252
|
+
return next();
|
|
253
|
+
await rt.load();
|
|
254
|
+
const activeService = service;
|
|
255
|
+
const own = rt.isBotSession(exec.agent?.id) ? ownerOf(exec.agent.id) : undefined;
|
|
256
|
+
if (own === undefined)
|
|
257
|
+
return next();
|
|
258
|
+
const asked = exec.arguments ?? {};
|
|
259
|
+
const limit = asked.limit ?? LIST_PAGE;
|
|
260
|
+
const offset = asked.offset ?? 0;
|
|
261
|
+
const mine = (entry) => {
|
|
262
|
+
const target = sessionOf(entry);
|
|
263
|
+
return target !== undefined && sameOwner(own, ownerOf(target));
|
|
264
|
+
};
|
|
265
|
+
// An invalid page gets DSH's own input error; a page it accepts anyway is still narrowed.
|
|
266
|
+
if (!Number.isSafeInteger(limit) ||
|
|
267
|
+
limit < 1 ||
|
|
268
|
+
limit > LIST_READ_LIMIT ||
|
|
269
|
+
!Number.isSafeInteger(offset) ||
|
|
270
|
+
offset < 0) {
|
|
271
|
+
const result = await next();
|
|
272
|
+
if (result.isError || !Array.isArray(result.value?.items))
|
|
273
|
+
return result;
|
|
274
|
+
const items = result.value.items.filter(mine);
|
|
275
|
+
const total = (await activeService.catalog()).filter((entry) => mine(entry) && (asked.active === undefined || (entry.status === "active") === asked.active)).length;
|
|
276
|
+
return { ...result, value: { ...result.value, items, shown: items.length, total } };
|
|
277
|
+
}
|
|
278
|
+
const pool = (await activeService.catalog()).filter((entry) => asked.active === undefined || (entry.status === "active") === asked.active);
|
|
279
|
+
const positions = pool.flatMap((entry, at) => (mine(entry) ? [at] : []));
|
|
280
|
+
const page = positions.slice(offset, offset + limit);
|
|
281
|
+
const from = page[0] ?? pool.length;
|
|
282
|
+
exec.arguments = {
|
|
283
|
+
...asked,
|
|
284
|
+
offset: from,
|
|
285
|
+
limit: page.length === 0 ? 1 : Math.min(LIST_READ_LIMIT, page.at(-1) - from + 1),
|
|
286
|
+
};
|
|
287
|
+
let result;
|
|
288
|
+
try {
|
|
289
|
+
result = await next();
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
exec.arguments = asked;
|
|
293
|
+
}
|
|
294
|
+
if (result.isError || !Array.isArray(result.value?.items))
|
|
295
|
+
return result;
|
|
296
|
+
const items = result.value.items.filter(mine).slice(0, limit);
|
|
297
|
+
return {
|
|
298
|
+
...result,
|
|
299
|
+
value: { ...result.value, items, shown: items.length, total: positions.length, limit, offset },
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
rt.scheduleEndpoint = (endpoint, body) => {
|
|
303
|
+
const run = endpoints[endpoint];
|
|
304
|
+
if (run === undefined)
|
|
305
|
+
throw invalid(`Unknown schedule endpoint ${endpoint}`);
|
|
306
|
+
return run(body ?? {});
|
|
307
|
+
};
|
|
308
|
+
rt.moveSchedules = moveSchedules;
|
|
309
|
+
}
|