@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4-beta.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/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +148 -1245
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +7 -1
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +10 -10
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
- package/dist/{runtime/app-home.js → app/home.js} +4 -75
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +10 -10
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +3 -3
- package/dist/commands/catalog.js +3 -3
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
- package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
- package/dist/{settings.js → config/settings.js} +7 -10
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +6 -2
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +6 -109
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/main.js +2 -2
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +2 -1
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +37 -755
- package/dist/runtime/durable-dispatch.d.ts +17 -4
- package/dist/runtime/durable-dispatch.js +60 -18
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +2 -2
- package/dist/runtime/task-driver.js +3 -3
- package/dist/runtime/task-migration.js +2 -2
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +1 -1
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.js +4 -0
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/host-process.js +1 -1
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +1 -1
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +2 -2
- package/dist/subagents/external/settlement.d.ts +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +7 -243
- package/dist/subagents/runs.js +8 -291
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/tasks/board.d.ts +2 -2
- package/dist/tasks/board.js +2 -2
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/{log.js → loop-log.js} +1 -1
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +2 -2
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
- package/dist/tools/{tool-details.js → contract/details.js} +4 -4
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +3 -3
- package/dist/tools/index.js +7 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.js +4 -3
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +3 -3
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +1 -1
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/usage/ledger.js +4 -0
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1470
- package/dist/subagents/tool.d.ts +0 -213
- package/dist/subagents/tool.js +0 -1282
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
- /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → app}/proxy.js +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/delivery.js +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/events/{event-validation.js → validation.js} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import * as log from "../log.js";
|
|
2
|
+
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
3
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
5
|
+
import { parseInboundMessage } from "./inbound-media.js";
|
|
6
|
+
export class InboundMessages {
|
|
7
|
+
constructor(deps) {
|
|
8
|
+
this.deps = deps;
|
|
9
|
+
// Deduplication cache (Set for O(1) lookup, order array for FIFO eviction)
|
|
10
|
+
this.processedIds = new Set();
|
|
11
|
+
this.processedIdsOrder = [];
|
|
12
|
+
// Serializes "resolve inbound image attachments → build event → route" per channel (spec 049
|
|
13
|
+
// D3): a message needing a download must not be overtaken, in delivery order, by a later
|
|
14
|
+
// download-free message on the same channel. `pendingInboundIngestCount` lets the bot's
|
|
15
|
+
// `allChannelQueuesIdle()` see this in-flight network work, which `ChannelQueue.isIdle()`
|
|
16
|
+
// alone cannot — the event has not been built yet, let alone enqueued.
|
|
17
|
+
this.inboundIngestQueue = createSerialQueue();
|
|
18
|
+
this.pendingInboundIngestCount = 0;
|
|
19
|
+
}
|
|
20
|
+
/** True while an inbound message is still being ingested (downloading, not yet enqueued). */
|
|
21
|
+
hasPendingIngest() {
|
|
22
|
+
return this.pendingInboundIngestCount > 0;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Mark an ID as processed. Returns true if this is a new ID, false if already seen.
|
|
26
|
+
* Maintains a FIFO buffer of at most 200 entries.
|
|
27
|
+
*/
|
|
28
|
+
markProcessed(id) {
|
|
29
|
+
if (this.processedIds.has(id))
|
|
30
|
+
return false;
|
|
31
|
+
this.processedIds.add(id);
|
|
32
|
+
this.processedIdsOrder.push(id);
|
|
33
|
+
while (this.processedIdsOrder.length > 200) {
|
|
34
|
+
this.processedIds.delete(this.processedIdsOrder.shift());
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
handleRawMessage(msg) {
|
|
39
|
+
// 1. Immediate ACK
|
|
40
|
+
if (msg.headers?.messageId) {
|
|
41
|
+
this.deps.ack(msg.headers.messageId);
|
|
42
|
+
}
|
|
43
|
+
// 2. Protocol deduplication
|
|
44
|
+
const messageId = msg.headers?.messageId;
|
|
45
|
+
if (messageId && !this.markProcessed(messageId)) {
|
|
46
|
+
return { status: "SUCCESS", message: "OK" };
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const parsedData = typeof msg.data === "string" ? JSON.parse(msg.data) : msg.data;
|
|
50
|
+
const data = isRecord(parsedData) ? parsedData : {};
|
|
51
|
+
// 3. Business logic deduplication
|
|
52
|
+
const msgId = data.msgId;
|
|
53
|
+
if (msgId && !this.markProcessed(msgId)) {
|
|
54
|
+
return { status: "SUCCESS", message: "OK" };
|
|
55
|
+
}
|
|
56
|
+
// Fire-and-forget processing
|
|
57
|
+
this.onStreamMessage(data).catch((err) => {
|
|
58
|
+
log.logWarn("dingtalk.handler.failed", "Message handler failed", { reason: errorMessage(err) });
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
log.logWarn("dingtalk.message.parse_failed", "Message parse failed", { reason: errorMessage(err) });
|
|
63
|
+
}
|
|
64
|
+
return { status: "SUCCESS", message: "OK" };
|
|
65
|
+
}
|
|
66
|
+
async onStreamMessage(data) {
|
|
67
|
+
const { config, handler } = this.deps;
|
|
68
|
+
if (this.deps.isStopped()) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const parsed = parseInboundMessage(data);
|
|
72
|
+
const senderId = data.senderStaffId || data.senderId || "";
|
|
73
|
+
const senderName = data.senderNick || "Unknown";
|
|
74
|
+
const conversationId = data.conversationId || "";
|
|
75
|
+
const conversationType = data.conversationType || "1";
|
|
76
|
+
if (!parsed.text && parsed.downloadCodes.length === 0) {
|
|
77
|
+
const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
|
|
78
|
+
log.logWarn("dingtalk.message.empty", "Empty message ignored", { fields: { msgtype } });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (config.allowFrom && config.allowFrom.length > 0) {
|
|
82
|
+
if (!config.allowFrom.includes(senderId)) {
|
|
83
|
+
log.logWarn("dingtalk.message.unauthorized", "Message from unauthorized user ignored", {
|
|
84
|
+
fields: { senderName, senderId },
|
|
85
|
+
});
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// Determine channel ID
|
|
90
|
+
const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
|
|
91
|
+
// Parsing above is free; resolving image attachments below is a real network round-trip.
|
|
92
|
+
// Serialize the whole "resolve attachments → build event → route" unit per channel (spec
|
|
93
|
+
// 049 D3): without this, a message needing a download can be overtaken, in delivery order,
|
|
94
|
+
// by a later download-free message on the same channel — nothing upstream of
|
|
95
|
+
// `enqueueStreamMessage` otherwise waits on anything asynchronous.
|
|
96
|
+
this.pendingInboundIngestCount++;
|
|
97
|
+
try {
|
|
98
|
+
await this.inboundIngestQueue.run(channelId, async () => {
|
|
99
|
+
const { text: content, images } = await this.deps.resolveInboundAttachments(channelId, parsed);
|
|
100
|
+
log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
|
|
101
|
+
ctx: { channelId, userName: senderName },
|
|
102
|
+
fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
|
|
103
|
+
});
|
|
104
|
+
// A group carries its title on every message; a DM has none, so the peer's nickname
|
|
105
|
+
// is the only human-readable handle that channel will ever have.
|
|
106
|
+
const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
|
|
107
|
+
const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
|
|
108
|
+
// Cache conversation metadata for card creation
|
|
109
|
+
this.deps.conversations.set(channelId, {
|
|
110
|
+
conversationId,
|
|
111
|
+
conversationType,
|
|
112
|
+
senderId,
|
|
113
|
+
});
|
|
114
|
+
// The one place a real person's message is seen before command/busy routing splits
|
|
115
|
+
// the path, so the channel index counts every human message and no synthetic wake.
|
|
116
|
+
handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
|
|
117
|
+
// Build event
|
|
118
|
+
const event = {
|
|
119
|
+
type: conversationType === "2" ? "group" : "dm",
|
|
120
|
+
channelId,
|
|
121
|
+
ts: Date.now().toString(),
|
|
122
|
+
user: senderId,
|
|
123
|
+
userName: senderName,
|
|
124
|
+
text: content,
|
|
125
|
+
conversationId,
|
|
126
|
+
conversationType,
|
|
127
|
+
...(channelName ? { channelName } : {}),
|
|
128
|
+
...(images.length > 0 ? { images } : {}),
|
|
129
|
+
};
|
|
130
|
+
await this.deps.routeInboundEvent(event);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
this.pendingInboundIngestCount--;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { MediaSendResult, OutboundMedia } from "../channel/channel-context.js";
|
|
2
|
+
import type { InboundImage } from "../channel/channel-event.js";
|
|
3
|
+
import { type ConversationMeta } from "./api.js";
|
|
4
|
+
import type { DingTalkConfig } from "./config.js";
|
|
5
|
+
import type { DingTalkHandler } from "./handler.js";
|
|
6
|
+
import { type ParsedInboundMessage } from "./inbound-media.js";
|
|
7
|
+
export interface DingTalkMediaDeps {
|
|
8
|
+
config: DingTalkConfig;
|
|
9
|
+
handler: DingTalkHandler;
|
|
10
|
+
getAccessToken: () => Promise<string | null>;
|
|
11
|
+
getConversationMeta: (channelId: string) => ConversationMeta | null;
|
|
12
|
+
sendRobotMessage: (meta: ConversationMeta, msgKey: string, msgParam: string) => Promise<boolean>;
|
|
13
|
+
/**
|
|
14
|
+
* The inbound file fetch used while resolving attachments. The bot supplies its own overridable
|
|
15
|
+
* `downloadMessageFile`, so the deterministic e2e harness can stub the network out.
|
|
16
|
+
*/
|
|
17
|
+
downloadMessageFile: (downloadCode: string) => Promise<{
|
|
18
|
+
data: Buffer;
|
|
19
|
+
} | null>;
|
|
20
|
+
}
|
|
21
|
+
export declare class DingTalkMedia {
|
|
22
|
+
private deps;
|
|
23
|
+
constructor(deps: DingTalkMediaDeps);
|
|
24
|
+
/**
|
|
25
|
+
* Deliver a local file to a channel as a native attachment. Uploads the bytes
|
|
26
|
+
* to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
|
|
27
|
+
* `sampleFile` (downloadable file) robot message. `channelId` is supplied by
|
|
28
|
+
* the runtime (the tool is bound to its channel at build time), never by the
|
|
29
|
+
* model, so an agent cannot target a channel other than its own.
|
|
30
|
+
*/
|
|
31
|
+
sendMedia(channelId: string, media: OutboundMedia): Promise<MediaSendResult>;
|
|
32
|
+
/**
|
|
33
|
+
* Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
|
|
34
|
+
* failure. The upload endpoint lives on the legacy oapi host and answers 200
|
|
35
|
+
* with a non-zero `errcode` on failure, so the body is inspected explicitly.
|
|
36
|
+
*/
|
|
37
|
+
private uploadMedia;
|
|
38
|
+
/**
|
|
39
|
+
* Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
|
|
40
|
+
* message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
|
|
41
|
+
* actual bytes. Both hops reuse the shared access token — the same app access token works across
|
|
42
|
+
* DingTalk's hosts, as the comment on `DINGTALK_OAPI` explains for the outbound side.
|
|
43
|
+
*
|
|
44
|
+
* This runs from the inbound per-channel ingestion queue, never from inside a turn: a busy
|
|
45
|
+
* channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
|
|
46
|
+
* queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
|
|
47
|
+
* already expired.
|
|
48
|
+
*/
|
|
49
|
+
downloadMessageFile(downloadCode: string): Promise<{
|
|
50
|
+
data: Buffer;
|
|
51
|
+
} | null>;
|
|
52
|
+
/**
|
|
53
|
+
* Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
|
|
54
|
+
* with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
|
|
55
|
+
* D8): a download failure, an unrecognized format, an oversized file, or a message that
|
|
56
|
+
* simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
|
|
57
|
+
* image never drops the rest of the message — only that one marker changes.
|
|
58
|
+
*
|
|
59
|
+
* No-op (no network call at all) when the message carries no image credentials, so a plain
|
|
60
|
+
* text message never pays for this method's existence.
|
|
61
|
+
*/
|
|
62
|
+
resolveInboundAttachments(channelId: string, parsed: ParsedInboundMessage): Promise<{
|
|
63
|
+
text: string;
|
|
64
|
+
images: InboundImage[];
|
|
65
|
+
}>;
|
|
66
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media (image / file) for DingTalk: outbound delivery (`MediaSender` contract), and the two-step
|
|
3
|
+
* inbound download plus the per-message attachment resolution built on it (spec 049).
|
|
4
|
+
*/
|
|
5
|
+
import axios from "axios";
|
|
6
|
+
import * as log from "../log.js";
|
|
7
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
8
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
9
|
+
import { formatSize } from "../tools/truncate.js";
|
|
10
|
+
import { DINGTALK_API, DINGTALK_OAPI, http } from "./api.js";
|
|
11
|
+
import { MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE, MEDIA_DOWNLOAD_TIMEOUT_MS, sniffImageMimeType, } from "./inbound-media.js";
|
|
12
|
+
// DingTalk caps robot image messages at 1MB and file messages at 20MB. We reject
|
|
13
|
+
// oversized files before spending an upload round-trip on a request the API rejects.
|
|
14
|
+
const MAX_IMAGE_BYTES = 1024 * 1024;
|
|
15
|
+
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
16
|
+
// Uploads can move up to 20MB; the 15s default HTTP timeout is too tight for that.
|
|
17
|
+
const MEDIA_UPLOAD_TIMEOUT_MS = 60_000;
|
|
18
|
+
// File extensions the `sampleFile` message type accepts (per DingTalk docs).
|
|
19
|
+
const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx", "ppt", "pptx", "csv", "txt"]);
|
|
20
|
+
/** Lowercased extension without the dot ("Report.PDF" → "pdf"); "" when none. */
|
|
21
|
+
function extractFileExtension(fileName) {
|
|
22
|
+
const dot = fileName.lastIndexOf(".");
|
|
23
|
+
if (dot < 0 || dot === fileName.length - 1)
|
|
24
|
+
return "";
|
|
25
|
+
return fileName.slice(dot + 1).toLowerCase();
|
|
26
|
+
}
|
|
27
|
+
export class DingTalkMedia {
|
|
28
|
+
constructor(deps) {
|
|
29
|
+
this.deps = deps;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Deliver a local file to a channel as a native attachment. Uploads the bytes
|
|
33
|
+
* to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
|
|
34
|
+
* `sampleFile` (downloadable file) robot message. `channelId` is supplied by
|
|
35
|
+
* the runtime (the tool is bound to its channel at build time), never by the
|
|
36
|
+
* model, so an agent cannot target a channel other than its own.
|
|
37
|
+
*/
|
|
38
|
+
async sendMedia(channelId, media) {
|
|
39
|
+
const isImage = media.kind === "image";
|
|
40
|
+
const limit = isImage ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;
|
|
41
|
+
if (media.data.length > limit) {
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
error: `File is ${(media.data.length / 1024 / 1024).toFixed(1)}MB, exceeds the ${limit / 1024 / 1024}MB DingTalk limit for ${media.kind} messages.`,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const fileType = extractFileExtension(media.fileName);
|
|
48
|
+
if (!isImage && !SUPPORTED_FILE_TYPES.has(fileType)) {
|
|
49
|
+
return {
|
|
50
|
+
ok: false,
|
|
51
|
+
error: `DingTalk file messages do not support the "${fileType || "(none)"}" type. Supported: ${[...SUPPORTED_FILE_TYPES].join(", ")}.`,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const meta = this.deps.getConversationMeta(channelId);
|
|
55
|
+
if (!meta) {
|
|
56
|
+
return { ok: false, error: "No conversation is known for this channel yet; cannot deliver a file." };
|
|
57
|
+
}
|
|
58
|
+
const mediaId = await this.uploadMedia(isImage ? "image" : "file", media.data, media.fileName);
|
|
59
|
+
if (!mediaId) {
|
|
60
|
+
return { ok: false, error: "Failed to upload the file to DingTalk (see server logs)." };
|
|
61
|
+
}
|
|
62
|
+
const { msgKey, msgParam } = isImage
|
|
63
|
+
? { msgKey: "sampleImageMsg", msgParam: JSON.stringify({ photoURL: mediaId }) }
|
|
64
|
+
: {
|
|
65
|
+
msgKey: "sampleFile",
|
|
66
|
+
msgParam: JSON.stringify({ mediaId, fileName: media.fileName, fileType }),
|
|
67
|
+
};
|
|
68
|
+
const sent = await this.deps.sendRobotMessage(meta, msgKey, msgParam);
|
|
69
|
+
return sent ? { ok: true } : { ok: false, error: "DingTalk rejected the file message (see server logs)." };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
|
|
73
|
+
* failure. The upload endpoint lives on the legacy oapi host and answers 200
|
|
74
|
+
* with a non-zero `errcode` on failure, so the body is inspected explicitly.
|
|
75
|
+
*/
|
|
76
|
+
async uploadMedia(type, data, fileName) {
|
|
77
|
+
const token = await this.deps.getAccessToken();
|
|
78
|
+
if (!token)
|
|
79
|
+
return null;
|
|
80
|
+
const form = new FormData();
|
|
81
|
+
form.append("media", new Blob([new Uint8Array(data)]), fileName);
|
|
82
|
+
try {
|
|
83
|
+
const resp = await http.post(`${DINGTALK_OAPI}/media/upload?access_token=${encodeURIComponent(token)}&type=${type}`, form,
|
|
84
|
+
// Override the 15s default: a multi-MB upload over a slow link can take
|
|
85
|
+
// longer, and unlike card streaming this call is not on the delivery loop.
|
|
86
|
+
{ timeout: MEDIA_UPLOAD_TIMEOUT_MS });
|
|
87
|
+
const body = isRecord(resp.data) ? resp.data : {};
|
|
88
|
+
if (body.errcode && body.errcode !== 0) {
|
|
89
|
+
log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
|
|
90
|
+
reason: String(body.errmsg ?? ""),
|
|
91
|
+
fields: { errcode: body.errcode },
|
|
92
|
+
});
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
const mediaId = typeof body.media_id === "string" ? body.media_id : null;
|
|
96
|
+
if (!mediaId) {
|
|
97
|
+
log.logWarn("dingtalk.media.upload_failed", "Media upload returned no media_id", {
|
|
98
|
+
reason: JSON.stringify(body),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return mediaId;
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
if (axios.isAxiosError(err) && err.response) {
|
|
105
|
+
log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
|
|
106
|
+
reason: JSON.stringify(err.response.data),
|
|
107
|
+
fields: { status: err.response.status },
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
log.logWarn("dingtalk.media.upload_failed", "Media upload failed", { reason: errorMessage(err) });
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
|
|
118
|
+
* message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
|
|
119
|
+
* actual bytes. Both hops reuse the shared access token — the same app access token works across
|
|
120
|
+
* DingTalk's hosts, as the comment on `DINGTALK_OAPI` explains for the outbound side.
|
|
121
|
+
*
|
|
122
|
+
* This runs from the inbound per-channel ingestion queue, never from inside a turn: a busy
|
|
123
|
+
* channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
|
|
124
|
+
* queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
|
|
125
|
+
* already expired.
|
|
126
|
+
*/
|
|
127
|
+
async downloadMessageFile(downloadCode) {
|
|
128
|
+
const token = await this.deps.getAccessToken();
|
|
129
|
+
if (!token)
|
|
130
|
+
return null;
|
|
131
|
+
const robotCode = this.deps.config.robotCode || this.deps.config.clientId;
|
|
132
|
+
try {
|
|
133
|
+
const downloadUrlResp = await http.post(`${DINGTALK_API}/v1.0/robot/messageFiles/download`, { robotCode, downloadCode }, { headers: { "x-acs-dingtalk-access-token": token } });
|
|
134
|
+
const downloadUrl = isRecord(downloadUrlResp.data) ? downloadUrlResp.data.downloadUrl : undefined;
|
|
135
|
+
if (typeof downloadUrl !== "string" || !downloadUrl) {
|
|
136
|
+
log.logWarn("dingtalk.file.download_failed", "Inbound file download returned no downloadUrl", {
|
|
137
|
+
reason: JSON.stringify(downloadUrlResp.data),
|
|
138
|
+
});
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
const fileResp = await http.get(downloadUrl, {
|
|
142
|
+
responseType: "arraybuffer",
|
|
143
|
+
// Reject an oversized body before it fully lands in memory rather than after.
|
|
144
|
+
maxContentLength: MAX_INBOUND_IMAGE_BYTES,
|
|
145
|
+
timeout: MEDIA_DOWNLOAD_TIMEOUT_MS,
|
|
146
|
+
});
|
|
147
|
+
return { data: Buffer.from(fileResp.data) };
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (axios.isAxiosError(err) && err.response) {
|
|
151
|
+
log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", {
|
|
152
|
+
reason: JSON.stringify(err.response.data),
|
|
153
|
+
fields: { status: err.response.status },
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", { reason: errorMessage(err) });
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
|
|
164
|
+
* with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
|
|
165
|
+
* D8): a download failure, an unrecognized format, an oversized file, or a message that
|
|
166
|
+
* simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
|
|
167
|
+
* image never drops the rest of the message — only that one marker changes.
|
|
168
|
+
*
|
|
169
|
+
* No-op (no network call at all) when the message carries no image credentials, so a plain
|
|
170
|
+
* text message never pays for this method's existence.
|
|
171
|
+
*/
|
|
172
|
+
async resolveInboundAttachments(channelId, parsed) {
|
|
173
|
+
if (parsed.downloadCodes.length === 0) {
|
|
174
|
+
return { text: parsed.text, images: [] };
|
|
175
|
+
}
|
|
176
|
+
let text = parsed.text;
|
|
177
|
+
const images = [];
|
|
178
|
+
const replaceMarker = (index, replacement) => {
|
|
179
|
+
text = text.replace(`[图片${index + 1}]`, replacement);
|
|
180
|
+
};
|
|
181
|
+
await Promise.all(parsed.downloadCodes.map(async (downloadCode, index) => {
|
|
182
|
+
const marker = index + 1;
|
|
183
|
+
if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
|
|
184
|
+
replaceMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const downloaded = await this.deps.downloadMessageFile(downloadCode);
|
|
188
|
+
if (!downloaded) {
|
|
189
|
+
replaceMarker(index, `[图片${marker}:接收失败]`);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
|
|
193
|
+
replaceMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const mimeType = sniffImageMimeType(downloaded.data);
|
|
197
|
+
const persisted = await this.deps.handler.persistInboundImage?.(channelId, {
|
|
198
|
+
data: downloaded.data,
|
|
199
|
+
mimeType,
|
|
200
|
+
});
|
|
201
|
+
if (!persisted) {
|
|
202
|
+
replaceMarker(index, `[图片${marker}:保存失败]`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (!mimeType) {
|
|
206
|
+
// Persisted for the record, but never handed to a model — see the handler
|
|
207
|
+
// contract's doc comment on `persistInboundImage`.
|
|
208
|
+
replaceMarker(index, `[图片${marker}:格式不支持,已保存]`);
|
|
209
|
+
}
|
|
210
|
+
images[index] = persisted;
|
|
211
|
+
}));
|
|
212
|
+
return { text, images: images.filter((image) => image !== undefined) };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/events`: list, show, delete and history of scheduled events, confined to `workspace/events/` and
|
|
3
|
+
* the event history.
|
|
4
|
+
*/
|
|
1
5
|
import { existsSync } from "fs";
|
|
2
6
|
import { readdir, readFile, unlink } from "fs/promises";
|
|
3
7
|
import { join } from "path";
|
|
@@ -5,8 +9,8 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
|
|
|
5
9
|
import { capReply } from "../commands/reply-limits.js";
|
|
6
10
|
import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
|
|
7
11
|
import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
12
|
+
import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
|
|
13
|
+
import { EventDefinitionError, validateScheduledEvent } from "./validation.js";
|
|
10
14
|
const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
11
15
|
const DEFAULT_HISTORY_LIMIT = 20;
|
|
12
16
|
const TEXT_PREVIEW_MAX_CHARS = 100;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ScheduledEvent } from "./types.js";
|
|
2
|
+
/** The one-line description of what an event delivers, for history records and listings. */
|
|
3
|
+
export declare function describeEventPayload(event: Pick<ScheduledEvent, "text" | "task">): string;
|
|
4
|
+
export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
|
|
5
|
+
/**
|
|
6
|
+
* Stable, provenance-derived dispatch id (spec 031, D1).
|
|
7
|
+
*
|
|
8
|
+
* The identity of a wake is its *occurrence*, never the moment it happened to be executed.
|
|
9
|
+
* A one-shot keyed on its own `at` therefore lands on the same durable record whether it
|
|
10
|
+
* arrives via the outbox retry or via the post-restart file recovery path, so the two
|
|
11
|
+
* independent retry systems can no longer deliver the same occurrence twice. A live periodic
|
|
12
|
+
* occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
|
|
13
|
+
* while the next callback produces a genuinely new record.
|
|
14
|
+
*/
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parsing a scheduled-event definition file into a `ScheduledEvent`: the payload (text or task
|
|
3
|
+
* template), the optional pre-action gate and the schedule. Pure — the watcher owns reading files.
|
|
4
|
+
*/
|
|
5
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
6
|
+
import { isPlainObject } from "../shared/type-guards.js";
|
|
7
|
+
import { validateTaskContractInput } from "../tasks/contract-input.js";
|
|
8
|
+
import { EventDefinitionError } from "./validation.js";
|
|
9
|
+
/** The one-line description of what an event delivers, for history records and listings. */
|
|
10
|
+
export function describeEventPayload(event) {
|
|
11
|
+
return event.task ? `任务模板:${event.task.title}` : (event.text ?? "");
|
|
12
|
+
}
|
|
13
|
+
function readRequiredString(data, field, filename) {
|
|
14
|
+
const value = data[field];
|
|
15
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
16
|
+
throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
/** `text` xor `task`: a chat message, or a template for a task instance (spec 052, D2). */
|
|
21
|
+
function parsePayload(data, filename) {
|
|
22
|
+
const hasText = typeof data.text === "string" && data.text.trim().length > 0;
|
|
23
|
+
const hasTask = data.task !== undefined;
|
|
24
|
+
if (hasText === hasTask) {
|
|
25
|
+
throw new EventDefinitionError("payload", `An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
|
|
26
|
+
}
|
|
27
|
+
if (hasText)
|
|
28
|
+
return { text: data.text };
|
|
29
|
+
try {
|
|
30
|
+
return { task: validateTaskContractInput(data.task) };
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new EventDefinitionError("task-template", `Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function parsePreAction(data, filename) {
|
|
37
|
+
if (!data.preAction)
|
|
38
|
+
return undefined;
|
|
39
|
+
if (!isPlainObject(data.preAction)) {
|
|
40
|
+
throw new EventDefinitionError("pre-action", `Invalid 'preAction' field in ${filename}, expected an object`);
|
|
41
|
+
}
|
|
42
|
+
const action = data.preAction;
|
|
43
|
+
if (action.type !== "bash") {
|
|
44
|
+
throw new EventDefinitionError("pre-action", `Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
|
|
45
|
+
}
|
|
46
|
+
if (typeof action.command !== "string" || action.command.trim().length === 0) {
|
|
47
|
+
throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
|
|
48
|
+
}
|
|
49
|
+
if (action.timeout !== undefined) {
|
|
50
|
+
if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
|
|
51
|
+
throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
type: "bash",
|
|
56
|
+
command: action.command,
|
|
57
|
+
...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export function parseScheduledEventContent(content, filename) {
|
|
61
|
+
let data;
|
|
62
|
+
try {
|
|
63
|
+
data = JSON.parse(content);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new EventDefinitionError("malformed", `Invalid JSON in ${filename}: ${errorMessage(error)}`);
|
|
67
|
+
}
|
|
68
|
+
if (!isPlainObject(data)) {
|
|
69
|
+
throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
|
|
70
|
+
}
|
|
71
|
+
const type = readRequiredString(data, "type", filename);
|
|
72
|
+
const channelId = readRequiredString(data, "channelId", filename);
|
|
73
|
+
const payload = parsePayload(data, filename);
|
|
74
|
+
const preAction = parsePreAction(data, filename);
|
|
75
|
+
switch (type) {
|
|
76
|
+
// Removed in spec 031 (D4): an event that fires the moment it is written is a
|
|
77
|
+
// self-triggering loop with no gate in front of it, and nothing in the runtime produced
|
|
78
|
+
// one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
|
|
79
|
+
// enforced, since the events directory is agent-writable.
|
|
80
|
+
case "immediate":
|
|
81
|
+
throw new EventDefinitionError("immediate", `Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
|
|
82
|
+
"or schedule a one-shot at least 2 minutes out via event_manage.");
|
|
83
|
+
case "one-shot": {
|
|
84
|
+
if (typeof data.at !== "string" || data.at.trim().length === 0) {
|
|
85
|
+
throw new EventDefinitionError("missing-field", `Missing 'at' field for one-shot event in ${filename}`);
|
|
86
|
+
}
|
|
87
|
+
return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
|
|
88
|
+
}
|
|
89
|
+
case "periodic": {
|
|
90
|
+
if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
|
|
91
|
+
throw new EventDefinitionError("missing-field", `Missing 'schedule' field for periodic event in ${filename}`);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
type,
|
|
95
|
+
channelId,
|
|
96
|
+
...payload,
|
|
97
|
+
schedule: data.schedule,
|
|
98
|
+
...(preAction ? { preAction } : {}),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
default:
|
|
102
|
+
throw new EventDefinitionError("unknown-type", `Unknown event type '${type}' in ${filename}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Stable, provenance-derived dispatch id (spec 031, D1).
|
|
107
|
+
*
|
|
108
|
+
* The identity of a wake is its *occurrence*, never the moment it happened to be executed.
|
|
109
|
+
* A one-shot keyed on its own `at` therefore lands on the same durable record whether it
|
|
110
|
+
* arrives via the outbox retry or via the post-restart file recovery path, so the two
|
|
111
|
+
* independent retry systems can no longer deliver the same occurrence twice. A live periodic
|
|
112
|
+
* occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
|
|
113
|
+
* while the next callback produces a genuinely new record.
|
|
114
|
+
*/
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scheduled-event shapes: the on-disk definition, history records and the injected callbacks.
|
|
3
|
+
* Types only, shared by validation, parsing and the watcher without forming an import cycle.
|
|
4
|
+
*/
|
|
5
|
+
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
6
|
+
import type { TaskCreateInput } from "../tasks/contract-input.js";
|
|
7
|
+
export interface EventAction {
|
|
8
|
+
type: "bash";
|
|
9
|
+
command: string;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* What an event delivers when it fires: a chat `text`, or a `task` template that spawns a fresh
|
|
14
|
+
* task instance (spec 052, D2). Exactly one is present — `parseScheduledEventContent` enforces it.
|
|
15
|
+
*/
|
|
16
|
+
export interface EventPayload {
|
|
17
|
+
text?: string;
|
|
18
|
+
task?: TaskCreateInput;
|
|
19
|
+
}
|
|
20
|
+
export interface OneShotEvent extends EventPayload {
|
|
21
|
+
type: "one-shot";
|
|
22
|
+
channelId: string;
|
|
23
|
+
at: string;
|
|
24
|
+
preAction?: EventAction;
|
|
25
|
+
}
|
|
26
|
+
export interface PeriodicEvent extends EventPayload {
|
|
27
|
+
type: "periodic";
|
|
28
|
+
channelId: string;
|
|
29
|
+
schedule: string;
|
|
30
|
+
preAction?: EventAction;
|
|
31
|
+
}
|
|
32
|
+
export type ScheduledEvent = OneShotEvent | PeriodicEvent;
|
|
33
|
+
export type EventHistoryAction = "loaded" | "scheduled" | "triggered" | "skipped" | "enqueued" | "queue_full" | "deleted" | "invalid" | "pre_action_started" | "pre_action_passed" | "pre_action_blocked" | "pre_action_failed" | "cancelled";
|
|
34
|
+
export type EventHistoryResult = "ok" | "error" | "skipped";
|
|
35
|
+
export interface EventHistoryRecord {
|
|
36
|
+
ts: string;
|
|
37
|
+
eventName: string;
|
|
38
|
+
eventPath: string;
|
|
39
|
+
eventType: ScheduledEvent["type"] | "unknown";
|
|
40
|
+
channelId?: string;
|
|
41
|
+
action: EventHistoryAction;
|
|
42
|
+
result: EventHistoryResult;
|
|
43
|
+
reason?: string;
|
|
44
|
+
schedule?: string;
|
|
45
|
+
at?: string;
|
|
46
|
+
nextRunAt?: string;
|
|
47
|
+
textPreview?: string;
|
|
48
|
+
preAction?: {
|
|
49
|
+
type: "bash";
|
|
50
|
+
command: string;
|
|
51
|
+
timeoutMs: number;
|
|
52
|
+
exitCode?: number | null;
|
|
53
|
+
durationMs?: number;
|
|
54
|
+
};
|
|
55
|
+
queue?: {
|
|
56
|
+
accepted: boolean;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** One occurrence of a template event asking for a task instance (spec 052, D2). */
|
|
60
|
+
export interface SpawnTaskRequest {
|
|
61
|
+
/** The event's name (filename without `.json`); becomes the instance's `origin`. */
|
|
62
|
+
eventName: string;
|
|
63
|
+
channelId: string;
|
|
64
|
+
template: TaskCreateInput;
|
|
65
|
+
/** The moment this occurrence was due — deterministic per occurrence, so a replay maps to the same instance. */
|
|
66
|
+
occurrence: Date;
|
|
67
|
+
}
|
|
68
|
+
export type SpawnTaskResult =
|
|
69
|
+
/** A new instance was created. */
|
|
70
|
+
{
|
|
71
|
+
outcome: "spawned";
|
|
72
|
+
id: string;
|
|
73
|
+
}
|
|
74
|
+
/** This occurrence's instance already exists: an idempotent replay. */
|
|
75
|
+
| {
|
|
76
|
+
outcome: "exists";
|
|
77
|
+
id: string;
|
|
78
|
+
}
|
|
79
|
+
/** Another instance of the same event is still running; the user was told. */
|
|
80
|
+
| {
|
|
81
|
+
outcome: "skipped";
|
|
82
|
+
id: string;
|
|
83
|
+
};
|
|
84
|
+
export interface EventsWatcherOptions {
|
|
85
|
+
historyPath?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Creates the task instance a template event asks for. Injected by the runtime so the events
|
|
88
|
+
* subsystem never reads or writes task files (spec 052, INV-8).
|
|
89
|
+
*/
|
|
90
|
+
spawnTask?: (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
|
|
91
|
+
/** Persist synthetic work before it enters the in-memory channel queue. */
|
|
92
|
+
dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
|
|
93
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|